Coverage for dao/bracket_follow_dao.py: 29.69%
56 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"""Bracket Follow DAO.
3Tracks which tournament brackets a user follows. A bracket is the tuple
4(tournament_id, tournament_group, age_group_id) — e.g. "Bracket A · U14".
5Following a bracket means: get a Web Push when any match in that bracket
6reaches a final score (fulltime). See dispatcher._send_push_fanout.
8list_subscriptions_for_bracket is the fan-out hot path — called once per
9fulltime event to find every push subscription that should receive it.
10Mirrors TeamFollowDAO (dao/team_follow_dao.py).
11"""
13from __future__ import annotations
15import structlog
17from dao.base_dao import BaseDAO
19logger = structlog.get_logger()
21TABLE = "user_bracket_follows"
24class BracketFollowDAO(BaseDAO):
25 """Data access for user→bracket follow relationships."""
27 def follow(
28 self,
29 user_id: str,
30 tournament_id: int,
31 tournament_group: str,
32 age_group_id: int,
33 ) -> bool:
34 """Follow a bracket. Idempotent — re-following returns True silently."""
35 try:
36 existing = (
37 self.client.table(TABLE)
38 .select("user_id")
39 .eq("user_id", user_id)
40 .eq("tournament_id", tournament_id)
41 .eq("tournament_group", tournament_group)
42 .eq("age_group_id", age_group_id)
43 .limit(1)
44 .execute()
45 )
46 if existing.data:
47 return True
48 self.client.table(TABLE).insert(
49 {
50 "user_id": user_id,
51 "tournament_id": tournament_id,
52 "tournament_group": tournament_group,
53 "age_group_id": age_group_id,
54 }
55 ).execute()
56 return True
57 except Exception:
58 logger.exception(
59 "bracket_follow_failed",
60 user_id=user_id,
61 tournament_id=tournament_id,
62 tournament_group=tournament_group,
63 age_group_id=age_group_id,
64 )
65 return False
67 def unfollow(
68 self,
69 user_id: str,
70 tournament_id: int,
71 tournament_group: str,
72 age_group_id: int,
73 ) -> bool:
74 """Unfollow a bracket. Idempotent — returns True even if not following."""
75 try:
76 (
77 self.client.table(TABLE)
78 .delete()
79 .eq("user_id", user_id)
80 .eq("tournament_id", tournament_id)
81 .eq("tournament_group", tournament_group)
82 .eq("age_group_id", age_group_id)
83 .execute()
84 )
85 return True
86 except Exception:
87 logger.exception(
88 "bracket_unfollow_failed",
89 user_id=user_id,
90 tournament_id=tournament_id,
91 tournament_group=tournament_group,
92 age_group_id=age_group_id,
93 )
94 return False
96 def list_for_user(self, user_id: str) -> list[dict]:
97 """Return brackets the user follows, joined with tournament + age group
98 names for display."""
99 try:
100 response = (
101 self.client.table(TABLE)
102 .select(
103 "tournament_id, tournament_group, age_group_id, created_at, "
104 "tournament:tournaments(id, name, logo_url), "
105 "age_group:age_groups(id, name)"
106 )
107 .eq("user_id", user_id)
108 .order("created_at", desc=True)
109 .execute()
110 )
111 return response.data or []
112 except Exception:
113 logger.exception("bracket_follow_list_failed", user_id=user_id)
114 return []
116 def _follower_user_ids(
117 self,
118 tournament_id: int,
119 tournament_group: str,
120 age_group_id: int,
121 ) -> list[str]:
122 """Distinct users following this exact bracket. Raises on DB error.
124 Shared by the Web Push and APNs fan-outs (SB-1236).
125 """
126 follow_resp = (
127 self.client.table(TABLE)
128 .select("user_id")
129 .eq("tournament_id", tournament_id)
130 .eq("tournament_group", tournament_group)
131 .eq("age_group_id", age_group_id)
132 .execute()
133 )
134 return list(
135 {
136 row["user_id"]
137 for row in (follow_resp.data or [])
138 if row.get("user_id")
139 }
140 )
142 def list_user_ids_for_bracket(
143 self,
144 tournament_id: int,
145 tournament_group: str,
146 age_group_id: int,
147 ) -> list[str]:
148 """Distinct users following this bracket (APNs fan-out, SB-1236).
150 Returns [] on error, like list_subscriptions_for_bracket.
151 """
152 try:
153 return self._follower_user_ids(
154 tournament_id, tournament_group, age_group_id
155 )
156 except Exception:
157 logger.exception(
158 "bracket_follow_list_user_ids_failed",
159 tournament_id=tournament_id,
160 tournament_group=tournament_group,
161 age_group_id=age_group_id,
162 )
163 return []
165 def list_subscriptions_for_bracket(
166 self,
167 tournament_id: int,
168 tournament_group: str,
169 age_group_id: int,
170 ) -> list[dict]:
171 """Fan-out query: every push subscription whose owner follows this bracket.
173 Returns subscription rows (id, endpoint, p256dh_key, auth_key, user_id),
174 deduplicated by subscription id (a user with multiple devices appears
175 once per device — intentional, each device gets its own push).
177 Two plain `in_`/`eq` queries rather than a PostgREST embed: as with
178 user_team_follows, there is no FK between user_bracket_follows and
179 push_subscriptions (both only reference user_profiles), so an embed
180 raises PGRST200 and — since the DAO swallows exceptions — the dispatcher
181 would silently deliver zero pushes. See dao/team_follow_dao.py:97.
182 """
183 try:
184 # Step 1: distinct users following this exact bracket.
185 user_ids = self._follower_user_ids(
186 tournament_id, tournament_group, age_group_id
187 )
188 if not user_ids:
189 return []
191 # Step 2: every push subscription owned by those users.
192 sub_resp = (
193 self.client.table("push_subscriptions")
194 .select("id, endpoint, p256dh_key, auth_key, user_id")
195 .in_("user_id", user_ids)
196 .execute()
197 )
199 seen_ids: set[str] = set()
200 flat: list[dict] = []
201 for sub in sub_resp.data or []:
202 if sub["id"] in seen_ids:
203 continue
204 seen_ids.add(sub["id"])
205 flat.append(sub)
206 return flat
207 except Exception:
208 logger.exception(
209 "bracket_follow_list_subscriptions_failed",
210 tournament_id=tournament_id,
211 tournament_group=tournament_group,
212 age_group_id=age_group_id,
213 )
214 return []