dead_targets.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. """Persistent registry of delivery targets confirmed unreachable. Re-sending to a permanently gone chat
  2. (deleted group, bot kicked/blocked, deactivated user) every cron tick wastes flood-control budget; delivery
  3. short-circuits targets proven dead and any later successful send clears the flag. Only *whole-chat* deaths
  4. (``forbidden``, chat-level ``not_found``) are recorded: adapters self-heal thread/topic-level ``not_found``
  5. by retrying without ``reply_to``. Storage is a per-profile JSON file; reads/writes are best-effort (a
  6. corrupt or unwritable file degrades to in-memory-only rather than raising on the delivery path).
  7. """
  8. from __future__ import annotations
  9. import json
  10. import logging
  11. import threading
  12. import time
  13. from pathlib import Path
  14. from typing import Dict, Optional
  15. from hermes_cli.config import get_hermes_home
  16. logger = logging.getLogger(__name__)
  17. # classify_send_error kinds meaning the whole chat is unreachable (not transient / thread-level).
  18. _DEAD_ERROR_KINDS = frozenset({"forbidden", "not_found"})
  19. def _normalize(platform: str, chat_id: str) -> str:
  20. """Canonical key for a (platform, chat_id) pair."""
  21. return f"{str(platform).strip().lower()}:{str(chat_id).strip()}"
  22. def classify_dead_error(error_text: Optional[str]) -> Optional[str]:
  23. """Best-effort dead-target error_kind from a raised error's text, else None. ``_deliver_to_platform``
  24. raises on hard failure (no SendResult), so ``deliver()`` only has the exception string. ``not_found``
  25. collapses chat-level and thread/topic/message-level failures: only a whole-chat not_found means the
  26. target is dead — a deleted forum topic or edited-away message must not mark the entire chat dead."""
  27. if not error_text:
  28. return None
  29. try:
  30. from .platforms.base import classify_send_error, is_chat_level_not_found
  31. except Exception: # pragma: no cover - import guard
  32. return None
  33. kind = classify_send_error(None, error_text=error_text)
  34. dead = kind in _DEAD_ERROR_KINDS and (kind != "not_found" or is_chat_level_not_found(error_text=error_text))
  35. return kind if dead else None
  36. class DeadTargetRegistry:
  37. """Thread-safe, persistent set of confirmed-dead targets keyed ``platform:chat_id``. Each entry stores
  38. reason + timestamp for observability; :meth:`clear` (called on a successful send) removes the flag."""
  39. def __init__(self, path: Optional[Path] = None) -> None:
  40. self._lock = threading.RLock()
  41. self._dead: dict[str, dict[str, object]] = {}
  42. self._path = path if path is not None else get_hermes_home() / "gateway" / "dead_targets.json"
  43. try:
  44. if self._path.exists():
  45. raw = json.loads(self._path.read_text(encoding="utf-8-sig"))
  46. if isinstance(raw, dict):
  47. # Only keep well-shaped entries.
  48. self._dead = {
  49. k: v for k, v in raw.items() if isinstance(v, dict)
  50. }
  51. except (OSError, ValueError) as exc:
  52. logger.debug("dead_targets: could not load %s (%s) — starting empty", self._path, exc)
  53. def _flush_locked(self) -> None:
  54. try:
  55. self._path.parent.mkdir(parents=True, exist_ok=True)
  56. tmp = self._path.with_suffix(self._path.suffix + ".tmp")
  57. tmp.write_text(json.dumps(self._dead, indent=2), encoding="utf-8")
  58. tmp.replace(self._path)
  59. except OSError as exc: # best-effort: keep in-memory state, never break delivery
  60. logger.debug("dead_targets: could not persist %s (%s)", self._path, exc)
  61. def is_dead(self, platform: str, chat_id: Optional[str]) -> bool:
  62. with self._lock:
  63. return bool(chat_id) and _normalize(platform, chat_id) in self._dead
  64. def mark_dead(self, platform: str, chat_id: Optional[str], reason: str = "") -> bool:
  65. """Record a target as confirmed-dead. Returns True if newly added."""
  66. if not chat_id:
  67. return False
  68. key = _normalize(platform, chat_id)
  69. with self._lock:
  70. existed = key in self._dead
  71. self._dead[key] = {"platform": str(platform).strip().lower(), "chat_id": str(chat_id),
  72. "reason": str(reason)[:200], "marked_at": time.time()}
  73. self._flush_locked()
  74. if not existed:
  75. logger.info("dead_targets: marked %s as unreachable (%s) — future deliveries "
  76. "to this target will be skipped until a send succeeds", key, reason or "no reason given")
  77. return not existed
  78. def clear(self, platform: str, chat_id: Optional[str]) -> bool:
  79. """Remove a target's dead flag (self-healing). Returns True if it was set."""
  80. if not chat_id:
  81. return False
  82. key = _normalize(platform, chat_id)
  83. with self._lock:
  84. if self._dead.pop(key, None) is None:
  85. return False
  86. self._flush_locked()
  87. logger.info("dead_targets: cleared %s (delivery succeeded again)", key)
  88. return True