Coverage for services/email_delivery.py: 97.59%
63 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"""
2Email delivery status from Resend webhooks: invitations (SB-1814) and
3Support Inbox replies (SB-1821).
5The invite send and the support-reply send store Resend's email id on their
6row (invitations / outbound email_messages); the webhook handler hands every
7delivery event here. Pure helpers decide what an event
8means and whether it may overwrite what is already recorded;
9record_delivery_event does the lookup and a compare-and-set write.
11Unknown email ids are routine, not errors: password resets, and invites or
12replies sent before tracking existed, all produce events too.
13"""
15from __future__ import annotations
17from datetime import UTC, datetime
18from typing import Any
20import structlog
22from services.email_service import _mask
24logger = structlog.get_logger(__name__)
26# Resend event type → email_status (invitations and email_messages). email.opened, email.clicked
27# and email.scheduled are deliberately absent: they say nothing about delivery.
28EVENT_STATUS: dict[str, str] = {
29 "email.sent": "sent",
30 "email.delivery_delayed": "delayed",
31 "email.delivered": "delivered",
32 "email.bounced": "bounced",
33 "email.complained": "complained",
34 "email.failed": "failed",
35 "email.suppressed": "suppressed",
36}
38# Events can arrive late or out of order, and Resend retries. A status only
39# replaces a lower-ranked one: delivered never overwrites bounced, while a
40# complaint after delivery still wins. The final outcomes share a rank, so the
41# first one recorded stays.
42_RANK: dict[str, int] = {
43 "sent": 0,
44 "delayed": 1,
45 "delivered": 2,
46 "bounced": 3,
47 "complained": 3,
48 "failed": 3,
49 "suppressed": 3,
50}
52_DETAIL_MAX = 60
55def status_for_event(event_type: str | None) -> str | None:
56 """The email_status an event type maps to, or None for one we ignore."""
57 return EVENT_STATUS.get(event_type or "")
60def should_apply(current: str | None, new: str) -> bool:
61 """Whether `new` may replace the recorded `current` status."""
62 if current is None:
63 return True
64 return _RANK[new] > _RANK.get(current, -1)
67def bounce_detail(data: dict[str, Any]) -> str | None:
68 """Short generic bounce reason, e.g. "Permanent: Suppressed".
70 Built only from the bounce type and subType. bounce.message is the raw
71 SMTP diagnostic, which can carry addresses and server internals, and is
72 never stored.
73 """
74 bounce = data.get("bounce")
75 if not isinstance(bounce, dict):
76 return None
77 parts = [str(p).strip() for p in (bounce.get("type"), bounce.get("subType")) if p]
78 detail = ": ".join(p for p in parts if p)
79 return detail[:_DETAIL_MAX] or None
82def _first_recipient(data: dict[str, Any]) -> str | None:
83 to = data.get("to")
84 if isinstance(to, list) and to: 84 ↛ 86line 84 didn't jump to line 86 because the condition on line 84 was always true
85 return str(to[0])
86 return to if isinstance(to, str) else None
89# Where a Resend email id can belong, in lookup order: (table, extra filters,
90# the log key for the row id). Invitations first, so their behaviour is
91# exactly what it was before support replies were tracked (SB-1821).
92_TARGETS: tuple[tuple[str, dict[str, str], str], ...] = (
93 ("invitations", {}, "invitation_id"),
94 ("email_messages", {"direction": "outbound"}, "message_row_id"),
95)
98def _find_target(client: Any, email_id: str) -> tuple[str, dict[str, str], str, dict[str, Any]] | None:
99 """The first tracked row carrying this Resend email id, with its table."""
100 for table, filters, id_key in _TARGETS:
101 query = client.table(table).select("id, email_status").eq("resend_email_id", email_id)
102 for col, value in filters.items():
103 query = query.eq(col, value)
104 response = query.limit(1).execute()
105 if response.data:
106 return table, filters, id_key, response.data[0]
107 return None
110def record_delivery_event(client: Any, event: dict[str, Any]) -> dict[str, Any]:
111 """Apply one Resend delivery event to the invitation or support reply it
112 belongs to.
114 Returns the webhook response body. Never raises for an event we cannot
115 use (unknown type, no email id, no matching row): Resend disables an
116 endpoint that keeps failing, so those are all 200 "ignored". Database
117 errors do propagate, so Resend retries a transient failure.
118 """
119 event_type = event.get("type")
120 new_status = status_for_event(event_type)
121 data = event.get("data") or {}
122 email_id = data.get("email_id")
123 if not new_status or not email_id:
124 logger.info("email_delivery_ignored_event", event_type=event_type)
125 return {"status": "ignored", "event_type": event_type}
127 recipient = _mask(_first_recipient(data))
128 target = _find_target(client, email_id)
129 if target is None:
130 logger.info(
131 "email_delivery_no_match",
132 event_type=event_type,
133 email_id=email_id,
134 recipient=recipient,
135 )
136 return {"status": "ignored", "event_type": event_type}
138 table, filters, id_key, row = target
139 current = row.get("email_status")
140 if not should_apply(current, new_status):
141 logger.info(
142 "email_delivery_unchanged",
143 table=table,
144 current=current,
145 event_status=new_status,
146 recipient=recipient,
147 **{id_key: row["id"]},
148 )
149 return {"status": "unchanged", "email_status": current}
151 update = {
152 "email_status": new_status,
153 "email_status_at": event.get("created_at") or data.get("created_at") or datetime.now(UTC).isoformat(),
154 "email_status_detail": bounce_detail(data) if new_status == "bounced" else None,
155 }
156 # Compare-and-set: only write over the status we read, and only while the
157 # row still points at this email (an invite resend replaces the id).
158 query = client.table(table).update(update).eq("id", row["id"]).eq("resend_email_id", email_id)
159 query = query.is_("email_status", "null") if current is None else query.eq("email_status", current)
160 for col, value in filters.items():
161 query = query.eq(col, value)
162 query.execute()
164 logger.info(
165 "email_delivery_recorded",
166 table=table,
167 previous=current,
168 email_status=new_status,
169 recipient=recipient,
170 **{id_key: row["id"]},
171 )
172 return {"status": "recorded", "email_status": new_status}