signal-bot/signal_bot/store.py
Krzysztof kuhy Rudnicki 4bbb1e1519
Some checks are pending
CI / check (push) Waiting to run
feat: name every release after a pope, and tell the group when one lands
Release n is pope n, so the version is a fact about the ordinal rather than a
judgement about the size of a change. The constraint that fixes the scheme is
Jan Pawel II at 2.13.7: eight patches per minor with majors opening at ordinals
33 and 153 gives (264 - 153) = 13 * 8 + 7 exactly, and both earlier majors
happen to divide evenly by eight too, so no bracket needs a fudge factor. The
anchors are not arbitrary -- 33 is Sylwester I, pope through the Edict of Milan
and Nicaea, and 153 is Wiktor II, the first pope elected after the 1054 schism.

popes.json is scraped by tool/gen_popes.py rather than recalled, because
antipopes, Benedykt IX's three separate reigns and the Stefan II question all
shift the count and being wrong by one moves Jan Pawel II off 2.13.7 silently.
The generator refuses to write a list that is not 267 contiguous entries with
Jan Pawel II at 264. A second, independent parse of the same page agreed on
every ordinal, which is the only reason to believe either.

On startup each watched group is told about the releases it has not seen. A
group with no record has seen none of them, so the first announcement starts at
0.0.0 "Swiety Piotr Apostol" rather than skipping to whatever is current --
watching the ladder start at Peter is the point of naming releases after popes.
A group added years from now would otherwise be handed the whole backlog, so
the message is capped at ten releases and says how many it left out. The
version is recorded before the message is sent: with Restart=always and
RestartSec=5, a crash between the two would re-announce on every restart, and a
missed announcement is far cheaper than a looping one.

DOCS-changelog.md is the single source -- the bot parses it, so there is no
second machine-readable copy to drift. It is DOCS-, not CHANGELOG.md, because
the md-naming gate allows four namespaces and that is not one of them.

Deliberately NOT bumping SCHEMA_VERSION for the new group_meta table:
_apply_schema drops every table on a bump, so bumping to add a table would have
thrown away the live tallies to gain nothing. Verified against the real
database -- group_meta appeared and all four counts survived the restart.

The schema moves to its own module so store.py stays under the 250-line cap,
and /healthz now names the build, because there was previously no way to ask a
running bot which version it is.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-29 22:51:20 +02:00

218 lines
8.9 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""SQLite persistence for tallies, cooldowns, daily limits and votes.
Everything the bot remembers lives here so a restart before the daily report
does not lose the day. The original bot kept all of it in module globals.
"""
from __future__ import annotations
import contextlib
import sqlite3
from dataclasses import dataclass
from typing import TYPE_CHECKING, Self
from signal_bot.schema import SCHEMA, SCHEMA_VERSION, TABLES
if TYPE_CHECKING:
from collections.abc import Iterator
from types import TracebackType
@dataclass(frozen=True, slots=True)
class Tally:
"""One person's message count for the current reporting period."""
uuid: str
display_name: str
count: int
class Store:
"""Thin, synchronous SQLite wrapper. All state the bot keeps lives here."""
def __init__(self, path: str) -> None:
"""Open (or create) the database at path and apply the schema."""
self._conn = sqlite3.connect(path)
self._conn.row_factory = sqlite3.Row
self._apply_schema()
def _apply_schema(self) -> None:
"""Create the tables, rebuilding them when the file predates them.
``CREATE TABLE IF NOT EXISTS`` is a no-op against a table that
already exists with the wrong columns, so a database written before
the group_id key would survive startup untouched and then fail on
every single INSERT -- a bot that starts clean and answers nothing.
PRAGMA user_version is the only thing that notices, because it is
the only part of the file that records which shape it holds.
The old rows are dropped rather than migrated: they carry no group,
and inventing one would silently attribute a whole day's counts to
the wrong conversation.
"""
version = int(self._conn.execute("PRAGMA user_version").fetchone()[0])
if version < SCHEMA_VERSION:
for table in TABLES:
self._conn.execute(f"DROP TABLE IF EXISTS {table}")
self._conn.executescript(SCHEMA)
self._conn.execute(f"PRAGMA user_version = {SCHEMA_VERSION}")
self._conn.commit()
def __enter__(self) -> Self:
"""Enter a context manager that closes the connection on exit."""
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
"""Close the underlying connection."""
self.close()
def close(self) -> None:
"""Close the underlying connection."""
self._conn.close()
def forget_group(self, group_id: str) -> None:
"""Drop every row belonging to one group.
Called when the bot is removed from a group, so that being added
back starts a fresh tally and a clean cooldown rather than
resurrecting whatever was true whenever it was last in there.
"""
# Spelled out rather than looped over _TABLES: an f-string here is a
# SQL-injection shape even when the input is a module constant, and
# the repo does not take lint suppressions. test_forget_group_clears
# _every_table is what keeps this list in step with the schema.
self._conn.execute("DELETE FROM message_counts WHERE group_id = ?", (group_id,))
self._conn.execute("DELETE FROM command_uses WHERE group_id = ?", (group_id,))
self._conn.execute("DELETE FROM daily_uses WHERE group_id = ?", (group_id,))
self._conn.execute("DELETE FROM votes WHERE group_id = ?", (group_id,))
self._conn.execute("DELETE FROM group_meta WHERE group_id = ?", (group_id,))
self._conn.commit()
# -- per-group key/value state -----------------------------------------
def meta(self, group_id: str, key: str) -> str | None:
"""Return a stored value for one group, or None if never set."""
row = self._conn.execute(
"SELECT value FROM group_meta WHERE group_id = ? AND key = ?",
(group_id, key),
).fetchone()
return None if row is None else str(row["value"])
def set_meta(self, group_id: str, key: str, value: str) -> None:
"""Store a value for one group, replacing any previous one."""
self._conn.execute(
"INSERT INTO group_meta (group_id, key, value) VALUES (?, ?, ?) "
"ON CONFLICT(group_id, key) DO UPDATE SET value = excluded.value",
(group_id, key, value),
)
self._conn.commit()
# -- message tallies ---------------------------------------------------
def increment(self, group_id: str, uuid: str, display_name: str) -> None:
"""Add one to a person's tally in one group, creating the row when new."""
self._conn.execute(
"""
INSERT INTO message_counts (group_id, uuid, display_name, count)
VALUES (?, ?, ?, 1)
ON CONFLICT(group_id, uuid) DO UPDATE SET
count = count + 1,
display_name = excluded.display_name
""",
(group_id, uuid, display_name),
)
self._conn.commit()
def tallies(self, group_id: str) -> list[Tally]:
"""Return one group's tallies, highest count first."""
rows = self._conn.execute(
"SELECT uuid, display_name, count FROM message_counts "
"WHERE group_id = ? ORDER BY count DESC, display_name ASC",
(group_id,),
).fetchall()
return [Tally(r["uuid"], r["display_name"], r["count"]) for r in rows]
def reset_tallies(self, group_id: str) -> None:
"""Clear one group's tallies, as its daily report does after publishing."""
self._conn.execute("DELETE FROM message_counts WHERE group_id = ?", (group_id,))
self._conn.commit()
# -- per-group, per-user, per-command rate limiting --------------------
def record_use(self, group_id: str, user_uuid: str, command: str, now: float, day: str) -> None:
"""Record one successful use for both cooldown and daily-limit checks."""
self._conn.execute(
"INSERT INTO command_uses (group_id, user_uuid, command, used_at) "
"VALUES (?, ?, ?, ?) "
"ON CONFLICT(group_id, user_uuid, command) DO UPDATE SET used_at = excluded.used_at",
(group_id, user_uuid, command, now),
)
self._conn.execute(
"""
INSERT INTO daily_uses (group_id, user_uuid, command, day, uses)
VALUES (?, ?, ?, ?, 1)
ON CONFLICT(group_id, user_uuid, command, day) DO UPDATE SET uses = uses + 1
""",
(group_id, user_uuid, command, day),
)
self._conn.commit()
def last_used(self, group_id: str, user_uuid: str, command: str) -> float | None:
"""Return when this user last ran this command in this group, or None."""
row = self._conn.execute(
"SELECT used_at FROM command_uses WHERE group_id = ? AND user_uuid = ? AND command = ?",
(group_id, user_uuid, command),
).fetchone()
return None if row is None else float(row["used_at"])
def uses_today(self, group_id: str, user_uuid: str, command: str, day: str) -> int:
"""Return how often this user ran this command in this group that day."""
row = self._conn.execute(
"SELECT uses FROM daily_uses "
"WHERE group_id = ? AND user_uuid = ? AND command = ? AND day = ?",
(group_id, user_uuid, command, day),
).fetchone()
return 0 if row is None else int(row["uses"])
# -- vote gating -------------------------------------------------------
def add_vote(self, group_id: str, command: str, voter_uuid: str, now: float) -> None:
"""Record one vote, ignoring a repeat vote from the same person."""
self._conn.execute(
"INSERT INTO votes (group_id, command, voter_uuid, voted_at) VALUES (?, ?, ?, ?) "
"ON CONFLICT(group_id, command, voter_uuid) DO NOTHING",
(group_id, command, voter_uuid, now),
)
self._conn.commit()
def count_votes(self, group_id: str, command: str, not_before: float) -> int:
"""Return how many votes for command in this group are still in the window."""
row = self._conn.execute(
"SELECT COUNT(*) AS n FROM votes WHERE group_id = ? AND command = ? AND voted_at >= ?",
(group_id, command, not_before),
).fetchone()
return int(row["n"])
def clear_votes(self, group_id: str, command: str) -> None:
"""Drop every vote for a command in one group, after it fires or expires."""
self._conn.execute(
"DELETE FROM votes WHERE group_id = ? AND command = ?", (group_id, command)
)
self._conn.commit()
@contextlib.contextmanager
def open_store(path: str) -> Iterator[Store]:
"""Open a Store as a context manager."""
store = Store(path)
try:
yield store
finally:
store.close()