Coverage for dao/notification_deliveries_dao.py: 28.85%
46 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:10 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:10 +0000
1"""
2Notification Deliveries Data Access Object (SB-1603).
4One row per (channel, match event). Claiming the row before posting is what
5stops a resent event from posting twice.
7Holds no destination. Errors are logged by type only.
8"""
10import structlog
12from dao.base_dao import BaseDAO
14logger = structlog.get_logger()
16TABLE = "notification_deliveries"
17_UNIQUE_VIOLATION = "23505"
18_MAX_ERROR_LENGTH = 500
21class DeliveryLedgerError(Exception):
22 """The ledger could not be read or written. Safe to log."""
25class NotificationDeliveriesDAO(BaseDAO):
26 """Data access for the notification delivery ledger."""
28 def claim(
29 self,
30 channel_id: int,
31 event_key: str,
32 content: str | None = None,
33 match_id: int | None = None,
34 event_type: str | None = None,
35 ) -> int | None:
36 """Reserve this event on this channel, keeping the message for a retry (SB-1604).
38 Returns the new delivery id, or None if it was already claimed.
39 Raises DeliveryLedgerError if the ledger cannot answer.
40 """
41 try:
42 row = {
43 "channel_id": channel_id,
44 "event_key": event_key,
45 "content": content,
46 "match_id": match_id,
47 "event_type": event_type,
48 }
49 return self.client.table(TABLE).insert(row).execute().data[0]["id"]
50 except Exception as exc:
51 if _UNIQUE_VIOLATION in str(exc):
52 return None
53 logger.error("dao_notification_deliveries_claim_failed", error_type=type(exc).__name__)
54 raise DeliveryLedgerError("Could not claim notification delivery") from None
56 def latest_for(self, channel_ids: list[int]) -> dict[int, dict] | None:
57 """Each channel's most recent delivery, keyed by channel id.
59 A channel with none is absent from the result. None means the ledger
60 could not be read, which is not the same as "nothing delivered yet".
61 One indexed query per channel: a scope holds a handful.
62 """
63 latest: dict[int, dict] = {}
64 try:
65 for channel_id in channel_ids:
66 rows = (
67 self.client.table(TABLE)
68 .select("channel_id, status, error, created_at, updated_at")
69 .eq("channel_id", channel_id)
70 .order("created_at", desc=True)
71 .limit(1)
72 .execute()
73 .data
74 )
75 if rows:
76 latest[channel_id] = rows[0]
77 except Exception as exc:
78 logger.error("dao_notification_deliveries_read_failed", error_type=type(exc).__name__)
79 return None
80 return latest
82 def mark_sent(self, delivery_id: int, message_ref: str | None) -> None:
83 """Record a successful post."""
84 self._finish(delivery_id, {"status": "sent", "provider_message_ref": message_ref})
86 def mark_failed(self, delivery_id: int, error: str) -> None:
87 """Record a failed post. `error` must already be safe to store."""
88 self._finish(delivery_id, {"status": "failed", "error": error[:_MAX_ERROR_LENGTH]})
90 def mark_retry(self, delivery_id: int, error: str, next_attempt_at: str) -> None:
91 """Leave the post pending for the retry worker, due at `next_attempt_at` (ISO)."""
92 self._finish(delivery_id, {"error": error[:_MAX_ERROR_LENGTH], "next_attempt_at": next_attempt_at})
94 def claim_due(self, limit: int, lease_seconds: int, stale_seconds: int) -> list[dict]:
95 """Atomically take up to `limit` due posts for the retry worker (SB-1604).
97 Each comes back with its attempt already counted and leased for
98 `lease_seconds`, so a worker that dies mid-send leaves it to be retried.
99 Raises DeliveryLedgerError when the ledger cannot answer.
100 """
101 try:
102 response = self.client.rpc(
103 "claim_due_notification_deliveries",
104 {"p_limit": limit, "p_lease_seconds": lease_seconds, "p_stale_seconds": stale_seconds},
105 ).execute()
106 return response.data or []
107 except Exception as exc:
108 logger.error("dao_notification_deliveries_claim_due_failed", error_type=type(exc).__name__)
109 raise DeliveryLedgerError("Could not read due notification deliveries") from None
111 def _finish(self, delivery_id: int, fields: dict) -> None:
112 """Best-effort: the message outcome is already decided by this point."""
113 try:
114 self.client.table(TABLE).update(fields).eq("id", delivery_id).execute()
115 except Exception as exc:
116 logger.error("dao_notification_deliveries_update_failed", error_type=type(exc).__name__)