aurelin_framework/
notifications.rs1use 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
10pub type NotificationError = Box<dyn Error + Send + Sync + 'static>;
12
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
15pub enum Channel {
16 Mail,
18}
19
20#[derive(Clone, Debug)]
22pub struct NotificationMetadata {
23 pub notification_type: &'static str,
25 pub channel: Channel,
27 pub recipient: String,
29}
30
31pub struct NotificationSending(pub NotificationMetadata);
33pub struct NotificationSent(pub NotificationMetadata);
35pub struct NotificationFailed(pub NotificationMetadata);
37
38pub trait Notification<Recipient> {
40 fn via(&self, recipient: &Recipient) -> Result<Vec<Channel>, NotificationError>;
42
43 fn to_mail(&self, recipient: &Recipient) -> Result<MailMessage, NotificationError>;
45}
46
47pub trait MailRecipient<N> {
49 fn route_mail(&self, notification: &N) -> Result<Option<String>, NotificationError>;
51}
52
53#[derive(Clone, Debug)]
55pub struct AnonymousRecipient {
56 address: String,
57}
58
59impl AnonymousRecipient {
60 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#[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 pub fn new(mailer: Mailer) -> Self {
88 Self { mailer, events: None }
89 }
90
91 pub fn with_events(mut self, events: EventDispatcher) -> Self {
93 self.events = Some(events);
94 self
95 }
96
97 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 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#[derive(Debug, thiserror::Error)]
189pub enum DispatchError {
190 #[error("notification channel selection failed")]
192 Selection(#[source] NotificationError),
193 #[error("notification mail composition failed")]
195 Composition(#[source] NotificationError),
196 #[error("notification mail routing failed")]
198 Routing(#[source] NotificationError),
199 #[error("notification mail delivery failed")]
201 Mail(#[from] MailError),
202 #[error("notification queue dispatch failed")]
204 Queue(#[source] Box<dyn Error + Send + Sync>),
205 #[error(transparent)]
207 Event(#[from] EventError),
208}