diff --git a/pyproject.toml b/pyproject.toml index dd8bfca..2158bc9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,12 +1,13 @@ [project] name = "lib-send-notifications" -version = "0.1.1" +version = "0.2.0" description = "Shared library to send notifications via the internal backend API" requires-python = ">=3.10" authors = [{ name = "Florian Gänsejunge" }] dependencies = [ "lib-secret-manager>=0.3.0", "requests>=2.31", + "lib-shared-models", ] [build-system] diff --git a/send_notifications/__init__.py b/send_notifications/__init__.py index 01018a8..28ee7a4 100644 --- a/send_notifications/__init__.py +++ b/send_notifications/__init__.py @@ -1,6 +1,17 @@ import logging -from .send_notification import NotificationClient, NotificationError,NotificationUnavailableError + +from .send_notification import ( + InvalidNotificationError, + NotificationClient, + NotificationError, + NotificationUnavailableError, +) logging.getLogger(__name__).addHandler(logging.NullHandler()) -__all__ = ["NotificationClient", "NotificationError", "NotificationUnavailableError"] +__all__ = [ + "InvalidNotificationError", + "NotificationClient", + "NotificationError", + "NotificationUnavailableError", + ] diff --git a/send_notifications/send_notification.py b/send_notifications/send_notification.py index 37168fd..cc64f85 100644 --- a/send_notifications/send_notification.py +++ b/send_notifications/send_notification.py @@ -10,15 +10,8 @@ import os import time import requests - - from secret_manager import get_secret - -__all__ = [ - "NotificationClient", - "NotificationError", - "NotificationUnavailableError", -] +from shared_models import Message, MessageValidationError, ValidationIssue logger = logging.getLogger(__name__) @@ -29,7 +22,19 @@ RETRYABLE_STATUS = {429, 502, 503, 504} class NotificationError(Exception): - """The notification could not be delivered.""" + """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) @@ -37,7 +42,33 @@ class NotificationError(Exception): class NotificationUnavailableError(NotificationError): - """The backend was unreachable or kept failing after all retries.""" + """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: @@ -59,6 +90,10 @@ class NotificationClient: 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__( @@ -78,59 +113,78 @@ class NotificationClient: def send( self, + user_id: int, title: str, body: str, link: str | None = None, category: str = "utility", timestamp: int | None = None, *, - user_id: int = 1, max_attempts: int = 5, timeout: float = 5.0, ) -> str: - """Send a notification to the backend. - - Delivery is retried with exponential backoff (1s, 2s, 4s, ...) on - timeouts, connection errors, and HTTP 429/502/503/504. Other HTTP - errors fail immediately. + """Validate and send one notification, retrying transient failures. Args: - title: Short headline shown for the notification. - body: Main notification text. - link: Optional URL the notification should open. - category: Notification category used by the backend for routing - and display. Defaults to "utility". - user_id: ID of the user who receives the notification. - max_attempts: Total number of delivery attempts, including the - first. - timeout: Per-request timeout in seconds. + 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: - NotificationUnavailableError: The backend was unreachable or kept - returning transient errors after all attempts. - NotificationError: The backend rejected the request (non-retryable - HTTP error) or the request could not be sent. The HTTP status - is available as ``status_code`` when there is one. + 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": { - "title": title, - "body": body, - "link": link, - "category": category, - "timestamp": timestamp if timestamp is not None else int(time.time()), - }, + "message": {"message": message.to_dict()}, } - logger.debug("Sending notification: title=%r link=%r", title, link) + logger.debug("Sending notification: title=%r body=%r", title, body) last_error = "unknown error" with requests.Session() as session: