Coverage for notifications/web_push_sender.py: 45.45%
49 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"""Web Push sender.
3Wraps pywebpush. Reads VAPID config from env. Auto-cleans subscriptions
4the push service rejects as gone (404 / 410) so push_send_log doesn't
5fill with permanent failures.
7Never raises to the caller — returns a SendResult that the dispatcher
8can log without breaking the user-facing flow.
9"""
11from __future__ import annotations
13import json
14import os
15from dataclasses import dataclass
16from typing import Any
18import structlog
20logger = structlog.get_logger(__name__)
23# Statuses written to push_send_log.status
24STATUS_SENT = "sent"
25STATUS_FAILED = "failed"
26STATUS_EXPIRED = "expired" # subscription gone — cleaned up
29@dataclass(frozen=True)
30class SendResult:
31 """Outcome of one push send attempt."""
33 status: str # one of STATUS_*
34 http_status: int | None = None
35 error: str | None = None
37 @property
38 def ok(self) -> bool:
39 return self.status == STATUS_SENT
41 @property
42 def expired(self) -> bool:
43 return self.status == STATUS_EXPIRED
46def is_configured() -> bool:
47 """True if VAPID env vars are all set. Backend boots without them
48 (push fan-out is a no-op until configured).
49 """
50 return bool(
51 os.getenv("VAPID_PRIVATE_KEY")
52 and os.getenv("VAPID_PUBLIC_KEY")
53 and os.getenv("VAPID_SUBJECT")
54 )
57def get_public_key() -> str | None:
58 """Public VAPID key (returned to the frontend at runtime). Non-secret."""
59 return os.getenv("VAPID_PUBLIC_KEY") or None
62def send_push(
63 subscription: dict[str, Any],
64 payload: dict[str, Any],
65 *,
66 ttl: int = 60,
67) -> SendResult:
68 """Send a single Web Push message. Never raises.
70 subscription dict must include `endpoint`, `p256dh_key`, `auth_key`.
71 payload is JSON-serialized and sent as the message body — the service
72 worker on the client parses it in the `push` event handler.
74 ttl: how long the push service should hold the message if the device
75 is offline. 60s is a sensible default for time-sensitive match events
76 (a goal that arrives 5 minutes late is just noise).
77 """
78 if not is_configured():
79 # Log once per process at registration time; here just skip silently.
80 return SendResult(status=STATUS_FAILED, error="VAPID not configured")
82 endpoint = subscription.get("endpoint")
83 p256dh = subscription.get("p256dh_key")
84 auth = subscription.get("auth_key")
85 if not endpoint or not p256dh or not auth:
86 return SendResult(status=STATUS_FAILED, error="invalid subscription")
88 try:
89 # Lazy import — pywebpush pulls in cryptography eagerly, which we
90 # already have. Keeps the import surface tight at module load.
91 from pywebpush import WebPushException, webpush
92 except ImportError as exc:
93 logger.error("pywebpush_import_failed", error=str(exc))
94 return SendResult(status=STATUS_FAILED, error=f"pywebpush import: {exc}")
96 sub_info = {
97 "endpoint": endpoint,
98 "keys": {"p256dh": p256dh, "auth": auth},
99 }
101 try:
102 response = webpush(
103 subscription_info=sub_info,
104 data=json.dumps(payload),
105 vapid_private_key=os.environ["VAPID_PRIVATE_KEY"],
106 vapid_claims={"sub": os.environ["VAPID_SUBJECT"]},
107 ttl=ttl,
108 )
109 return SendResult(status=STATUS_SENT, http_status=response.status_code)
110 except WebPushException as exc:
111 http_status = getattr(getattr(exc, "response", None), "status_code", None)
112 # 404 + 410 = subscription gone (user unsubscribed at OS level, or
113 # uninstalled the PWA). The caller should drop the row.
114 if http_status in (404, 410):
115 return SendResult(
116 status=STATUS_EXPIRED, http_status=http_status, error=str(exc)
117 )
118 return SendResult(
119 status=STATUS_FAILED, http_status=http_status, error=str(exc)
120 )
121 except Exception as exc:
122 return SendResult(status=STATUS_FAILED, error=str(exc))