Skip to main content

aurelin_framework/
notifications.rs

1//! Recipient-aware notification dispatch with an explicit mail channel.
2
3use std::{any::type_name, error::Error, fmt};
4
5use crate::events::{DispatchError as EventError, DispatchOutcome, EventDispatcher};
6use crate::mail::{MailError, MailMessage, Mailer, SendOutcome};
7use crate::queue::TaskSink;
8use apalis_sqlite::SqliteStorage;
9
10/// An application error encountered while selecting or composing a notification.
11pub type NotificationError = Box<dyn Error + Send + Sync + 'static>;
12
13/// A supported notification delivery channel.
14#[derive(Clone, Copy, Debug, Eq, PartialEq)]
15pub enum Channel {
16    /// Deliver using the configured mailer.
17    Mail,
18}
19
20/// Non-content metadata for a notification channel delivery.
21#[derive(Clone, Debug)]
22pub struct NotificationMetadata {
23    /// The Rust notification type selected by the application.
24    pub notification_type: &'static str,
25    /// The selected channel.
26    pub channel: Channel,
27    /// The destination address; treat it as personal data.
28    pub recipient: String,
29}
30
31/// Before a prepared notification is sent or enqueued. Stop cancels the channel.
32pub struct NotificationSending(pub NotificationMetadata);
33/// A synchronous notification was accepted by its mail transport.
34pub struct NotificationSent(pub NotificationMetadata);
35/// A synchronous notification's mail delivery failed.
36pub struct NotificationFailed(pub NotificationMetadata);
37
38/// Application-owned notification content and channel selection.
39pub trait Notification<Recipient> {
40    /// Select channels separately for each recipient.
41    fn via(&self, recipient: &Recipient) -> Result<Vec<Channel>, NotificationError>;
42
43    /// Compose the application-rendered mail for this recipient.
44    fn to_mail(&self, recipient: &Recipient) -> Result<MailMessage, NotificationError>;
45}
46
47/// Explicit routing for mail notifications, independent of any user model.
48pub trait MailRecipient<N> {
49    /// Return the address to use for this notification, or no route.
50    fn route_mail(&self, notification: &N) -> Result<Option<String>, NotificationError>;
51}
52
53/// An on-demand recipient with an explicit mail address.
54#[derive(Clone, Debug)]
55pub struct AnonymousRecipient {
56    address: String,
57}
58
59impl AnonymousRecipient {
60    /// Create an on-demand mail recipient.
61    pub fn mail(address: impl Into<String>) -> Self {
62        Self { address: address.into() }
63    }
64}
65
66impl<N> MailRecipient<N> for AnonymousRecipient {
67    fn route_mail(&self, _notification: &N) -> Result<Option<String>, NotificationError> {
68        Ok(Some(self.address.clone()))
69    }
70}
71
72/// Dispatches notifications through explicitly supplied channel dependencies.
73#[derive(Clone)]
74pub struct NotificationDispatcher {
75    mailer: Mailer,
76    events: Option<EventDispatcher>,
77}
78
79impl fmt::Debug for NotificationDispatcher {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        f.debug_struct("NotificationDispatcher").finish_non_exhaustive()
82    }
83}
84
85impl NotificationDispatcher {
86    /// Create a dispatcher using the given mailer.
87    pub fn new(mailer: Mailer) -> Self {
88        Self { mailer, events: None }
89    }
90
91    /// Configure notification lifecycle listeners explicitly.
92    pub fn with_events(mut self, events: EventDispatcher) -> Self {
93        self.events = Some(events);
94        self
95    }
96
97    /// Deliver selected channels in order. An empty selection does nothing.
98    pub async fn send<N, R>(&self, recipient: &R, notification: &N) -> Result<(), DispatchError>
99    where
100        N: Notification<R>,
101        R: MailRecipient<N>,
102    {
103        let channels = notification.via(recipient).map_err(DispatchError::Selection)?;
104        for channel in channels {
105            match channel {
106                Channel::Mail => {
107                    if let Some((message, address)) = mail_message(recipient, notification)? {
108                        let metadata =
109                            NotificationMetadata { notification_type: type_name::<N>(), channel, recipient: address };
110                        if !self.sending(&metadata).await? {
111                            continue;
112                        }
113                        match self.mailer.send_with_outcome(message).await {
114                            Ok(SendOutcome::Sent) => {
115                                if let Some(events) = &self.events {
116                                    events.dispatch(NotificationSent(metadata)).await?;
117                                }
118                            }
119                            Ok(SendOutcome::Cancelled) => {}
120                            Err(error) => {
121                                if let Some(events) = &self.events {
122                                    events.dispatch(NotificationFailed(metadata)).await?;
123                                }
124                                return Err(error.into());
125                            }
126                        }
127                    }
128                }
129            }
130        }
131        Ok(())
132    }
133
134    /// Render recipient-specific mail and enqueue it on the existing mail queue.
135    ///
136    /// Content and addresses are persisted in the queue. Applications must
137    /// protect queue storage and register a worker that sends `MailMessage` jobs.
138    pub async fn queue<N, R>(
139        &self,
140        recipient: &R,
141        notification: &N,
142        queue: &mut SqliteStorage<MailMessage>,
143    ) -> Result<(), DispatchError>
144    where
145        N: Notification<R>,
146        R: MailRecipient<N>,
147    {
148        for channel in notification.via(recipient).map_err(DispatchError::Selection)? {
149            match channel {
150                Channel::Mail => {
151                    if let Some((message, address)) = mail_message(recipient, notification)? {
152                        let metadata =
153                            NotificationMetadata { notification_type: type_name::<N>(), channel, recipient: address };
154                        if !self.sending(&metadata).await? {
155                            continue;
156                        }
157                        queue.push(message).await.map_err(|error| DispatchError::Queue(Box::new(error)))?;
158                    }
159                }
160            }
161        }
162        Ok(())
163    }
164
165    async fn sending(&self, metadata: &NotificationMetadata) -> Result<bool, DispatchError> {
166        match &self.events {
167            Some(events) => {
168                Ok(events.dispatch(NotificationSending(metadata.clone())).await? != DispatchOutcome::Stopped)
169            }
170            None => Ok(true),
171        }
172    }
173}
174
175fn mail_message<N, R>(recipient: &R, notification: &N) -> Result<Option<(MailMessage, String)>, DispatchError>
176where
177    N: Notification<R>,
178    R: MailRecipient<N>,
179{
180    let message = notification.to_mail(recipient).map_err(DispatchError::Composition)?;
181    let Some(address) = recipient.route_mail(notification).map_err(DispatchError::Routing)? else {
182        return Ok(None);
183    };
184    Ok(Some((message.routed_to(&address)?, address)))
185}
186
187/// Failure to select, compose, route, or deliver a notification.
188#[derive(Debug, thiserror::Error)]
189pub enum DispatchError {
190    /// Channel selection failed.
191    #[error("notification channel selection failed")]
192    Selection(#[source] NotificationError),
193    /// Notification composition failed.
194    #[error("notification mail composition failed")]
195    Composition(#[source] NotificationError),
196    /// Recipient routing failed.
197    #[error("notification mail routing failed")]
198    Routing(#[source] NotificationError),
199    /// Message construction or transport failed.
200    #[error("notification mail delivery failed")]
201    Mail(#[from] MailError),
202    /// The rendered notification could not be enqueued.
203    #[error("notification queue dispatch failed")]
204    Queue(#[source] Box<dyn Error + Send + Sync>),
205    /// A lifecycle listener failed.
206    #[error(transparent)]
207    Event(#[from] EventError),
208}