"""Delivering recorded events by email."""
from __future__ import annotations
from contextlib import AsyncExitStack
from datetime import UTC, datetime, timedelta
import structlog
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from s365b.core import settings_store
from s365b.core.branding import Branding
from s365b.core.services import Services
from s365b.db.models import AppPurpose, AppRegistration, Event, Tenant
from s365b.modules.sdk import Severity
from s365b.notify.message import Message, render
from s365b.notify.senders import GraphNotifier, Notifier, SendError, SmtpNotifier
from s365b.notify.settings import SEVERITY_ORDER, NotificationSettings
[docs]
log = structlog.get_logger(__name__)
# Waits between attempts; after the last one the event is marked failed.
[docs]
RETRY_DELAYS = (timedelta(minutes=1), timedelta(minutes=5), timedelta(minutes=15),
timedelta(hours=1), timedelta(hours=3)) # fmt: skip
[docs]
async def build_notifier(
services: Services,
s: AsyncSession,
method: str,
cfg: NotificationSettings,
stack: AsyncExitStack,
) -> Notifier:
"""Create the notifier for a method.
Args:
services: Process services (tests replace ``notifier_factory``).
s: Open session.
method: ``graph`` or ``smtp``.
cfg: Notification settings.
stack: Closes the Graph client when delivery is done.
Returns:
The notifier.
Raises:
SendError: If the method is not set up.
"""
if services.notifier_factory is not None:
notifier: Notifier = services.notifier_factory(method)
return notifier
if method == "smtp":
secrets = await settings_store.load_secrets(s, NotificationSettings.key, services.secrets)
return SmtpNotifier(
cfg.smtp_host,
cfg.smtp_port,
cfg.smtp_security,
cfg.smtp_from,
cfg.smtp_username,
secrets.get("smtp_password", ""),
)
if not cfg.graph_sender:
raise SendError("no sender mailbox is set for Microsoft Graph")
row = (
await s.execute(
select(Tenant, AppRegistration)
.join(AppRegistration, AppRegistration.tenant_fk == Tenant.id)
.where(AppRegistration.purpose == AppPurpose.NOTIFICATIONS)
)
).first()
if row is None:
raise SendError(
"the Notifications app does not exist yet; open Microsoft 365 tenant and click"
" 'Update permissions and renew certificates'"
)
graph = services.graph_for(row[0], row[1])
stack.push_async_callback(graph.aclose)
return GraphNotifier(graph, cfg.graph_sender)
[docs]
async def send_with_fallback(
services: Services,
s: AsyncSession,
cfg: NotificationSettings,
message: Message,
stack: AsyncExitStack,
) -> str | None:
"""Send through the primary method, then the fallback.
Args:
services: Process services.
s: Open session.
cfg: Notification settings.
message: The message.
stack: Owns Graph clients.
Returns:
A note if the primary failed but the fallback worked, else ``None``.
Raises:
SendError: If every method failed (message lists each error).
"""
methods = [cfg.method] + ([cfg.fallback] if cfg.fallback not in ("none", cfg.method) else [])
errors: list[str] = []
for method in methods:
try:
notifier = await build_notifier(services, s, method, cfg, stack)
await notifier.send(message, cfg.recipients)
except SendError as exc:
errors.append(f"{method}: {exc}")
continue
return f"sent by {method} after: {'; '.join(errors)}" if errors else None
raise SendError("; ".join(errors))
[docs]
async def deliver_pending(
services: Services, *, now: datetime | None = None, limit: int = 50
) -> dict[str, int]:
"""Deliver events that are due.
Each event is sent, skipped (email off, or below the minimum severity),
throttled (the same alert was sent recently), or retried later; after the
last retry it is marked failed. Its state is visible in the UI.
Args:
services: Process services.
now: Current time (tests).
limit: Most events handled per call.
Returns:
Count of events per outcome.
"""
now = now or datetime.now(UTC)
counts: dict[str, int] = {}
async with services.db.session() as s, AsyncExitStack() as stack:
cfg = await settings_store.load(s, NotificationSettings)
branding = await settings_store.load(s, Branding)
events = (
(
await s.execute(
select(Event)
.where(
Event.delivery_status == "pending",
(Event.next_attempt_at.is_(None)) | (Event.next_attempt_at <= now),
)
.order_by(Event.id)
.limit(limit)
.with_for_update(skip_locked=True)
)
)
.scalars()
.all()
)
for event in events:
outcome = await _deliver_one(services, s, cfg, branding, event, now, stack)
counts[outcome] = counts.get(outcome, 0) + 1
if counts:
log.info("notifications.delivered", **counts)
return counts
async def _deliver_one(
services: Services,
s: AsyncSession,
cfg: NotificationSettings,
branding: Branding,
event: Event,
now: datetime,
stack: AsyncExitStack,
) -> str:
if not cfg.enabled or not cfg.recipients:
event.delivery_status = "skipped"
event.delivery_error = "email notifications are off"
return "skipped"
below = SEVERITY_ORDER.get(event.severity, 0) < SEVERITY_ORDER[cfg.min_severity]
if below and not (event.body or {}).get("always"):
event.delivery_status = "skipped"
event.delivery_error = f"below the minimum severity ({cfg.min_severity})"
return "skipped"
if event.dedup_key and cfg.throttle_hours:
recent = await s.execute(
select(Event.id)
.where(
Event.dedup_key == event.dedup_key,
Event.delivery_status == "sent",
Event.delivered_at > now - timedelta(hours=cfg.throttle_hours),
)
.limit(1)
)
if recent.first() is not None:
event.delivery_status = "throttled"
event.delivery_error = f"the same alert was sent in the last {cfg.throttle_hours} h"
return "throttled"
message = render(event, branding, services.settings.base_url, cfg.subject_prefix)
try:
note = await send_with_fallback(services, s, cfg, message, stack)
except SendError as exc:
event.delivery_attempts += 1
event.delivery_error = str(exc)
if event.delivery_attempts > len(RETRY_DELAYS):
event.delivery_status = "failed"
return "failed"
event.next_attempt_at = now + RETRY_DELAYS[event.delivery_attempts - 1]
return "retry"
event.delivery_status = "sent"
event.delivered_at = now
event.delivery_error = note
return "sent"
[docs]
async def send_test(services: Services, cfg: NotificationSettings, method: str) -> None:
"""Send a test email with one method (no fallback).
Args:
services: Process services.
cfg: Settings to test (may be unsaved edits).
method: ``graph`` or ``smtp``.
Raises:
SendError: With the reason it failed.
"""
if not cfg.recipients:
raise SendError("add at least one recipient first")
async with services.db.session() as s, AsyncExitStack() as stack:
branding = await settings_store.load(s, Branding)
event = Event(
type="test",
severity=Severity.INFO.value,
subject="Test email",
body={"method": "Microsoft Graph" if method == "graph" else "SMTP"},
)
message = render(event, branding, services.settings.base_url, cfg.subject_prefix)
notifier = await build_notifier(services, s, method, cfg, stack)
await notifier.send(message, cfg.recipients)