Coverage for notifications/ingest_alerts.py: 96.83%
51 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 14:44 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 14:44 +0000
1"""Telegram alerts for names the match ingest could not resolve (SB-829).
3The point of this module is that a failed load should be *noticed*. Before it,
4an unresolved name produced a `logger.error` in a worker pod, and the scraper's
5own Telegram report showed the run as green — it counts RabbitMQ publish
6errors, and publishing succeeds regardless of whether the match is accepted.
8Two rules keep the alerting readable:
10- **One message per distinct name, not per dropped match.** A season load that
11 dies on seven spellings sends seven messages, however many hundreds of
12 fixtures they cost. `ingest_failures.was_new` is what gates that.
13- **A cap per window.** A brand-new season can arrive with dozens of unknown
14 names, and a message each would be its own kind of unreadable. Past the cap
15 one summary message points at the API and the rest stay silent — they are
16 still recorded, so nothing is lost.
17"""
19from __future__ import annotations
21import os
22from datetime import UTC, datetime, timedelta
23from typing import Any
25import structlog
27from notifications.senders import send_to
29logger = structlog.get_logger()
31# Where operator alerts go. Deliberately separate from club notification
32# destinations: those are chosen by users, this one is the operator's.
33CHAT_ID_ENV = "MT_ADMIN_TELEGRAM_CHAT_ID"
35DEFAULT_MAX_ALERTS_PER_WINDOW = 10
36WINDOW = timedelta(hours=1)
38_KIND_LABEL = {
39 "team": "Unknown team",
40 "division": "Unknown division",
41 "league": "Unknown league",
42 "invalid": "Invalid match data",
43}
45# The fix for a bad team name is one CLI command (SB-822/SB-824). Putting it in
46# the alert is the difference between a notification and a task.
47_KIND_FIX = {
48 "team": 'mt team alias add <team> "{raw_name}"',
49 "division": "mt division create — or correct the feed's league mapping",
50}
53def _max_alerts_per_window() -> int:
54 try:
55 return int(os.getenv("MT_INGEST_ALERT_MAX_PER_HOUR", DEFAULT_MAX_ALERTS_PER_WINDOW))
56 except ValueError:
57 return DEFAULT_MAX_ALERTS_PER_WINDOW
60def _format(kind: str, raw_name: str, league: str | None, sample: str | None, match_count: int) -> str:
61 lines = [
62 "⚠️ MT ingest blocked",
63 f"{_KIND_LABEL.get(kind, kind)}: {raw_name}",
64 ]
65 context = " · ".join(p for p in (f"league: {league}" if league else None, sample) if p)
66 if context: 66 ↛ 68line 66 didn't jump to line 68 because the condition on line 66 was always true
67 lines.append(context)
68 lines.append(f"Matches dropped so far: {match_count}")
69 fix = _KIND_FIX.get(kind)
70 if fix: 70 ↛ 72line 70 didn't jump to line 72 because the condition on line 70 was always true
71 lines.append(f"Fix: {fix.format(raw_name=raw_name)}")
72 return "\n".join(lines)
75def alert_unresolved_name(
76 ingest_dao: Any,
77 *,
78 kind: str,
79 raw_name: str,
80 league: str | None,
81 sample: str | None,
82 record: dict[str, Any] | None,
83) -> bool:
84 """Send one Telegram alert for a newly-seen unresolved name.
86 `record` is the row returned by IngestFailuresDAO.record. Returns whether a
87 message was sent.
89 Never raises. Alerting is the diagnostic path; a diagnostic that can take
90 down ingest is worse than no diagnostic, and the failure is already durable
91 in `ingest_failures` by the time this runs.
92 """
93 try:
94 if not record or not record.get("should_alert"):
95 return False
97 chat_id = os.getenv(CHAT_ID_ENV)
98 if not chat_id:
99 # Expected locally and in CI. The row is still recorded, and the
100 # scraper's run report reads it over the API either way.
101 logger.info("Ingest failure recorded but not alerted — %s is unset", CHAT_ID_ENV, raw_name=raw_name)
102 return False
104 window_start = (datetime.now(tz=UTC) - WINDOW).isoformat()
105 already = ingest_dao.notified_since(window_start)
106 cap = _max_alerts_per_window()
108 if already > cap:
109 return False
110 if already == cap:
111 # Exactly at the cap: say so once, then go quiet for the window.
112 send_to(
113 "telegram",
114 chat_id,
115 f"⚠️ MT ingest: more than {cap} unresolved names this hour. "
116 "Further names are recorded but not alerted — "
117 "see GET /api/admin/ingest-failures for the full list.",
118 )
119 ingest_dao.mark_notified([record["id"]])
120 return True
122 send_to("telegram", chat_id, _format(kind, raw_name, league, sample, record.get("match_count", 1)))
123 ingest_dao.mark_notified([record["id"]])
124 logger.info("Alerted on unresolved name", kind=kind, raw_name=raw_name)
125 return True
127 except Exception:
128 logger.exception("Could not alert on unresolved name", kind=kind, raw_name=raw_name)
129 return False