sqlite_store.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. from __future__ import annotations
  2. import json
  3. import sqlite3
  4. from dataclasses import dataclass
  5. from datetime import datetime, timezone, timedelta
  6. from pathlib import Path
  7. from typing import Any
  8. @dataclass
  9. class ClusterRow:
  10. cluster_id: str
  11. topic: str
  12. payload: dict
  13. updated_at: datetime
  14. class SQLiteClusterStore:
  15. def __init__(self, db_path: str | Path):
  16. self.db_path = str(db_path)
  17. self._init_db()
  18. def _conn(self) -> sqlite3.Connection:
  19. return sqlite3.connect(self.db_path)
  20. def _init_db(self) -> None:
  21. Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
  22. with self._conn() as conn:
  23. conn.execute(
  24. """
  25. CREATE TABLE IF NOT EXISTS clusters (
  26. cluster_id TEXT PRIMARY KEY,
  27. topic TEXT NOT NULL,
  28. payload TEXT NOT NULL,
  29. updated_at TEXT NOT NULL,
  30. summary_payload TEXT,
  31. summary_updated_at TEXT
  32. )
  33. """
  34. )
  35. # If the table already exists without the summary columns,
  36. # add them (SQLite-friendly incremental migrations).
  37. for col_def in [
  38. "summary_payload TEXT",
  39. "summary_updated_at TEXT",
  40. ]:
  41. col = col_def.split()[0]
  42. try:
  43. conn.execute(f"ALTER TABLE clusters ADD COLUMN {col_def}")
  44. except sqlite3.OperationalError:
  45. pass
  46. conn.execute(
  47. "CREATE INDEX IF NOT EXISTS idx_clusters_topic ON clusters(topic)"
  48. )
  49. conn.execute(
  50. """
  51. CREATE TABLE IF NOT EXISTS feed_state (
  52. feed_key TEXT PRIMARY KEY,
  53. last_hash TEXT NOT NULL,
  54. updated_at TEXT NOT NULL
  55. )
  56. """
  57. )
  58. def upsert_clusters(self, clusters: list[dict], topic: str) -> None:
  59. now = datetime.now(timezone.utc)
  60. with self._conn() as conn:
  61. for c in clusters:
  62. cluster_id = c["cluster_id"]
  63. payload = json.dumps(c, ensure_ascii=False)
  64. conn.execute(
  65. "INSERT INTO clusters(cluster_id, topic, payload, updated_at) VALUES(?,?,?,?) "
  66. "ON CONFLICT(cluster_id) DO UPDATE SET topic=excluded.topic, payload=excluded.payload, updated_at=excluded.updated_at",
  67. (cluster_id, topic, payload, now.isoformat()),
  68. )
  69. def upsert_cluster_summary(
  70. self,
  71. cluster_id: str,
  72. summary_payload: dict,
  73. ) -> None:
  74. now = datetime.now(timezone.utc).isoformat()
  75. with self._conn() as conn:
  76. conn.execute(
  77. "INSERT INTO clusters(cluster_id, topic, payload, updated_at, summary_payload, summary_updated_at) "
  78. "VALUES(?,?,?,?,?,?) "
  79. "ON CONFLICT(cluster_id) DO UPDATE SET "
  80. "summary_payload=excluded.summary_payload, summary_updated_at=excluded.summary_updated_at",
  81. (
  82. cluster_id,
  83. "", # topic not used for update
  84. json.dumps({}, ensure_ascii=False),
  85. now,
  86. json.dumps(summary_payload, ensure_ascii=False),
  87. now,
  88. ),
  89. )
  90. def get_cluster_summary(self, cluster_id: str, ttl_hours: float) -> dict | None:
  91. cutoff = datetime.now(timezone.utc) - timedelta(hours=ttl_hours)
  92. cutoff_iso = cutoff.isoformat()
  93. with self._conn() as conn:
  94. cur = conn.execute(
  95. "SELECT summary_payload, summary_updated_at FROM clusters "
  96. "WHERE cluster_id=? AND summary_updated_at >= ?",
  97. (cluster_id, cutoff_iso),
  98. )
  99. row = cur.fetchone()
  100. if not row or not row[0]:
  101. return None
  102. return json.loads(row[0])
  103. def get_latest_clusters(self, topic: str, ttl_hours: float, limit: int) -> list[dict]:
  104. cutoff = datetime.now(timezone.utc) - timedelta(hours=ttl_hours)
  105. cutoff_iso = cutoff.isoformat()
  106. with self._conn() as conn:
  107. cur = conn.execute(
  108. "SELECT payload FROM clusters WHERE topic=? AND updated_at >= ? ORDER BY updated_at DESC LIMIT ?",
  109. (topic, cutoff_iso, int(limit)),
  110. )
  111. rows = [json.loads(r[0]) for r in cur.fetchall()]
  112. return rows
  113. def get_latest_clusters_all_topics(self, ttl_hours: float, limit: int) -> list[dict]:
  114. cutoff = datetime.now(timezone.utc) - timedelta(hours=ttl_hours)
  115. cutoff_iso = cutoff.isoformat()
  116. with self._conn() as conn:
  117. cur = conn.execute(
  118. "SELECT payload FROM clusters WHERE updated_at >= ? ORDER BY updated_at DESC LIMIT ?",
  119. (cutoff_iso, int(limit)),
  120. )
  121. return [json.loads(r[0]) for r in cur.fetchall()]
  122. def get_cluster_by_id(self, cluster_id: str) -> dict | None:
  123. with self._conn() as conn:
  124. cur = conn.execute(
  125. "SELECT payload FROM clusters WHERE cluster_id=?",
  126. (cluster_id,),
  127. )
  128. row = cur.fetchone()
  129. return json.loads(row[0]) if row else None
  130. def get_feed_hash(self, feed_key: str) -> str | None:
  131. with self._conn() as conn:
  132. cur = conn.execute(
  133. "SELECT last_hash FROM feed_state WHERE feed_key=?",
  134. (feed_key,),
  135. )
  136. row = cur.fetchone()
  137. return row[0] if row else None
  138. def set_feed_hash(self, feed_key: str, last_hash: str) -> None:
  139. now = datetime.now(timezone.utc).isoformat()
  140. with self._conn() as conn:
  141. conn.execute(
  142. "INSERT INTO feed_state(feed_key, last_hash, updated_at) VALUES(?,?,?) "
  143. "ON CONFLICT(feed_key) DO UPDATE SET last_hash=excluded.last_hash, updated_at=excluded.updated_at",
  144. (feed_key, last_hash, now),
  145. )
  146. def get_feed_state(self, feed_key: str) -> dict | None:
  147. with self._conn() as conn:
  148. cur = conn.execute(
  149. "SELECT last_hash, updated_at FROM feed_state WHERE feed_key=?",
  150. (feed_key,),
  151. )
  152. row = cur.fetchone()
  153. if not row:
  154. return None
  155. return {"last_hash": row[0], "updated_at": row[1]}