feat(fetcher): add SQLite db module with WAL, payload hashing, GC

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
shay
2026-04-17 16:25:05 -04:00
co-authored by Claude Sonnet 4.6
parent f0e6d9439e
commit 832f94c1b9
2 changed files with 186 additions and 0 deletions
+121
View File
@@ -0,0 +1,121 @@
"""SQLite repository for the fetcher service.
Single table: users (raw GitHub payloads keyed by username).
Uses WAL mode so concurrent readers don't block the writer.
"""
import hashlib
import json
import os
import sqlite3
from contextlib import contextmanager
from datetime import datetime, timedelta
from typing import Optional
from . import config
DB_PATH = config.DB_PATH
SCHEMA_SQL = """
CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
data_json TEXT NOT NULL,
payload_hash TEXT NOT NULL,
fetched_at TEXT NOT NULL,
last_requested_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_users_fetched_at ON users(fetched_at);
CREATE INDEX IF NOT EXISTS idx_users_last_requested_at ON users(last_requested_at);
"""
def _now() -> str:
return datetime.utcnow().isoformat(timespec="seconds") + "Z"
@contextmanager
def _connect():
os.makedirs(os.path.dirname(DB_PATH) or ".", exist_ok=True)
conn = sqlite3.connect(DB_PATH, timeout=10)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA foreign_keys=ON")
conn.execute("PRAGMA busy_timeout=5000")
try:
yield conn
conn.commit()
finally:
conn.close()
def init_db() -> None:
with _connect() as c:
c.executescript(SCHEMA_SQL)
c.commit()
def payload_hash(data: dict) -> str:
canonical = json.dumps(data, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def upsert_user(username: str, data: dict) -> str:
h = payload_hash(data)
now = _now()
with _connect() as c:
c.execute(
"""INSERT INTO users(username, data_json, payload_hash, fetched_at, last_requested_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(username) DO UPDATE SET
data_json = excluded.data_json,
payload_hash = excluded.payload_hash,
fetched_at = excluded.fetched_at""",
(username, json.dumps(data), h, now, now),
)
c.commit()
return h
def get_user(username: str) -> Optional[dict]:
"""Returns {data, payload_hash, fetched_at, last_requested_at} or None. Updates last_requested_at."""
now = _now()
with _connect() as c:
row = c.execute(
"SELECT data_json, payload_hash, fetched_at, last_requested_at FROM users WHERE username=?",
(username,),
).fetchone()
if row is None:
return None
c.execute("UPDATE users SET last_requested_at=? WHERE username=?", (now, username))
c.commit()
return {
"data": json.loads(row["data_json"]),
"payload_hash": row["payload_hash"],
"fetched_at": row["fetched_at"],
"last_requested_at": now,
}
def delete_stale(days: int) -> int:
cutoff = (datetime.utcnow() - timedelta(days=days)).isoformat(timespec="seconds") + "Z"
with _connect() as c:
cur = c.execute("DELETE FROM users WHERE last_requested_at < ?", (cutoff,))
c.commit()
return cur.rowcount
def users_due_for_refresh(hours: int, active_within_days: int) -> list[str]:
"""Return usernames with fetched_at older than `hours` and last_requested_at within `active_within_days`."""
stale_before = (datetime.utcnow() - timedelta(hours=hours)).isoformat(timespec="seconds") + "Z"
active_after = (datetime.utcnow() - timedelta(days=active_within_days)).isoformat(timespec="seconds") + "Z"
with _connect() as c:
rows = c.execute(
"SELECT username FROM users WHERE fetched_at < ? AND last_requested_at > ?",
(stale_before, active_after),
).fetchall()
return [r["username"] for r in rows]
def list_usernames() -> list[str]:
with _connect() as c:
return [r["username"] for r in c.execute("SELECT username FROM users ORDER BY username").fetchall()]
+65
View File
@@ -0,0 +1,65 @@
import os
import tempfile
import pytest
from src import db as dbmod
@pytest.fixture
def tmp_db(monkeypatch):
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, "t.db")
monkeypatch.setattr(dbmod, "DB_PATH", path)
dbmod.init_db()
yield path
def test_init_creates_schema_with_wal(tmp_db):
with dbmod._connect() as c:
mode = c.execute("PRAGMA journal_mode").fetchone()[0]
assert mode.lower() == "wal"
cols = [r[1] for r in c.execute("PRAGMA table_info(users)").fetchall()]
assert set(cols) == {"username", "data_json", "payload_hash",
"fetched_at", "last_requested_at"}
def test_upsert_and_get_round_trip(tmp_db):
dbmod.upsert_user("alice", {"user": {"login": "alice"}, "repos": []})
row = dbmod.get_user("alice")
assert row["data"]["user"]["login"] == "alice"
assert row["payload_hash"]
assert row["fetched_at"]
def test_payload_hash_is_deterministic_and_changes_on_diff():
h1 = dbmod.payload_hash({"a": 1, "b": 2})
h2 = dbmod.payload_hash({"b": 2, "a": 1})
h3 = dbmod.payload_hash({"a": 1, "b": 3})
assert h1 == h2
assert h1 != h3
def test_get_updates_last_requested_at(tmp_db):
dbmod.upsert_user("alice", {"user": {"login": "alice"}})
first = dbmod.get_user("alice")["last_requested_at"]
import time; time.sleep(1.1)
second = dbmod.get_user("alice")["last_requested_at"]
assert second > first
def test_delete_stale_removes_old_rows(tmp_db):
dbmod.upsert_user("ghost", {"user": {"login": "ghost"}})
# Manually backdate last_requested_at
with dbmod._connect() as c:
c.execute("UPDATE users SET last_requested_at='2020-01-01T00:00:00Z' WHERE username='ghost'")
removed = dbmod.delete_stale(days=7)
assert removed == 1
assert dbmod.get_user("ghost") is None
def test_users_due_for_refresh(tmp_db):
dbmod.upsert_user("alice", {"user": {"login": "alice"}})
# Backdate fetched_at so alice is due
with dbmod._connect() as c:
c.execute("UPDATE users SET fetched_at='2020-01-01T00:00:00Z' WHERE username='alice'")
due = dbmod.users_due_for_refresh(hours=24, active_within_days=7)
assert "alice" in due