Breaking change: user_id is now mandatory and no longer defaults to 1
Incoming notifications are now validated against shared Message model
This commit is contained in:
1 parent
ae9cd00cce
commit
b5c5717c6f
3 files changed
+107
-41
No files matched your search
+2
-1
@@ -1,12 +1,13 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "lib-send-notifications"
|
name = "lib-send-notifications"
|
||||||
version = "0.1.1"
|
version = "0.2.0"
|
||||||
description = "Shared library to send notifications via the internal backend API"
|
description = "Shared library to send notifications via the internal backend API"
|
||||||
requires-python = ">=3.10"
|
requires-python = ">=3.10"
|
||||||
authors = [{ name = "Florian Gänsejunge" }]
|
authors = [{ name = "Florian Gänsejunge" }]
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"lib-secret-manager>=0.3.0",
|
"lib-secret-manager>=0.3.0",
|
||||||
"requests>=2.31",
|
"requests>=2.31",
|
||||||
|
"lib-shared-models",
|
||||||
]
|
]
|
||||||
|
|
||||||
[build-system]
|
[build-system]
|
||||||
|
|||||||
@@ -1,6 +1,17 @@
|
|||||||
import logging
|
import logging
|
||||||
from .send_notification import NotificationClient, NotificationError,NotificationUnavailableError
|
|
||||||
|
from .send_notification import (
|
||||||
|
InvalidNotificationError,
|
||||||
|
NotificationClient,
|
||||||
|
NotificationError,
|
||||||
|
NotificationUnavailableError,
|
||||||
|
)
|
||||||
|
|
||||||
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
||||||
__all__ = ["NotificationClient", "NotificationError", "NotificationUnavailableError"]
|
__all__ = [
|
||||||
|
"InvalidNotificationError",
|
||||||
|
"NotificationClient",
|
||||||
|
"NotificationError",
|
||||||
|
"NotificationUnavailableError",
|
||||||
|
]
|
||||||
|
|
||||||
@@ -10,15 +10,8 @@ import os
|
|||||||
import time
|
import time
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
|
|
||||||
from secret_manager import get_secret
|
from secret_manager import get_secret
|
||||||
|
from shared_models import Message, MessageValidationError, ValidationIssue
|
||||||
__all__ = [
|
|
||||||
"NotificationClient",
|
|
||||||
"NotificationError",
|
|
||||||
"NotificationUnavailableError",
|
|
||||||
]
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -29,7 +22,19 @@ RETRYABLE_STATUS = {429, 502, 503, 504}
|
|||||||
|
|
||||||
|
|
||||||
class NotificationError(Exception):
|
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):
|
def __init__(self, message: str, status_code: int | None = None):
|
||||||
super().__init__(message)
|
super().__init__(message)
|
||||||
@@ -37,7 +42,33 @@ class NotificationError(Exception):
|
|||||||
|
|
||||||
|
|
||||||
class NotificationUnavailableError(NotificationError):
|
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:
|
class NotificationClient:
|
||||||
@@ -59,6 +90,10 @@ class NotificationClient:
|
|||||||
Raises:
|
Raises:
|
||||||
MissingCredentialError: No API key was passed, set in the environment,
|
MissingCredentialError: No API key was passed, set in the environment,
|
||||||
or found in the secret file.
|
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__(
|
def __init__(
|
||||||
@@ -78,59 +113,78 @@ class NotificationClient:
|
|||||||
|
|
||||||
def send(
|
def send(
|
||||||
self,
|
self,
|
||||||
|
user_id: int,
|
||||||
title: str,
|
title: str,
|
||||||
body: str,
|
body: str,
|
||||||
link: str | None = None,
|
link: str | None = None,
|
||||||
category: str = "utility",
|
category: str = "utility",
|
||||||
timestamp: int | None = None,
|
timestamp: int | None = None,
|
||||||
*,
|
*,
|
||||||
user_id: int = 1,
|
|
||||||
max_attempts: int = 5,
|
max_attempts: int = 5,
|
||||||
timeout: float = 5.0,
|
timeout: float = 5.0,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Send a notification to the backend.
|
"""Validate and send one notification, retrying transient failures.
|
||||||
|
|
||||||
Delivery is retried with exponential backoff (1s, 2s, 4s, ...) on
|
|
||||||
timeouts, connection errors, and HTTP 429/502/503/504. Other HTTP
|
|
||||||
errors fail immediately.
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
title: Short headline shown for the notification.
|
user_id: User id as int.
|
||||||
body: Main notification text.
|
title: Headline, 1-255 characters after stripping whitespace.
|
||||||
link: Optional URL the notification should open.
|
body: Message text, 1-255 characters after stripping whitespace.
|
||||||
category: Notification category used by the backend for routing
|
link: Optional URL opened on tap; must start with http:// or
|
||||||
and display. Defaults to "utility".
|
https://. A blank string is treated as no link.
|
||||||
user_id: ID of the user who receives the notification.
|
category: A Category member or its string value
|
||||||
max_attempts: Total number of delivery attempts, including the
|
("royal-road", "podcasts", "mixtapes", "utility").
|
||||||
first.
|
timestamp: Unix time in seconds; defaults to now.
|
||||||
timeout: Per-request timeout in seconds.
|
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:
|
Returns:
|
||||||
The backend's response body as text.
|
The backend's response body as text.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
NotificationUnavailableError: The backend was unreachable or kept
|
InvalidNotificationError: Input failed validation; nothing was sent.
|
||||||
returning transient errors after all attempts.
|
NotificationUnavailableError: Every attempt failed with a
|
||||||
NotificationError: The backend rejected the request (non-retryable
|
retryable error.
|
||||||
HTTP error) or the request could not be sent. The HTTP status
|
NotificationError: The backend rejected the request with a
|
||||||
is available as ``status_code`` when there is one.
|
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 = {
|
headers = {
|
||||||
"X-API-Key-Internal": self._api_key,
|
"X-API-Key-Internal": self._api_key,
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
}
|
}
|
||||||
payload = {
|
payload = {
|
||||||
"user_id": user_id,
|
"user_id": user_id,
|
||||||
"message": {
|
"message": {"message": message.to_dict()},
|
||||||
"title": title,
|
|
||||||
"body": body,
|
|
||||||
"link": link,
|
|
||||||
"category": category,
|
|
||||||
"timestamp": timestamp if timestamp is not None else int(time.time()),
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.debug("Sending notification: title=%r link=%r", title, link)
|
logger.debug("Sending notification: title=%r body=%r", title, body)
|
||||||
last_error = "unknown error"
|
last_error = "unknown error"
|
||||||
|
|
||||||
with requests.Session() as session:
|
with requests.Session() as session:
|
||||||
|
|||||||
Reference in new issue
Block a user