Files
ServerKit/backend/app/notifications/channels/base.py
T
Juan DenisandClaude Opus 4.8 a661212d50 feat(notifications): queue-backed Notification Bus + email system
Reusable, non-blocking notification layer on top of the Queue Bus:
notify.send(event, to, data) records a Notification + per-channel
NotificationDelivery, queues them, and a daemon consumer delivers via
pluggable channel adapters (in-app, email, chat) inheriting retry,
backoff and dead-letter.

- Jinja2 email system: branded, dark-mode, Outlook-safe base layout +
  per-event templates (security/backup/monitoring/welcome/invitation).
  The legacy inline f-string email was removed and now renders here.
- In-app center API (inbox/unread-count/mark-read) + per-user Socket.IO push.
- Admin delivery log (stats/filter/retry).
- Email providers (SMTP/SendGrid/Postmark/SES/Mailgun) with encrypted
  credentials + test; the email adapter prefers the default provider and
  falls back to the legacy SMTP config; surfaced in ConnectionRegistry.
- NotificationService.send_all() is now a non-blocking shim that routes
  system alerts through the bus. Migrations 023 + 024.

Tests: backend/tests/test_notification_bus.py (20). Full suite: 391 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 19:57:02 -04:00

56 lines
1.6 KiB
Python

"""Channel adapter contract.
Each channel (in-app, email, chat, ...) implements ``ChannelAdapter.deliver``
and returns a ``DeliveryResult``. The consumer maps the result onto the
delivery row + the queue (sent -> complete, failed -> retry/dead-letter,
skipped -> complete without sending).
Adapters render whatever they need themselves (email builds HTML, chat builds
its own payload), so the interface stays a single method.
"""
class DeliveryResult:
SENT = 'sent'
FAILED = 'failed'
SKIPPED = 'skipped'
def __init__(self, status, message_id=None, error=None):
self.status = status
self.message_id = message_id
self.error = error
@property
def ok(self):
return self.status == self.SENT
@classmethod
def sent(cls, message_id=None):
return cls(cls.SENT, message_id=message_id)
@classmethod
def failed(cls, error):
return cls(cls.FAILED, error=str(error)[:1000] if error else None)
@classmethod
def skipped(cls, reason=None):
return cls(cls.SKIPPED, error=str(reason)[:1000] if reason else None)
def __repr__(self):
return f'<DeliveryResult {self.status}{" " + self.error if self.error else ""}>'
class ChannelAdapter:
"""Base class for a notification channel. Subclasses set ``key`` and
implement ``deliver``."""
key = None
def deliver(self, delivery, notification):
"""Transmit ``notification`` to ``delivery.target`` for this channel.
Returns a DeliveryResult. May raise — the consumer treats an exception
the same as DeliveryResult.failed (so the queue retries).
"""
raise NotImplementedError