Coverage for notifications/ops_events.py: 96.70%
73 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 17:31 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 17:31 +0000
1"""Operator-channel events through sb-notify (SB-1849).
3The follower push and club-channel fan-out (dispatcher.py) are product
4notifications. This is the operator's feed: one routed sb-notify event per new
5final score, so the owner sees results land without opening the app. Where it
6goes is the routing config's call (`$SB_NOTIFY_CONFIG`), never this module's.
8Dormant unless `SB_NOTIFY_CONFIG` is set. sb-notify reads its own destinations
9from env, holds events overnight (quiet hours) and drops repeats of a
10`dedupe_key`, using the state file at `$SB_NOTIFY_STATE`.
12Never raises: it runs in a background task after the response is sent, and a
13broken operator feed must not touch the fan-out that runs beside it.
14"""
16from __future__ import annotations
18import os
19from typing import TYPE_CHECKING
21import structlog
22from sb_notify import notify
24if TYPE_CHECKING:
25 from collections.abc import Callable
27logger = structlog.get_logger(__name__)
29CONFIG_ENV = "SB_NOTIFY_CONFIG"
30SOURCE = "mt-backend"
31MATCH_FINAL_KIND = "mt.match_final"
32# An en dash, as a score is typeset.
33SCORE_DASH = "\u2013"
35# The match DAO fills unknown joins with "Unknown"; that says nothing to a reader.
36_ABSENT = {"", "unknown"}
38_dormant_logged = False
41def is_enabled() -> bool:
42 return bool(os.getenv(CONFIG_ENV))
45def _log_dormant_once() -> None:
46 global _dormant_logged
47 if not _dormant_logged:
48 _dormant_logged = True
49 logger.info("ops_events.dormant", reason=f"{CONFIG_ENV} is not set")
52def _present(value: object) -> str | None:
53 if value is None:
54 return None
55 text = str(value).strip()
56 return None if text.lower() in _ABSENT else text
59def _match_date(match: dict) -> str | None:
60 # A timestamp reads as its day; the time is the scheduled kickoff's business.
61 date = _present(match.get("match_date"))
62 return date[:10] if date else None
65def build_match_final_event(match: dict) -> dict | None:
66 """The notify() fields for a final score, or None if the row has no score.
68 Team names are typed by people. They go through as plain text: each sink
69 escapes and defangs for its own platform, so adding markup here would only
70 break that.
71 """
72 match_id = match.get("id")
73 home_score, away_score = match.get("home_score"), match.get("away_score")
74 if match_id is None or home_score is None or away_score is None:
75 return None
77 home = _present(match.get("home_team_name")) or "Home team"
78 away = _present(match.get("away_team_name")) or "Away team"
80 competition = _present(match.get("tournament_name")) or _present(match.get("match_type_name"))
81 details = [
82 competition,
83 _present(match.get("age_group_name")),
84 _present(match.get("division_name")),
85 _match_date(match),
86 ]
87 body = " · ".join(part for part in details if part) or None
88 home_pens, away_pens = match.get("home_penalty_score"), match.get("away_penalty_score")
89 if home_pens is not None and away_pens is not None:
90 pens = f"Penalties {home_pens}{SCORE_DASH}{away_pens}"
91 body = f"{body}\n{pens}" if body else pens
93 tags = {
94 "age_group": _present(match.get("age_group_name")),
95 "match_type": _present(match.get("match_type_name")),
96 # Who wrote the score: the scraper, or a person in the app.
97 "match_source": _present(match.get("source")),
98 # Routes match on the id (stable); the name is for people (SB-1853).
99 "tournament_id": str(match["tournament_id"]) if match.get("tournament_id") is not None else None,
100 "tournament": _present(match.get("tournament_name")),
101 }
103 base_url = os.getenv("APP_BASE_URL", "https://missingtable.com").rstrip("/")
104 return {
105 "source": SOURCE,
106 "kind": MATCH_FINAL_KIND,
107 "level": "info",
108 "title": f"{home} {home_score}{SCORE_DASH}{away_score} {away}",
109 "body": body,
110 # The SPA opens MatchDetailView from ?matchId= (see App.vue, SB-86).
111 "links": [("Match", f"{base_url}/?matchId={match_id}")],
112 "tags": {key: value for key, value in tags.items() if value},
113 "dedupe_key": f"{MATCH_FINAL_KIND}:{match_id}:{home_score}-{away_score}",
114 }
117def emit_match_final(match: dict) -> None:
118 """Send one `mt.match_final` event for a match that just got its final score."""
119 if not is_enabled():
120 _log_dormant_once()
121 return
122 match_id = (match or {}).get("id")
123 try:
124 if match.get("is_test"):
125 # A TSC rehearsal is not a result (SB-591 keeps it out of every public room too).
126 logger.info("ops_events.skipped", kind=MATCH_FINAL_KIND, match_id=match_id, reason="test_match")
127 return
128 fields = build_match_final_event(match)
129 if fields is None: 129 ↛ 130line 129 didn't jump to line 130 because the condition on line 129 was never true
130 logger.info("ops_events.skipped", kind=MATCH_FINAL_KIND, match_id=match_id, reason="no_score")
131 return
132 result = notify(**fields)
133 # Status and reason only: outcomes are safe too, but a destination never is.
134 logger.info(
135 "ops_events.sent",
136 kind=MATCH_FINAL_KIND,
137 match_id=match_id,
138 status=str(result.status),
139 reason=str(result.reason) if result.reason else None,
140 held_until=result.held_until,
141 )
142 except Exception as exc:
143 logger.warning(
144 "ops_events.failed",
145 kind=MATCH_FINAL_KIND,
146 match_id=match_id,
147 error_type=type(exc).__name__,
148 )
151def emit_match_final_by_id(match_id: int, load_match: Callable[[int], dict | None]) -> None:
152 """Load the match, then `emit_match_final`. The read is skipped while dormant."""
153 if not is_enabled():
154 _log_dormant_once()
155 return
156 try:
157 match = load_match(match_id)
158 except Exception as exc:
159 logger.warning(
160 "ops_events.failed",
161 kind=MATCH_FINAL_KIND,
162 match_id=match_id,
163 error_type=type(exc).__name__,
164 )
165 return
166 if not match:
167 logger.info("ops_events.skipped", kind=MATCH_FINAL_KIND, match_id=match_id, reason="match_not_found")
168 return
169 emit_match_final(match)