use std::{any::type_name, error::Error, fmt};
use crate::events::{DispatchError as EventError, DispatchOutcome, EventDispatcher};
use crate::mail::{MailError, MailMessage, Mailer, SendOutcome};
use crate::queue::TaskSink;
use apalis_sqlite::SqliteStorage;
pub type NotificationError = Box<dyn Error + Send + Sync + 'static>;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Channel {
Mail,
}
#[derive(Clone, Debug)]
pub struct NotificationMetadata {
pub notification_type: &'static str,
pub channel: Channel,
pub recipient: String,
}
pub struct NotificationSending(pub NotificationMetadata);
pub struct NotificationSent(pub NotificationMetadata);
pub struct NotificationFailed(pub NotificationMetadata);
pub trait Notification<Recipient> {
fn via(&self, recipient: &Recipient) -> Result<Vec<Channel>, NotificationError>;
fn to_mail(&self, recipient: &Recipient) -> Result<MailMessage, NotificationError>;
}
pub trait MailRecipient<N> {
fn route_mail(&self, notification: &N) -> Result<Option<String>, NotificationError>;
}
#[derive(Clone, Debug)]
pub struct AnonymousRecipient {
address: String,
}
impl AnonymousRecipient {
pub fn mail(address: impl Into<String>) -> Self {
Self { address: address.into() }
}
}
impl<N> MailRecipient<N> for AnonymousRecipient {
fn route_mail(&self, _notification: &N) -> Result<Option<String>, NotificationError> {
Ok(Some(self.address.clone()))
}
}
#[derive(Clone)]
pub struct NotificationDispatcher {
mailer: Mailer,
events: Option<EventDispatcher>,
}
impl fmt::Debug for NotificationDispatcher {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NotificationDispatcher").finish_non_exhaustive()
}
}
impl NotificationDispatcher {
pub fn new(mailer: Mailer) -> Self {
Self { mailer, events: None }
}
pub fn with_events(mut self, events: EventDispatcher) -> Self {
self.events = Some(events);
self
}
pub async fn send<N, R>(&self, recipient: &R, notification: &N) -> Result<(), DispatchError>
where
N: Notification<R>,
R: MailRecipient<N>,
{
let channels = notification.via(recipient).map_err(DispatchError::Selection)?;
for channel in channels {
match channel {
Channel::Mail => {
if let Some((message, address)) = mail_message(recipient, notification)? {
let metadata =
NotificationMetadata { notification_type: type_name::<N>(), channel, recipient: address };
if !self.sending(&metadata).await? {
continue;
}
match self.mailer.send_with_outcome(message).await {
Ok(SendOutcome::Sent) => {
if let Some(events) = &self.events {
events.dispatch(NotificationSent(metadata)).await?;
}
}
Ok(SendOutcome::Cancelled) => {}
Err(error) => {
if let Some(events) = &self.events {
events.dispatch(NotificationFailed(metadata)).await?;
}
return Err(error.into());
}
}
}
}
}
}
Ok(())
}
pub async fn queue<N, R>(
&self,
recipient: &R,
notification: &N,
queue: &mut SqliteStorage<MailMessage>,
) -> Result<(), DispatchError>
where
N: Notification<R>,
R: MailRecipient<N>,
{
for channel in notification.via(recipient).map_err(DispatchError::Selection)? {
match channel {
Channel::Mail => {
if let Some((message, address)) = mail_message(recipient, notification)? {
let metadata =
NotificationMetadata { notification_type: type_name::<N>(), channel, recipient: address };
if !self.sending(&metadata).await? {
continue;
}
queue.push(message).await.map_err(|error| DispatchError::Queue(Box::new(error)))?;
}
}
}
}
Ok(())
}
async fn sending(&self, metadata: &NotificationMetadata) -> Result<bool, DispatchError> {
match &self.events {
Some(events) => {
Ok(events.dispatch(NotificationSending(metadata.clone())).await? != DispatchOutcome::Stopped)
}
None => Ok(true),
}
}
}
fn mail_message<N, R>(recipient: &R, notification: &N) -> Result<Option<(MailMessage, String)>, DispatchError>
where
N: Notification<R>,
R: MailRecipient<N>,
{
let message = notification.to_mail(recipient).map_err(DispatchError::Composition)?;
let Some(address) = recipient.route_mail(notification).map_err(DispatchError::Routing)? else {
return Ok(None);
};
Ok(Some((message.routed_to(&address)?, address)))
}
#[derive(Debug, thiserror::Error)]
pub enum DispatchError {
#[error("notification channel selection failed")]
Selection(#[source] NotificationError),
#[error("notification mail composition failed")]
Composition(#[source] NotificationError),
#[error("notification mail routing failed")]
Routing(#[source] NotificationError),
#[error("notification mail delivery failed")]
Mail(#[from] MailError),
#[error("notification queue dispatch failed")]
Queue(#[source] Box<dyn Error + Send + Sync>),
#[error(transparent)]
Event(#[from] EventError),
}