227 lines
6.6 KiB
Python
227 lines
6.6 KiB
Python
"""Client for sending notifications to the internal notification backend.
|
|
|
|
Usage:
|
|
notifier = NotificationClient() # resolves the API key once, fails fast if missing
|
|
notifier.send("Title", "Body text", link="https://example.com")
|
|
"""
|
|
|
|
import logging
|
|
import os
|
|
import time
|
|
|
|
import requests
|
|
from secret_manager import get_secret
|
|
from shared_models import Message, MessageValidationError, ValidationIssue
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
DEFAULT_BACKEND_URL = "http://localhost:8101/internal/receive-notifications"
|
|
DEFAULT_KEY_ENV = "NOTIFY_API_KEY"
|
|
DEFAULT_KEY_PATH = "/etc/secrets/api_key"
|
|
RETRYABLE_STATUS = {429, 502, 503, 504}
|
|
|
|
|
|
class NotificationError(Exception):
|
|
"""The notification could not be delivered.
|
|
|
|
Attributes:
|
|
status_code: HTTP status returned by the backend, or None if there
|
|
was no usable response.
|
|
|
|
Catch this to handle every failure from the client:
|
|
|
|
try:
|
|
client.send("Title", "Body")
|
|
except NotificationError as e:
|
|
print(f"failed: {e}")
|
|
"""
|
|
|
|
def __init__(self, message: str, status_code: int | None = None):
|
|
super().__init__(message)
|
|
self.status_code = status_code
|
|
|
|
|
|
class NotificationUnavailableError(NotificationError):
|
|
"""The backend was unreachable or kept failing after all retries.
|
|
|
|
Retrying later may succeed, unlike InvalidNotificationError.
|
|
"""
|
|
|
|
|
|
class InvalidNotificationError(NotificationError, ValueError):
|
|
"""The notification failed local validation and was never sent.
|
|
|
|
Retrying with the same input will always fail; fix the input instead.
|
|
|
|
Attributes:
|
|
issues: Every problem found, as ValidationIssue objects with
|
|
`field`, `code` and `message`.
|
|
|
|
Example:
|
|
try:
|
|
client.send("", "Body", category="news")
|
|
except InvalidNotificationError as e:
|
|
for issue in e.issues:
|
|
print(issue.field, issue.code, issue.message)
|
|
"""
|
|
|
|
def __init__(self, message: str, issues: list[ValidationIssue] | None = None):
|
|
super().__init__(message)
|
|
self.issues = list(issues or [])
|
|
|
|
|
|
|
|
class NotificationClient:
|
|
"""Sends notifications to the internal backend service.
|
|
|
|
The API key is resolved once at construction time and kept in memory, so it
|
|
keeps working after secret files are deleted. Construction raises if no key
|
|
can be found, so misconfiguration surfaces at startup rather than on the
|
|
first notification.
|
|
|
|
Args:
|
|
api_key: Internal API key. If omitted, it is read from the environment
|
|
variable ``key_env`` first, then from the file at ``key_path``.
|
|
url: Backend endpoint. Defaults to the BACKEND_API_URL environment
|
|
variable, then to DEFAULT_BACKEND_URL.
|
|
key_env: Name of the environment variable holding the API key.
|
|
key_path: Path of the secret file holding the API key.
|
|
|
|
Raises:
|
|
MissingCredentialError: No API key was passed, set in the environment,
|
|
or found in the secret file.
|
|
|
|
Example:
|
|
client = NotificationClient(api_key="abc123", url="https://.../myscript")
|
|
client.send(1,"Backup finished", "Took 42s", category="utility")
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
api_key: str | None = None,
|
|
url: str | None = None,
|
|
*,
|
|
key_env: str = DEFAULT_KEY_ENV,
|
|
key_path: str = DEFAULT_KEY_PATH,
|
|
):
|
|
self._api_key = api_key or get_secret(key_env, key_path)
|
|
self.url = url or os.getenv("BACKEND_API_URL", DEFAULT_BACKEND_URL)
|
|
|
|
def __repr__(self) -> str:
|
|
# Never include the API key in logs or tracebacks.
|
|
return f"{type(self).__name__}(url={self.url!r})"
|
|
|
|
def send(
|
|
self,
|
|
user_id: int,
|
|
title: str,
|
|
body: str,
|
|
link: str | None = None,
|
|
category: str = "utility",
|
|
timestamp: int | None = None,
|
|
*,
|
|
max_attempts: int = 5,
|
|
timeout: float = 5.0,
|
|
) -> str:
|
|
"""Validate and send one notification, retrying transient failures.
|
|
|
|
Args:
|
|
user_id: User id as int.
|
|
title: Headline, 1-255 characters after stripping whitespace.
|
|
body: Message text, 1-255 characters after stripping whitespace.
|
|
link: Optional URL opened on tap; must start with http:// or
|
|
https://. A blank string is treated as no link.
|
|
category: A Category member or its string value
|
|
("royal-road", "podcasts", "mixtapes", "utility").
|
|
timestamp: Unix time in seconds; defaults to now.
|
|
max_attempts: Total tries (first attempt included) for retryable
|
|
failures: timeouts, connection errors, HTTP 429/502/503/504.
|
|
Backoff between tries is 1s, 2s, 4s, ...
|
|
timeout: Seconds to wait for each HTTP request.
|
|
|
|
Returns:
|
|
The backend's response body as text.
|
|
|
|
Raises:
|
|
InvalidNotificationError: Input failed validation; nothing was sent.
|
|
NotificationUnavailableError: Every attempt failed with a
|
|
retryable error.
|
|
NotificationError: The backend rejected the request with a
|
|
non-retryable status (e.g. 401, 403, 422); see `status_code`.
|
|
ValueError: `max_attempts` is less than 1.
|
|
|
|
Example:
|
|
client.send(
|
|
user_id: 1,
|
|
title="New chapter",
|
|
body="Chapter 12 is out",
|
|
link="https://example.com/ch12",
|
|
category="royal-road",
|
|
)
|
|
"""
|
|
if max_attempts < 1:
|
|
raise ValueError("max_attempts must be at least 1")
|
|
|
|
try:
|
|
message = Message.parse(
|
|
{
|
|
"title": title,
|
|
"body": body,
|
|
"link": link,
|
|
"category": category,
|
|
"timestamp": timestamp if timestamp is not None else int(time.time()),
|
|
}
|
|
)
|
|
except MessageValidationError as e:
|
|
raise InvalidNotificationError(str(e), issues=e.issues) from e
|
|
|
|
headers = {
|
|
"X-API-Key-Internal": self._api_key,
|
|
"Content-Type": "application/json",
|
|
}
|
|
payload = {
|
|
"user_id": user_id,
|
|
"message": {message.to_dict()},
|
|
}
|
|
|
|
logger.debug("Sending notification: title=%r body=%r", title, body)
|
|
last_error = "unknown error"
|
|
|
|
with requests.Session() as session:
|
|
for attempt in range(1, max_attempts + 1):
|
|
try:
|
|
response = session.post(
|
|
self.url, headers=headers, json=payload, timeout=timeout
|
|
)
|
|
except (requests.Timeout, requests.ConnectionError) as e:
|
|
last_error = type(e).__name__
|
|
except requests.RequestException as e:
|
|
raise NotificationError(f"Request failed: {e}") from e
|
|
else:
|
|
if response.ok:
|
|
logger.info("Notification sent: %r", title)
|
|
return response.text
|
|
|
|
logger.warning(
|
|
"Backend returned HTTP %s: %s",
|
|
response.status_code,
|
|
response.text,
|
|
)
|
|
if response.status_code not in RETRYABLE_STATUS:
|
|
raise NotificationError(
|
|
f"Backend rejected notification "
|
|
f"(HTTP {response.status_code})",
|
|
status_code=response.status_code,
|
|
)
|
|
last_error = f"HTTP {response.status_code}"
|
|
|
|
logger.warning(
|
|
"Attempt %d/%d failed: %s", attempt, max_attempts, last_error
|
|
)
|
|
if attempt < max_attempts:
|
|
time.sleep(2 ** (attempt - 1))
|
|
|
|
raise NotificationUnavailableError(
|
|
f"Notification service unavailable after {max_attempts} attempts: "
|
|
f"{last_error}"
|
|
) |