Coverage for notifications/dispatcher.py: 80.46%
352 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
1"""Live-match notification dispatcher.
3Given a match event, resolve the channels that should receive it, format
4the message in the home club's timezone, and best-effort deliver it to
5each destination.
7All failures are swallowed and logged — the notifier must never impact the
8user-facing live-scoring flow.
9"""
11from __future__ import annotations
13import os
14from datetime import UTC, datetime
15from zoneinfo import ZoneInfo
17import structlog
19from dao.apns_device_dao import ApnsDeviceDAO
20from dao.bracket_follow_dao import BracketFollowDAO
21from dao.club_notifications_dao import ClubNotificationsDAO
22from dao.fcm_device_dao import FcmDeviceDAO
23from dao.match_dao import MatchDAO, SupabaseConnection
24from dao.notification_deliveries_dao import DeliveryLedgerError, NotificationDeliveriesDAO
25from dao.notification_threads_dao import NotificationThreadsDAO
26from dao.push_send_log_dao import PushSendLogDAO
27from dao.push_subscription_dao import PushSubscriptionDAO
28from dao.team_follow_dao import TeamFollowDAO
29from notifications.adapters.base import DeliveryError, NotificationConfigError
30from notifications.apns_sender import is_configured as apns_is_configured
31from notifications.apns_sender import send_apns
32from notifications.channel_resolver import (
33 ResolvedChannel,
34 fetch_club_timezone,
35 resolve_destinations,
36 resolve_user_push_subscriptions,
37)
38from notifications.fcm_sender import is_configured as fcm_is_configured
39from notifications.fcm_sender import send_fcm
40from notifications.formatters import format_event, thread_title
41from notifications.preferences import DEFAULT_PREFERENCES, is_player_only
42from notifications.retry_policy import next_attempt
43from notifications.threads import send as thread_send
44from notifications.web_push_sender import is_configured as push_is_configured
45from notifications.web_push_sender import send_push
47# NotificationPreferencesDAO is imported lazily inside `prefs_dao` to break
48# the circular import: notification_preferences_dao.py → notifications.preferences
49# → notifications/__init__ → dispatcher → notification_preferences_dao.py.
51logger = structlog.get_logger(__name__)
53# An FCM fan-out of at least this many sends that comes back entirely expired
54# is treated as a config problem, and nothing is pruned (SB-1463).
55FCM_MASS_EXPIRY_MIN_SENDS = 3
58def is_notifications_enabled() -> bool:
59 """Global kill switch — matches the one in api/club_notifications.py."""
60 return os.getenv("NOTIFICATIONS_ENABLED", "true").lower() not in {
61 "0",
62 "false",
63 "no",
64 "off",
65 }
68def _safe_error(exc: Exception) -> str:
69 """Text safe to log and store: only our own errors are free of URLs and tokens."""
70 if isinstance(exc, DeliveryError | NotificationConfigError): 70 ↛ 72line 70 didn't jump to line 72 because the condition on line 70 was always true
71 return str(exc)
72 return type(exc).__name__
75def _build_push_payload(event_type: str, match: dict, content: str) -> dict:
76 """Construct the JSON payload the service worker will receive.
78 title = first line of formatted content (the headline w/ emoji)
79 body = remaining lines
81 `tag` collapses repeated events on the same match so the user sees
82 one notification per (match, event_type) instead of a stack.
83 """
84 lines = content.split("\n", 1)
85 title = lines[0]
86 body = lines[1] if len(lines) > 1 else ""
87 match_id = match.get("id")
88 return {
89 "title": title,
90 "body": body,
91 "icon": "/pwa/icon-192.png",
92 "badge": "/pwa/icon-192.png",
93 "tag": f"match-{match_id}-{event_type}",
94 "data": {
95 # Deep link to the match detail. The SPA reads ?matchId= on load and
96 # opens MatchDetailView (works for completed matches too — unlike the
97 # old ?tab=live link, which nothing read). See App.vue (SB-86).
98 "url": f"/?matchId={match_id}",
99 "matchId": match_id,
100 "eventType": event_type,
101 },
102 }
105class Notifier:
106 """Dispatcher wrapper with DI-friendly constructor for tests."""
108 def __init__(
109 self,
110 connection: SupabaseConnection | None = None,
111 send_fn=None,
112 push_send_fn=None,
113 apns_send_fn=None,
114 fcm_send_fn=None,
115 ):
116 self._connection = connection
117 self._match_dao: MatchDAO | None = None
118 self._notif_dao: ClubNotificationsDAO | None = None
119 self._delivery_dao: NotificationDeliveriesDAO | None = None
120 self._threads_dao: NotificationThreadsDAO | None = None
121 self._team_follow_dao: TeamFollowDAO | None = None
122 self._bracket_follow_dao: BracketFollowDAO | None = None
123 self._push_sub_dao: PushSubscriptionDAO | None = None
124 self._push_log_dao: PushSendLogDAO | None = None
125 self._apns_device_dao: ApnsDeviceDAO | None = None
126 self._fcm_device_dao: FcmDeviceDAO | None = None
127 # NotificationPreferencesDAO; typed via local import to avoid the cycle.
128 self._prefs_dao = None
129 # Lazy-imported default sender so tests can swap without importing httpx.
130 self._send_fn = send_fn
131 # Push sender override for tests.
132 self._push_send_fn = push_send_fn or send_push
133 # APNs sender override for tests (SB-1236).
134 self._apns_send_fn = apns_send_fn or send_apns
135 # FCM sender override for tests (SB-1463).
136 self._fcm_send_fn = fcm_send_fn or send_fcm
138 @property
139 def connection(self) -> SupabaseConnection:
140 if self._connection is None: 140 ↛ 141line 140 didn't jump to line 141 because the condition on line 140 was never true
141 self._connection = SupabaseConnection()
142 return self._connection
144 @property
145 def match_dao(self) -> MatchDAO:
146 if self._match_dao is None: 146 ↛ 147line 146 didn't jump to line 147 because the condition on line 146 was never true
147 self._match_dao = MatchDAO(self.connection)
148 return self._match_dao
150 @property
151 def notif_dao(self) -> ClubNotificationsDAO:
152 if self._notif_dao is None: 152 ↛ 153line 152 didn't jump to line 153 because the condition on line 152 was never true
153 self._notif_dao = ClubNotificationsDAO(self.connection)
154 return self._notif_dao
156 @property
157 def delivery_dao(self) -> NotificationDeliveriesDAO:
158 if self._delivery_dao is None:
159 self._delivery_dao = NotificationDeliveriesDAO(self.connection)
160 return self._delivery_dao
162 @property
163 def threads_dao(self) -> NotificationThreadsDAO:
164 if self._threads_dao is None:
165 self._threads_dao = NotificationThreadsDAO(self.connection)
166 return self._threads_dao
168 @property
169 def team_follow_dao(self) -> TeamFollowDAO:
170 if self._team_follow_dao is None: 170 ↛ 171line 170 didn't jump to line 171 because the condition on line 170 was never true
171 self._team_follow_dao = TeamFollowDAO(self.connection)
172 return self._team_follow_dao
174 @property
175 def bracket_follow_dao(self) -> BracketFollowDAO:
176 if self._bracket_follow_dao is None: 176 ↛ 177line 176 didn't jump to line 177 because the condition on line 176 was never true
177 self._bracket_follow_dao = BracketFollowDAO(self.connection)
178 return self._bracket_follow_dao
180 @property
181 def push_sub_dao(self) -> PushSubscriptionDAO:
182 if self._push_sub_dao is None: 182 ↛ 183line 182 didn't jump to line 183 because the condition on line 182 was never true
183 self._push_sub_dao = PushSubscriptionDAO(self.connection)
184 return self._push_sub_dao
186 @property
187 def push_log_dao(self) -> PushSendLogDAO:
188 if self._push_log_dao is None: 188 ↛ 189line 188 didn't jump to line 189 because the condition on line 188 was never true
189 self._push_log_dao = PushSendLogDAO(self.connection)
190 return self._push_log_dao
192 @property
193 def apns_device_dao(self) -> ApnsDeviceDAO:
194 if self._apns_device_dao is None: 194 ↛ 195line 194 didn't jump to line 195 because the condition on line 194 was never true
195 self._apns_device_dao = ApnsDeviceDAO(self.connection)
196 return self._apns_device_dao
198 @property
199 def fcm_device_dao(self) -> FcmDeviceDAO:
200 if self._fcm_device_dao is None: 200 ↛ 201line 200 didn't jump to line 201 because the condition on line 200 was never true
201 self._fcm_device_dao = FcmDeviceDAO(self.connection)
202 return self._fcm_device_dao
204 @property
205 def prefs_dao(self):
206 if self._prefs_dao is None: 206 ↛ 207line 206 didn't jump to line 207 because the condition on line 206 was never true
207 from dao.notification_preferences_dao import (
208 NotificationPreferencesDAO,
209 )
211 self._prefs_dao = NotificationPreferencesDAO(self.connection)
212 return self._prefs_dao
214 @property
215 def send_fn(self):
216 if self._send_fn is None: 216 ↛ 217line 216 didn't jump to line 217 because the condition on line 216 was never true
217 from notifications.senders import send_to
219 self._send_fn = send_to
220 return self._send_fn
222 def notify(
223 self,
224 event_type: str,
225 match_id: int,
226 extra: dict | None = None,
227 event_key: str | None = None,
228 ) -> None:
229 """Deliver a notification for a single match event.
231 `event_key` makes chat posts idempotent; see `_post_to_channel`.
233 Best-effort: logs and returns on any failure, never raises.
234 """
235 if not is_notifications_enabled(): 235 ↛ 236line 235 didn't jump to line 236 because the condition on line 235 was never true
236 logger.info(
237 "notifications.skipped",
238 reason="disabled",
239 match_id=match_id,
240 event_type=event_type,
241 )
242 return
244 # include_test: a TSC rehearsal is a match too. Without it every test
245 # match is "not found" and nothing is ever sent for one (SB-1534);
246 # who may hear about it is narrowed below instead.
247 match = self.match_dao.get_match_by_id(match_id, include_test=True)
248 if not match: 248 ↛ 249line 248 didn't jump to line 249 because the condition on line 248 was never true
249 logger.warning(
250 "notifications.skipped",
251 reason="match_not_found",
252 match_id=match_id,
253 event_type=event_type,
254 )
255 return
257 home_club = match.get("home_team_club") or {}
258 away_club = match.get("away_team_club") or {}
259 home_club_id = home_club.get("id")
260 away_club_id = away_club.get("id")
262 tz_name = fetch_club_timezone(home_club_id, self.connection.get_client())
263 try:
264 tz = ZoneInfo(tz_name)
265 except Exception:
266 tz = ZoneInfo("America/New_York")
268 content = format_event(event_type, match, extra, tz)
269 if not content: 269 ↛ 270line 269 didn't jump to line 270 because the condition on line 269 was never true
270 logger.warning(
271 "notifications.skipped",
272 reason="unknown_event_type",
273 match_id=match_id,
274 event_type=event_type,
275 )
276 return
278 # Chat channels (club, squad, global). A match may have none
279 # — e.g. tournament teams whose clubs have no channel config — in which
280 # case we skip the club sends but STILL run the Web Push fan-out below.
281 # Push to team followers must not depend on the clubs having channels
282 # (SB-77); previously a no-channels match returned here and followers
283 # got nothing.
284 # A test match never reaches a club channel: those are public rooms,
285 # and the SB-591 partition exists so a rehearsal stays out of them.
286 is_test = bool(match.get("is_test"))
287 player_only = is_player_only(event_type)
288 target_team_id = (extra or {}).get("team_id") if player_only else None
289 destinations = [] if is_test else resolve_destinations(match, event_type, self.notif_dao, target_team_id)
290 if destinations:
291 title = thread_title(match, tz)
292 outcomes = [
293 self._post_to_channel(channel, content, event_key, match_id, event_type, title)
294 for channel in destinations
295 ]
296 logger.info(
297 "notifications.dispatched",
298 match_id=match_id,
299 event_type=event_type,
300 sent=outcomes.count("sent"),
301 failed=outcomes.count("failed"),
302 duplicate=outcomes.count("duplicate"),
303 retrying=outcomes.count("retrying"),
304 )
305 elif is_test:
306 logger.info(
307 "notifications.test_match_no_club_channels",
308 match_id=match_id,
309 event_type=event_type,
310 )
311 else:
312 logger.info(
313 "notifications.no_club_channels",
314 match_id=match_id,
315 event_type=event_type,
316 home_club_id=home_club_id,
317 away_club_id=away_club_id,
318 )
320 # Player-only events (SB-1610) are content for a squad's player room.
321 # Followers are fans, so no personal push of any kind.
322 if player_only:
323 return
325 # --- Web Push fan-out -------------------------------------------------
326 # Independent of club-channel sends above; failures don't affect each
327 # other. Skipped entirely if VAPID isn't configured (dormant state
328 # before the platform-bootstrap secrets land — see SB-50).
329 self._send_push_fanout(event_type, match, content)
331 # --- Native audience (APNs + FCM) -------------------------------------
332 # Followers and their preferences are resolved once and shared by both
333 # native fan-outs; skipped entirely when neither is configured.
334 apns_on = apns_is_configured()
335 fcm_on = fcm_is_configured()
336 if not apns_on and not fcm_on:
337 return
338 try:
339 user_ids, prefs_by_user = self._native_audience(event_type, match)
340 except Exception as exc:
341 logger.warning(
342 "notifications.native_audience_failed",
343 match_id=match_id,
344 event_type=event_type,
345 error_type=type(exc).__name__,
346 error=str(exc),
347 )
348 return
349 if not user_ids:
350 return
352 # --- APNs fan-out (native iOS, SB-1236) -------------------------------
353 # Same followers, same preference gate, same bracket rule as Web Push
354 # above, but its own device table and sender. Runs after — and
355 # independently of — the web path; skipped if APNs isn't configured.
356 try:
357 if apns_on:
358 self._send_apns_fanout(event_type, match, content, user_ids, prefs_by_user)
359 except Exception as exc:
360 logger.warning(
361 "notifications.apns_fanout_failed",
362 match_id=match_id,
363 event_type=event_type,
364 error_type=type(exc).__name__,
365 error=str(exc),
366 )
368 # --- FCM fan-out (native Android, SB-1463) ----------------------------
369 # Same followers, preferences and bracket rule as APNs; its own device
370 # table and sender. Skipped if FCM isn't configured.
371 try:
372 if fcm_on:
373 self._send_fcm_fanout(event_type, match, content, user_ids, prefs_by_user)
374 except Exception as exc:
375 logger.warning(
376 "notifications.fcm_fanout_failed",
377 match_id=match_id,
378 event_type=event_type,
379 error_type=type(exc).__name__,
380 error=str(exc),
381 )
383 def _post_to_channel(
384 self,
385 channel: ResolvedChannel,
386 content: str,
387 event_key: str | None,
388 match_id: int,
389 event_type: str,
390 thread_name: str | None = None,
391 ) -> str:
392 """Post once to one channel. Returns "sent", "failed", "retrying" or "duplicate".
394 The ledger row is claimed before the post, so a crash mid-send leaves a
395 missed message rather than a double one. If the ledger itself is down
396 the post goes ahead unrecorded: losing a goal update is worse than the
397 small chance of repeating one.
398 """
399 delivery_id = None
400 if event_key: 400 ↛ 401line 400 didn't jump to line 401 because the condition on line 400 was never true
401 try:
402 delivery_id = self.delivery_dao.claim(channel.channel_id, event_key, content, match_id, event_type)
403 if delivery_id is None:
404 return "duplicate"
405 except DeliveryLedgerError:
406 logger.warning(
407 "notifications.ledger_unavailable",
408 platform=channel.platform,
409 match_id=match_id,
410 event_type=event_type,
411 )
413 try:
414 result = thread_send(
415 self.send_fn,
416 channel.platform,
417 channel.destination,
418 content,
419 post_as_threads=channel.post_as_threads,
420 channel_id=channel.channel_id,
421 match_id=match_id,
422 thread_name=thread_name,
423 threads=self.threads_dao if channel.post_as_threads else None,
424 )
425 except Exception as exc:
426 error = _safe_error(exc)
427 logger.warning(
428 "notifications.send_failed",
429 platform=channel.platform,
430 match_id=match_id,
431 event_type=event_type,
432 error_type=type(exc).__name__,
433 error=error,
434 )
435 if delivery_id is not None:
436 # A rate limit, server error or network failure is retried by
437 # the delivery worker (SB-1604); anything else is final.
438 retry_at = next_attempt(
439 1,
440 bool(getattr(exc, "retryable", False)),
441 getattr(exc, "retry_after", None),
442 datetime.now(UTC),
443 )
444 if retry_at is not None:
445 self.delivery_dao.mark_retry(delivery_id, error, retry_at.isoformat())
446 return "retrying"
447 self.delivery_dao.mark_failed(delivery_id, error)
448 return "failed"
450 if delivery_id is not None: 450 ↛ 451line 450 didn't jump to line 451 because the condition on line 450 was never true
451 self.delivery_dao.mark_sent(delivery_id, getattr(result, "message_ref", None))
452 return "sent"
454 def _send_push_fanout(
455 self, event_type: str, match: dict, content: str
456 ) -> None:
457 """Push to every user following either team, gated by per-user preferences.
459 Pre-SB-57, yellow_card/red_card were hard-skipped here; now they fire
460 only for users who opted in. Defaults preserve prior behavior (cards
461 off, everything else on) so existing followers see no change until
462 they touch the prefs UI.
463 """
464 if not push_is_configured():
465 return # VAPID env unset — dormant; SB-50 activates this
467 home_team_id = match.get("home_team_id")
468 away_team_id = match.get("away_team_id")
469 match_id = match.get("id")
471 subscriptions = resolve_user_push_subscriptions(
472 home_team_id, away_team_id, self.team_follow_dao, match.get("age_group_id")
473 )
475 # Bracket followers: users who follow this match's tournament bracket
476 # (tournament_id + group + age_group). Fulltime only — bracket follows
477 # are "tell me the final score", not play-by-play. Merged into the same
478 # fan-out and deduped below so a user following both the team and the
479 # bracket gets one push per device, not two.
480 if event_type == "fulltime":
481 tournament_id = match.get("tournament_id")
482 tournament_group = match.get("tournament_group")
483 age_group_id = match.get("age_group_id")
484 if tournament_id and tournament_group and age_group_id:
485 subscriptions = subscriptions + self.bracket_follow_dao.list_subscriptions_for_bracket(
486 tournament_id, tournament_group, age_group_id
487 )
489 # Dedupe by subscription id across the team + bracket sources.
490 seen_sub_ids: set[str] = set()
491 deduped: list[dict] = []
492 for sub in subscriptions:
493 sub_id = sub.get("id")
494 if sub_id in seen_sub_ids: 494 ↛ 495line 494 didn't jump to line 495 because the condition on line 494 was never true
495 continue
496 seen_sub_ids.add(sub_id)
497 deduped.append(sub)
498 subscriptions = deduped
500 # A test match reaches only those who can see it (SB-1534).
501 if subscriptions and match.get("is_test"):
502 allowed = self._test_content_viewers(
503 sorted({sub.get("user_id") for sub in subscriptions if sub.get("user_id")})
504 )
505 subscriptions = [sub for sub in subscriptions if sub.get("user_id") in allowed]
507 if not subscriptions:
508 return
510 # One batch query for the entire fanout instead of N per subscription.
511 user_ids = sorted({sub.get("user_id") for sub in subscriptions if sub.get("user_id")})
512 prefs_by_user = self.prefs_dao.get_preferences_batch(user_ids)
514 payload = _build_push_payload(event_type, match, content)
516 push_sent = 0
517 push_failed = 0
518 push_expired = 0
519 push_skipped_pref = 0
520 for sub in subscriptions:
521 user_id = sub.get("user_id")
522 user_prefs = prefs_by_user.get(user_id, DEFAULT_PREFERENCES)
523 if not user_prefs.get(event_type, True):
524 push_skipped_pref += 1
525 continue
526 result = self._push_send_fn(sub, payload)
527 self.push_log_dao.log(
528 subscription_id=sub.get("id"),
529 user_id=user_id,
530 match_id=match_id,
531 event_type=event_type,
532 status=result.status,
533 http_status=result.http_status,
534 error=result.error,
535 )
536 if result.ok:
537 push_sent += 1
538 elif result.expired: 538 ↛ 543line 538 didn't jump to line 543 because the condition on line 538 was always true
539 push_expired += 1
540 # Subscription is dead — clean it up so we don't retry forever.
541 self.push_sub_dao.delete_by_endpoint(sub["endpoint"])
542 else:
543 push_failed += 1
545 logger.info(
546 "notifications.push_dispatched",
547 match_id=match_id,
548 event_type=event_type,
549 sent=push_sent,
550 failed=push_failed,
551 expired=push_expired,
552 skipped_pref=push_skipped_pref,
553 )
555 def _native_audience(
556 self, event_type: str, match: dict
557 ) -> tuple[list[str], dict[str, dict[str, bool]]]:
558 """Users who should hear about this event on a native app, sorted,
559 plus their preferences — one follow lookup and one preferences batch
560 shared by the APNs and FCM fan-outs.
562 Mirrors _send_push_fanout's resolution: followers of either team at the
563 match's age group (squad follows, SB-1608), plus bracket followers at
564 fulltime, deduped by user.
565 """
566 home_team_id = match.get("home_team_id")
567 away_team_id = match.get("away_team_id")
569 team_ids = [t for t in (home_team_id, away_team_id) if t is not None]
570 user_ids: set[str] = set(
571 self.team_follow_dao.list_user_ids_for_team_ids(team_ids, match.get("age_group_id"))
572 )
574 # Bracket followers get the final score only, as on the web path.
575 if event_type == "fulltime":
576 tournament_id = match.get("tournament_id")
577 tournament_group = match.get("tournament_group")
578 age_group_id = match.get("age_group_id")
579 if tournament_id and tournament_group and age_group_id:
580 user_ids.update(
581 self.bracket_follow_dao.list_user_ids_for_bracket(
582 tournament_id, tournament_group, age_group_id
583 )
584 )
585 if user_ids and match.get("is_test"):
586 user_ids &= self._test_content_viewers(sorted(user_ids))
587 if not user_ids:
588 return [], {}
589 sorted_ids = sorted(user_ids)
590 return sorted_ids, self.prefs_dao.get_preferences_batch(sorted_ids)
592 def _test_content_viewers(self, user_ids: list[str]) -> set[str]:
593 """Which of these users may see the SB-591 test partition — admins and
594 flagged test users, the same rule as auth.viewer_sees_test_content.
596 Fails closed: if the lookup breaks, nobody hears about a test match.
597 """
598 if not user_ids: 598 ↛ 599line 598 didn't jump to line 599 because the condition on line 598 was never true
599 return set()
600 try:
601 response = (
602 self.connection.get_client()
603 .table("user_profiles")
604 .select("id, role, is_test")
605 .in_("id", user_ids)
606 .execute()
607 )
608 except Exception as exc:
609 logger.warning(
610 "notifications.test_viewer_lookup_failed",
611 error_type=type(exc).__name__,
612 error=str(exc),
613 )
614 return set()
615 return {
616 row["id"]
617 for row in response.data or []
618 if row.get("role") == "admin" or row.get("is_test")
619 }
621 def _send_apns_fanout(
622 self,
623 event_type: str,
624 match: dict,
625 content: str,
626 user_ids: list[str],
627 prefs_by_user: dict[str, dict[str, bool]],
628 ) -> None:
629 """Push to the iOS devices of every user following either team.
631 Followers and preferences come from _native_audience; per-user
632 preferences decide each send.
633 """
634 if not apns_is_configured(): 634 ↛ 635line 634 didn't jump to line 635 because the condition on line 634 was never true
635 return # APNS_* env unset — dormant
637 match_id = match.get("id")
638 if not user_ids: 638 ↛ 639line 638 didn't jump to line 639 because the condition on line 638 was never true
639 return
641 devices = self.apns_device_dao.list_for_user_ids(user_ids)
642 if not devices:
643 return
645 payload = _build_push_payload(event_type, match, content)
647 sent = 0
648 failed = 0
649 expired = 0
650 skipped_pref = 0
651 for device in devices:
652 user_id = device.get("user_id")
653 user_prefs = prefs_by_user.get(user_id, DEFAULT_PREFERENCES)
654 if not user_prefs.get(event_type, True):
655 skipped_pref += 1
656 continue
657 result = self._apns_send_fn(device, payload)
658 self.push_log_dao.log(
659 subscription_id=None,
660 user_id=user_id,
661 match_id=match_id,
662 event_type=event_type,
663 status=result.status,
664 http_status=result.http_status,
665 error=result.error,
666 apns_device_id=device.get("id"),
667 platform="apns",
668 )
669 if result.ok:
670 sent += 1
671 elif result.expired:
672 expired += 1
673 # APNs says the token is gone — drop it so we stop sending.
674 self.apns_device_dao.delete_by_token(device["device_token"])
675 else:
676 failed += 1
678 logger.info(
679 "notifications.apns_dispatched",
680 match_id=match_id,
681 event_type=event_type,
682 sent=sent,
683 failed=failed,
684 expired=expired,
685 skipped_pref=skipped_pref,
686 )
688 def _send_fcm_fanout(
689 self,
690 event_type: str,
691 match: dict,
692 content: str,
693 user_ids: list[str],
694 prefs_by_user: dict[str, dict[str, bool]],
695 ) -> None:
696 """Push to the Android devices of every user following either team.
698 Same shape as _send_apns_fanout, with one extra guard: if every send
699 in a fan-out of FCM_MASS_EXPIRY_MIN_SENDS or more comes back expired,
700 nothing is pruned. That pattern means a project/credential problem,
701 not a crowd of uninstalls, and pruning would wipe every device.
702 """
703 if not fcm_is_configured(): 703 ↛ 704line 703 didn't jump to line 704 because the condition on line 703 was never true
704 return # FCM_SERVICE_ACCOUNT_* env unset — dormant
706 match_id = match.get("id")
707 if not user_ids: 707 ↛ 708line 707 didn't jump to line 708 because the condition on line 707 was never true
708 return
710 devices = self.fcm_device_dao.list_for_user_ids(user_ids)
711 if not devices:
712 return
714 payload = _build_push_payload(event_type, match, content)
716 sent = 0
717 failed = 0
718 expired = 0
719 skipped_pref = 0
720 expired_fids: list[str] = []
721 for device in devices:
722 user_id = device.get("user_id")
723 user_prefs = prefs_by_user.get(user_id, DEFAULT_PREFERENCES)
724 if not user_prefs.get(event_type, True):
725 skipped_pref += 1
726 continue
727 result = self._fcm_send_fn(device, payload)
728 self.push_log_dao.log(
729 subscription_id=None,
730 user_id=user_id,
731 match_id=match_id,
732 event_type=event_type,
733 status=result.status,
734 http_status=result.http_status,
735 error=result.error,
736 fcm_device_id=device.get("id"),
737 platform="fcm",
738 )
739 if result.ok:
740 sent += 1
741 elif result.expired:
742 expired += 1
743 expired_fids.append(device["fid"])
744 else:
745 failed += 1
747 attempted = sent + failed + expired
748 if expired_fids and attempted >= FCM_MASS_EXPIRY_MIN_SENDS and expired == attempted:
749 logger.warning(
750 "notifications.fcm_mass_expiry_suspected",
751 match_id=match_id,
752 event_type=event_type,
753 expired=expired,
754 )
755 else:
756 # FCM says these installations are gone — drop them so we stop sending.
757 for fid in expired_fids:
758 self.fcm_device_dao.delete_by_fid(fid)
760 logger.info(
761 "notifications.fcm_dispatched",
762 match_id=match_id,
763 event_type=event_type,
764 sent=sent,
765 failed=failed,
766 expired=expired,
767 skipped_pref=skipped_pref,
768 )
771_default_notifier: Notifier | None = None
774def get_notifier() -> Notifier:
775 """Process-wide default notifier. Tests override via set_notifier()."""
776 global _default_notifier
777 if _default_notifier is None:
778 _default_notifier = Notifier()
779 return _default_notifier
782def set_notifier(notifier: Notifier | None) -> None:
783 """Install a custom notifier (for tests) or reset by passing None."""
784 global _default_notifier
785 _default_notifier = notifier