Coverage for celery_tasks/final_score_alert.py: 100.00%
36 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"""Ask the MT API to send a final-score alert after the worker writes a score (SB-1619).
3The worker writes scores straight to the database, so the API's own
4write-path alert never runs for scraped scores. The worker also has none of
5the push credentials (web push, APNs, FCM), which live only with the API.
6So after a write that sets a new final score, it calls
7POST /api/matches/{id}/final-score-alert, and the API decides and sends.
9Best-effort by design: an alert that cannot be requested is logged and
10dropped. It never fails, delays or retries the ingest of the score itself.
12Needs MT_API_URL (the API's base URL) and SERVICE_ACCOUNT_SECRET (the same
13secret the API verifies service tokens with). Without either it stays dormant.
14"""
16from __future__ import annotations
18import os
19from datetime import UTC, datetime, timedelta
20from typing import Any
22import httpx
23import jwt
25from logging_config import get_logger
26from notifications.score_change import is_new_final_score
28logger = get_logger(__name__)
30SERVICE_NAME = "match-scraper-worker"
31TOKEN_TTL = timedelta(minutes=5)
32REQUEST_TIMEOUT_SECONDS = 5.0
35def service_token(secret: str, now: datetime | None = None) -> str:
36 """A short-lived service-account token the API accepts (auth.verify_service_account_token)."""
37 issued = now or datetime.now(UTC)
38 payload = {
39 "sub": f"service-{SERVICE_NAME}",
40 "iss": "missing-table",
41 "aud": "service-account",
42 "iat": int(issued.timestamp()),
43 "exp": int((issued + TOKEN_TTL).timestamp()),
44 "service_name": SERVICE_NAME,
45 "permissions": ["manage_matches"],
46 "role": "service_account",
47 }
48 return jwt.encode(payload, secret, algorithm="HS256")
51def alert_if_new_final_score(before: dict[str, Any] | None, after: dict[str, Any], post=None) -> bool:
52 """Request the alert when the write set a new final score. Returns whether it asked.
54 The API re-checks everything (completed, both scores, recent, not already
55 sent), so this only avoids calling it for writes that changed no score.
56 """
57 if not is_new_final_score(before, after):
58 return False
59 match_id = after.get("id")
60 base = (os.getenv("MT_API_URL") or "").rstrip("/")
61 secret = os.getenv("SERVICE_ACCOUNT_SECRET") or ""
62 if match_id is None or not base or not secret:
63 logger.warning("final_score_alert_dormant", match_id=match_id, has_url=bool(base), has_secret=bool(secret))
64 return False
65 send = post or httpx.post
66 try:
67 response = send(
68 f"{base}/api/matches/{match_id}/final-score-alert",
69 headers={"Authorization": f"Bearer {service_token(secret)}"},
70 timeout=REQUEST_TIMEOUT_SECONDS,
71 )
72 status = getattr(response, "status_code", None)
73 if status != 200:
74 logger.warning("final_score_alert_rejected", match_id=match_id, http_status=status)
75 else:
76 body = response.json()
77 logger.info(
78 "final_score_alert_requested",
79 match_id=match_id,
80 queued=body.get("queued"),
81 reason=body.get("reason"),
82 )
83 except Exception as exc:
84 logger.warning("final_score_alert_failed", match_id=match_id, error_type=type(exc).__name__)
85 return True