use larust_auth::{authorize, Authenticatable};
use larust_core::AppError;
use larust_mail::Mailable;
use larust_orm::Backend;
use serde::Serialize;
use sqlx::AnyPool;
use std::future::Future;
use std::pin::Pin;
use std::time::{SystemTime, UNIX_EPOCH};
pub trait Notification: Serialize + Send + Sync {
const NOTIFICATION_TYPE: &'static str;
}
#[derive(Debug, Clone)]
pub struct StoredNotification {
pub id: i64,
pub notification_type: String,
pub data: serde_json::Value,
pub read_at: Option<i64>,
pub created_at: i64,
}
async fn ensure_table(pool: &AnyPool) -> Result<(), AppError> {
let create_table = match larust_orm::backend() {
Backend::Sqlite => {
"CREATE TABLE IF NOT EXISTS notifications (\
id INTEGER PRIMARY KEY AUTOINCREMENT, \
notifiable_id INTEGER NOT NULL, \
notification_type TEXT NOT NULL, \
data TEXT NOT NULL, \
read_at INTEGER, \
created_at INTEGER NOT NULL\
)"
}
Backend::MySql => {
"CREATE TABLE IF NOT EXISTS notifications (\
id INTEGER PRIMARY KEY AUTO_INCREMENT, \
notifiable_id INTEGER NOT NULL, \
notification_type VARCHAR(255) NOT NULL, \
data VARCHAR(4000) NOT NULL, \
read_at INTEGER, \
created_at INTEGER NOT NULL\
)"
}
Backend::Postgres => {
"CREATE TABLE IF NOT EXISTS notifications (\
id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, \
notifiable_id INTEGER NOT NULL, \
notification_type TEXT NOT NULL, \
data TEXT NOT NULL, \
read_at INTEGER, \
created_at INTEGER NOT NULL\
)"
}
};
sqlx::query(create_table)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
match larust_orm::backend() {
Backend::Sqlite | Backend::Postgres => {
sqlx::query(
"CREATE INDEX IF NOT EXISTS idx_notifications_notifiable \
ON notifications (notifiable_id, created_at DESC)",
)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
}
Backend::MySql => {
if let Err(error) = sqlx::query(
"CREATE INDEX idx_notifications_notifiable \
ON notifications (notifiable_id, created_at DESC)",
)
.execute(pool)
.await
{
let duplicate_key = matches!(&error, sqlx::Error::Database(database)
if database.message().contains("Duplicate key name"));
if !duplicate_key {
return Err(AppError::Internal(Box::new(error)));
}
}
}
}
Ok(())
}
fn now_unix_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock is before the Unix epoch")
.as_secs() as i64
}
pub async fn notify<U: Authenticatable, N: Notification>(
notifiable: &U,
notification: &N,
) -> Result<(), AppError> {
let pool = larust_orm::pool()?;
ensure_table(pool).await?;
let data = serde_json::to_string(notification)
.map_err(|source| AppError::Internal(Box::new(source)))?;
let backend = larust_orm::backend();
let insert_sql = format!(
"INSERT INTO notifications (notifiable_id, notification_type, data, created_at) \
VALUES ({}, {}, {}, {})",
larust_orm::placeholder(backend, 1),
larust_orm::placeholder(backend, 2),
larust_orm::placeholder(backend, 3),
larust_orm::placeholder(backend, 4),
);
sqlx::query(&insert_sql)
.bind(notifiable.auth_id())
.bind(N::NOTIFICATION_TYPE)
.bind(data)
.bind(now_unix_secs())
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
pub async fn notify_and_mail<U, N, M>(
notifiable: &U,
notification: &N,
email: &str,
mailable: M,
) -> Result<(), AppError>
where
U: Authenticatable + Sync,
N: Notification + Sync,
M: Mailable,
{
tokio::try_join!(
notify(notifiable, notification),
larust_mail::mail().to(email).send(mailable),
)?;
Ok(())
}
pub trait MailNotification: Send + Sync {
type Mail: Mailable + Send + 'static;
fn to_mail(&self) -> Self::Mail;
}
pub trait MailNotifiable: Authenticatable {
fn notification_email(&self) -> String;
}
type BoxedDelivery<'a> = Pin<Box<dyn Future<Output = Result<(), AppError>> + Send + 'a>>;
pub struct PendingNotification<'a, U, N> {
notifiable: &'a U,
notification: &'a N,
channels: Vec<BoxedDelivery<'a>>,
}
pub fn to<'a, U, N>(notifiable: &'a U, notification: &'a N) -> PendingNotification<'a, U, N> {
PendingNotification {
notifiable,
notification,
channels: Vec::new(),
}
}
impl<'a, U, N> PendingNotification<'a, U, N> {
#[must_use]
pub fn database(mut self) -> Self
where
U: Authenticatable,
N: Notification,
{
self.channels
.push(Box::pin(notify(self.notifiable, self.notification)));
self
}
#[must_use]
pub fn mail(mut self) -> Self
where
U: MailNotifiable,
N: MailNotification,
{
let email = self.notifiable.notification_email();
let mailable = self.notification.to_mail();
self.channels.push(Box::pin(async move {
larust_mail::mail().to(email).send(mailable).await
}));
self
}
pub async fn send(self) -> Result<(), AppError> {
if self.channels.is_empty() {
tracing::warn!(
"notification::to(...).send() called with no channel selected \
(.database()/.mail()) - nothing was sent"
);
return Ok(());
}
for channel in self.channels {
channel.await?;
}
Ok(())
}
}
pub async fn notifications_for<U: Authenticatable>(
notifiable: &U,
limit: i64,
) -> Result<Vec<StoredNotification>, AppError> {
let pool = larust_orm::pool()?;
ensure_table(pool).await?;
let backend = larust_orm::backend();
let select_sql = format!(
"SELECT id, notification_type, data, read_at, created_at FROM notifications \
WHERE notifiable_id = {} ORDER BY created_at DESC, id DESC LIMIT {}",
larust_orm::placeholder(backend, 1),
larust_orm::placeholder(backend, 2),
);
let rows: Vec<(i64, String, String, Option<i64>, i64)> = sqlx::query_as(&select_sql)
.bind(notifiable.auth_id())
.bind(limit)
.fetch_all(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
rows.into_iter()
.map(|(id, notification_type, data, read_at, created_at)| {
Ok(StoredNotification {
id,
notification_type,
data: serde_json::from_str(&data)
.map_err(|source| AppError::Internal(Box::new(source)))?,
read_at,
created_at,
})
})
.collect()
}
pub async fn unread_count<U: Authenticatable>(notifiable: &U) -> Result<i64, AppError> {
let pool = larust_orm::pool()?;
ensure_table(pool).await?;
let select_sql = format!(
"SELECT COUNT(*) FROM notifications WHERE notifiable_id = {} AND read_at IS NULL",
larust_orm::placeholder(larust_orm::backend(), 1)
);
let (count,): (i64,) = sqlx::query_as(&select_sql)
.bind(notifiable.auth_id())
.fetch_one(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(count)
}
pub async fn mark_as_read<U: Authenticatable>(
notifiable: &U,
notification_id: i64,
) -> Result<(), AppError> {
let pool = larust_orm::pool()?;
ensure_table(pool).await?;
let backend = larust_orm::backend();
let select_owner_sql = format!(
"SELECT notifiable_id FROM notifications WHERE id = {}",
larust_orm::placeholder(backend, 1)
);
let owner: Option<(i64,)> = sqlx::query_as(&select_owner_sql)
.bind(notification_id)
.fetch_optional(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
let Some((owner_id,)) = owner else {
return Err(AppError::NotFound);
};
authorize(owner_id == notifiable.auth_id())?;
let update_sql = format!(
"UPDATE notifications SET read_at = {} WHERE id = {}",
larust_orm::placeholder(backend, 1),
larust_orm::placeholder(backend, 2),
);
sqlx::query(&update_sql)
.bind(now_unix_secs())
.bind(notification_id)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
pub async fn mark_all_as_read<U: Authenticatable>(notifiable: &U) -> Result<(), AppError> {
let pool = larust_orm::pool()?;
ensure_table(pool).await?;
let backend = larust_orm::backend();
let sql = format!(
"UPDATE notifications SET read_at = {} WHERE notifiable_id = {} AND read_at IS NULL",
larust_orm::placeholder(backend, 1),
larust_orm::placeholder(backend, 2),
);
sqlx::query(&sql)
.bind(now_unix_secs())
.bind(notifiable.auth_id())
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
pub async fn delete_notification<U: Authenticatable>(
notifiable: &U,
notification_id: i64,
) -> Result<(), AppError> {
let pool = larust_orm::pool()?;
ensure_table(pool).await?;
let backend = larust_orm::backend();
let select_owner_sql = format!(
"SELECT notifiable_id FROM notifications WHERE id = {}",
larust_orm::placeholder(backend, 1)
);
let owner: Option<(i64,)> = sqlx::query_as(&select_owner_sql)
.bind(notification_id)
.fetch_optional(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
let Some((owner_id,)) = owner else {
return Err(AppError::NotFound);
};
authorize(owner_id == notifiable.auth_id())?;
let delete_sql = format!(
"DELETE FROM notifications WHERE id = {}",
larust_orm::placeholder(backend, 1)
);
sqlx::query(&delete_sql)
.bind(notification_id)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
pub async fn clear_notifications<U: Authenticatable>(notifiable: &U) -> Result<(), AppError> {
let pool = larust_orm::pool()?;
ensure_table(pool).await?;
let sql = format!(
"DELETE FROM notifications WHERE notifiable_id = {}",
larust_orm::placeholder(larust_orm::backend(), 1)
);
sqlx::query(&sql)
.bind(notifiable.auth_id())
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
struct TestUser {
id: i64,
}
impl Authenticatable for TestUser {
fn auth_id(&self) -> i64 {
self.id
}
async fn find_for_auth(_id: i64) -> Result<Option<Self>, AppError> {
unreachable!("not exercised by these tests")
}
}
#[derive(Serialize, Deserialize)]
struct Greeting {
message: String,
}
impl Notification for Greeting {
const NOTIFICATION_TYPE: &'static str = "greeting";
}
async fn connect_test_db() {
let dir = tempfile::tempdir().unwrap().keep();
let database_url = format!("sqlite://{}/test.sqlite", dir.display());
larust_orm::connect(&database_url).await.unwrap();
}
async fn greet<U: Authenticatable>(notifiable: &U, message: &str) {
notify(
notifiable,
&Greeting {
message: message.to_string(),
},
)
.await
.unwrap();
}
#[tokio::test]
async fn notifications_crate_behaves_correctly_across_every_scenario() {
connect_test_db().await;
let alice = TestUser { id: 1 };
let bob = TestUser { id: 2 };
greet(&alice, "first").await;
greet(&alice, "second").await;
greet(&bob, "for bob").await;
let alice_notifications = notifications_for(&alice, 10).await.unwrap();
assert_eq!(alice_notifications.len(), 2);
assert_eq!(alice_notifications[0].data["message"], "second");
assert_eq!(alice_notifications[1].data["message"], "first");
assert_eq!(alice_notifications[0].notification_type, "greeting");
let carol = TestUser { id: 3 };
greet(&carol, "a").await;
greet(&carol, "b").await;
greet(&carol, "c").await;
assert_eq!(unread_count(&carol).await.unwrap(), 3);
let first_id = notifications_for(&carol, 10).await.unwrap()[2].id;
mark_as_read(&carol, first_id).await.unwrap();
assert_eq!(unread_count(&carol).await.unwrap(), 2);
let dave = TestUser { id: 4 };
greet(&dave, "hi").await;
let dave_id = notifications_for(&dave, 1).await.unwrap()[0].id;
mark_as_read(&dave, dave_id).await.unwrap();
mark_as_read(&dave, dave_id).await.unwrap();
assert_eq!(unread_count(&dave).await.unwrap(), 0);
let erin = TestUser { id: 5 };
let frank = TestUser { id: 6 };
greet(&erin, "erin's").await;
let erin_notification_id = notifications_for(&erin, 1).await.unwrap()[0].id;
match mark_as_read(&frank, erin_notification_id).await {
Err(AppError::Http { status, .. }) => {
assert_eq!(status, larust_core::axum::http::StatusCode::FORBIDDEN);
}
Err(other) => panic!("expected AppError::Http{{FORBIDDEN, ..}}, got {other:?}"),
Ok(()) => panic!("expected AppError::Http{{FORBIDDEN, ..}}, got Ok(())"),
}
assert_eq!(
unread_count(&erin).await.unwrap(),
1,
"erin's notification must still be unread"
);
assert!(matches!(
mark_as_read(&erin, 999_999).await,
Err(AppError::NotFound)
));
let grace = TestUser { id: 7 };
let heidi = TestUser { id: 8 };
greet(&grace, "grace's").await;
greet(&heidi, "heidi's").await;
mark_all_as_read(&grace).await.unwrap();
assert_eq!(unread_count(&grace).await.unwrap(), 0);
assert_eq!(unread_count(&heidi).await.unwrap(), 1);
let judy = TestUser { id: 10 };
let karl = TestUser { id: 11 };
greet(&judy, "remove me").await;
greet(&karl, "keep me").await;
let judy_id = notifications_for(&judy, 1).await.unwrap()[0].id;
delete_notification(&judy, judy_id).await.unwrap();
assert!(notifications_for(&judy, 10).await.unwrap().is_empty());
clear_notifications(&judy).await.unwrap();
assert_eq!(notifications_for(&karl, 10).await.unwrap().len(), 1);
let ivan = TestUser { id: 9 };
for i in 0..5 {
greet(&ivan, &format!("message {i}")).await;
}
assert_eq!(notifications_for(&ivan, 2).await.unwrap().len(), 2);
larust_mail::fake();
let liam = TestUser { id: 12 };
notify_and_mail(
&liam,
&Greeting {
message: "concurrent".to_string(),
},
"liam@example.com",
WelcomeMail,
)
.await
.unwrap();
let liam_notifications = notifications_for(&liam, 10).await.unwrap();
assert_eq!(liam_notifications.len(), 1);
assert_eq!(liam_notifications[0].data["message"], "concurrent");
larust_mail::assert_sent::<WelcomeMail>(|sent| {
sent.to == vec!["liam@example.com".to_string()] && sent.subject == "Welcome"
});
let mia = TestUser { id: 100 };
to(
&mia,
&Greeting {
message: "builder database+mail".to_string(),
},
)
.database()
.mail()
.send()
.await
.unwrap();
let mia_notifications = notifications_for(&mia, 10).await.unwrap();
assert_eq!(mia_notifications.len(), 1);
assert_eq!(
mia_notifications[0].data["message"],
"builder database+mail"
);
larust_mail::assert_sent::<GreetingMail>(|sent| {
sent.to == vec!["user100@example.com".to_string()]
&& sent.subject == "You have a greeting"
});
let noah = TestUser { id: 101 };
to(
&noah,
&Greeting {
message: "mail only".to_string(),
},
)
.mail()
.send()
.await
.unwrap();
assert!(notifications_for(&noah, 10).await.unwrap().is_empty());
larust_mail::assert_sent::<GreetingMail>(|sent| {
sent.to == vec!["user101@example.com".to_string()]
});
let olive = TestUser { id: 102 };
to(
&olive,
&Greeting {
message: "nobody asked".to_string(),
},
)
.send()
.await
.unwrap();
assert!(notifications_for(&olive, 10).await.unwrap().is_empty());
}
struct WelcomeMail;
impl Mailable for WelcomeMail {
fn subject(&self) -> String {
"Welcome".to_string()
}
fn html_body(&self) -> String {
"<p>hi</p>".to_string()
}
}
impl MailNotifiable for TestUser {
fn notification_email(&self) -> String {
format!("user{}@example.com", self.id)
}
}
impl MailNotification for Greeting {
type Mail = GreetingMail;
fn to_mail(&self) -> Self::Mail {
GreetingMail {
message: self.message.clone(),
}
}
}
struct GreetingMail {
message: String,
}
impl Mailable for GreetingMail {
fn subject(&self) -> String {
"You have a greeting".to_string()
}
fn html_body(&self) -> String {
format!("<p>{}</p>", self.message)
}
}
}