recovery.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. """Durable state for Discord reconnect message recovery."""
  2. from __future__ import annotations
  3. import datetime as dt
  4. import logging
  5. import os
  6. import sqlite3
  7. import threading
  8. from contextlib import suppress
  9. from pathlib import Path
  10. from typing import Any, Callable
  11. from hermes_constants import get_hermes_home
  12. logger = logging.getLogger(__name__)
  13. _DB_FILENAME = "discord_message_recovery.db"
  14. _RETENTION_DAYS = 30
  15. class DiscordRecoveryStore:
  16. """Small profile-scoped SQLite ledger for completed Discord messages."""
  17. def __init__(self, hermes_home: Path | None = None) -> None:
  18. self._lock = threading.Lock()
  19. self._initialized = False
  20. self._hermes_home = Path(hermes_home or get_hermes_home())
  21. def path(self) -> Path:
  22. directory = self._hermes_home / "gateway"
  23. directory.mkdir(parents=True, exist_ok=True)
  24. return directory / _DB_FILENAME
  25. def call(self, fn: Callable[[sqlite3.Connection], Any], default: Any = None) -> Any:
  26. try:
  27. with self._lock:
  28. path = self.path()
  29. conn = sqlite3.connect(path, timeout=0.1)
  30. try:
  31. if not self._initialized:
  32. self._initialize(conn)
  33. self._initialized = True
  34. with suppress(OSError):
  35. os.chmod(path, 0o600)
  36. result = fn(conn)
  37. conn.commit()
  38. return result
  39. finally:
  40. conn.close()
  41. except Exception as exc:
  42. logger.warning("Discord recovery ledger unavailable: %s", exc)
  43. return default
  44. def _initialize(self, conn: sqlite3.Connection) -> None:
  45. from hermes_state_wal import apply_wal_with_fallback
  46. apply_wal_with_fallback(conn, db_label="discord_recovery.db")
  47. conn.executescript("""
  48. CREATE TABLE IF NOT EXISTS discord_messages (
  49. message_id TEXT PRIMARY KEY, channel_id TEXT, thread_id TEXT, parent_channel_id TEXT,
  50. author_id TEXT, created_at TEXT, status TEXT NOT NULL,
  51. replied INTEGER NOT NULL DEFAULT 0, emoji_ack INTEGER NOT NULL DEFAULT 0,
  52. outage_response INTEGER NOT NULL DEFAULT 0, response_message_id TEXT,
  53. attempts INTEGER NOT NULL DEFAULT 0, last_attempt_at TEXT, last_error TEXT,
  54. updated_at TEXT NOT NULL
  55. );
  56. CREATE TABLE IF NOT EXISTS discord_recovery_scans (
  57. scan_id TEXT PRIMARY KEY, started_at TEXT NOT NULL, completed_at TEXT, status TEXT NOT NULL,
  58. channels TEXT NOT NULL, window_seconds REAL NOT NULL, limit_count INTEGER NOT NULL,
  59. scanned INTEGER NOT NULL DEFAULT 0, missed INTEGER NOT NULL DEFAULT 0,
  60. dispatched INTEGER NOT NULL DEFAULT 0, error TEXT
  61. );
  62. CREATE TABLE IF NOT EXISTS discord_recovery_cursors (
  63. channel_id TEXT PRIMARY KEY, last_message_id TEXT NOT NULL, updated_at TEXT NOT NULL
  64. );
  65. """)
  66. cutoff = (dt.datetime.now(dt.UTC) - dt.timedelta(days=_RETENTION_DAYS)).isoformat()
  67. conn.execute("DELETE FROM discord_messages WHERE updated_at < ?", (cutoff,))
  68. conn.execute("DELETE FROM discord_recovery_scans WHERE COALESCE(completed_at, started_at) < ?", (cutoff,))
  69. conn.execute("DELETE FROM discord_recovery_cursors WHERE updated_at < ?", (cutoff,))