use crate::mail::{Mail, MailError, Mailer};
use sea_orm::entity::prelude::*;
use sea_orm::{
ActiveValue::Set, ConnectionTrait, DatabaseConnection, DbErr, QueryFilter, QueryOrder, Schema,
};
use std::time::Duration;
pub mod stored {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "notifications")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub notifiable_id: i64,
pub kind: String,
pub data: String,
pub read_at: Option<i64>,
pub created_at: i64,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
use stored::{Column, Entity};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Channel {
Mail,
Database,
}
pub trait Notifiable: Send + Sync {
fn notifiable_id(&self) -> i64;
fn mail_address(&self) -> Option<String> {
None
}
}
pub trait Notification: Send + Sync {
fn via(&self) -> Vec<Channel>;
fn to_mail(&self, _notifiable: &dyn Notifiable) -> Mail {
Mail::new()
}
fn to_database(&self) -> serde_json::Value {
serde_json::Value::Null
}
fn kind(&self) -> String {
"notification".into()
}
}
#[derive(Debug, thiserror::Error)]
pub enum NotifyError {
#[error("database: {0}")]
Db(#[from] DbErr),
#[error("mail: {0}")]
Mail(#[from] MailError),
#[error("notifiable has no mail address")]
NoAddress,
}
#[derive(Clone)]
pub struct Notifier {
db: DatabaseConnection,
mailer: Mailer,
}
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
impl Notifier {
pub fn new(db: DatabaseConnection, mailer: Mailer) -> Self {
Self { db, mailer }
}
pub async fn ensure_tables(&self) -> Result<(), DbErr> {
let mut t = Schema::new(self.db.get_database_backend()).create_table_from_entity(Entity);
self.db.execute(t.if_not_exists()).await?;
Ok(())
}
pub async fn send(
&self,
to: &dyn Notifiable,
n: &dyn Notification,
) -> Vec<(Channel, Result<(), NotifyError>)> {
let mut out = Vec::new();
for ch in n.via() {
let r = match ch {
Channel::Mail => self.send_mail(to, n).await,
Channel::Database => self.store(to, n).await,
};
if let Err(e) = &r {
tracing::warn!("notification {ch:?} channel failed: {e}");
}
out.push((ch, r));
}
out
}
async fn send_mail(
&self,
to: &dyn Notifiable,
n: &dyn Notification,
) -> Result<(), NotifyError> {
let mut mail = n.to_mail(to);
if mail.to.is_empty() {
mail.to
.push(to.mail_address().ok_or(NotifyError::NoAddress)?);
}
Ok(self.mailer.send(mail).await?)
}
async fn store(&self, to: &dyn Notifiable, n: &dyn Notification) -> Result<(), NotifyError> {
stored::ActiveModel {
notifiable_id: Set(to.notifiable_id()),
kind: Set(n.kind()),
data: Set(n.to_database().to_string()),
read_at: Set(None),
created_at: Set(now()),
..Default::default()
}
.insert(&self.db)
.await?;
Ok(())
}
pub async fn unread(&self, who: &dyn Notifiable) -> Result<Vec<stored::Model>, DbErr> {
Entity::find()
.filter(Column::NotifiableId.eq(who.notifiable_id()))
.filter(Column::ReadAt.is_null())
.order_by_desc(Column::Id)
.all(&self.db)
.await
}
pub async fn all(&self, who: &dyn Notifiable) -> Result<Vec<stored::Model>, DbErr> {
Entity::find()
.filter(Column::NotifiableId.eq(who.notifiable_id()))
.order_by_desc(Column::Id)
.all(&self.db)
.await
}
pub async fn mark_as_read(&self, who: &dyn Notifiable, id: i64) -> Result<bool, DbErr> {
Ok(self.mark(who, Some(id)).await? == 1)
}
pub async fn mark_all_as_read(&self, who: &dyn Notifiable) -> Result<u64, DbErr> {
self.mark(who, None).await
}
async fn mark(&self, who: &dyn Notifiable, id: Option<i64>) -> Result<u64, DbErr> {
let mut q = Entity::update_many()
.col_expr(Column::ReadAt, Expr::value(now()))
.filter(Column::NotifiableId.eq(who.notifiable_id()))
.filter(Column::ReadAt.is_null());
if let Some(id) = id {
q = q.filter(Column::Id.eq(id));
}
Ok(q.exec(&self.db).await?.rows_affected)
}
pub async fn delete(&self, who: &dyn Notifiable, id: i64) -> Result<bool, DbErr> {
let r = Entity::delete_many()
.filter(Column::NotifiableId.eq(who.notifiable_id()))
.filter(Column::Id.eq(id))
.exec(&self.db)
.await?;
Ok(r.rows_affected == 1)
}
pub async fn prune_older_than(&self, age: Duration) -> Result<u64, DbErr> {
let cutoff = now().saturating_sub(age.as_secs().min(i64::MAX as u64 / 2) as i64);
Ok(Entity::delete_many()
.filter(Column::CreatedAt.lt(cutoff))
.exec(&self.db)
.await?
.rows_affected)
}
}
#[cfg(all(test, feature = "sqlite"))]
mod tests {
use super::*;
struct U(i64, Option<&'static str>);
impl Notifiable for U {
fn notifiable_id(&self) -> i64 {
self.0
}
fn mail_address(&self) -> Option<String> {
self.1.map(Into::into)
}
}
struct Hello(Vec<Channel>);
impl Notification for Hello {
fn via(&self) -> Vec<Channel> {
self.0.clone()
}
fn to_mail(&self, _: &dyn Notifiable) -> Mail {
Mail::new().subject("hi").text("body")
}
fn to_database(&self) -> serde_json::Value {
serde_json::json!({"k": 1})
}
}
async fn dbs() -> Vec<(&'static str, DatabaseConnection)> {
let ns = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let path = std::env::temp_dir().join(format!("ryuk-notif-{ns}.db"));
let mut v = vec![(
"sqlite",
sea_orm::Database::connect(format!("sqlite://{}?mode=rwc", path.display()))
.await
.unwrap(),
)];
for (name, var) in [
("postgres", "TEST_POSTGRES_URL"),
("mysql", "TEST_MYSQL_URL"),
] {
if let Ok(url) = std::env::var(var) {
v.push((name, sea_orm::Database::connect(url).await.unwrap()));
}
}
v
}
#[tokio::test]
async fn send_store_read_scope_prune() {
for (name, db) in dbs().await {
let n = Notifier::new(db.clone(), Mailer::log("app@example.com"));
n.ensure_tables().await.unwrap();
n.ensure_tables().await.unwrap();
let (a, b) = (U(1, Some("a@example.com")), U(2, None));
Entity::delete_many().exec(&db).await.unwrap();
let both = Hello(vec![Channel::Mail, Channel::Database]);
let r = n.send(&a, &both).await;
assert!(r.iter().all(|(_, r)| r.is_ok()), "{name}");
n.send(&a, &Hello(vec![Channel::Database])).await;
n.send(&b, &Hello(vec![Channel::Database])).await;
let un = n.unread(&a).await.unwrap();
assert_eq!(un.len(), 2, "{name}");
assert_eq!(un[0].data, r#"{"k":1}"#);
let b_id = n.all(&b).await.unwrap()[0].id;
assert!(!n.mark_as_read(&a, b_id).await.unwrap(), "{name}");
assert!(!n.delete(&a, b_id).await.unwrap(), "{name}");
assert_eq!(n.unread(&b).await.unwrap().len(), 1);
assert!(n.mark_as_read(&a, un[0].id).await.unwrap());
assert!(!n.mark_as_read(&a, un[0].id).await.unwrap(), "already read");
assert_eq!(n.unread(&a).await.unwrap().len(), 1);
assert_eq!(n.all(&a).await.unwrap().len(), 2);
assert_eq!(n.mark_all_as_read(&a).await.unwrap(), 1);
assert!(n.unread(&a).await.unwrap().is_empty());
assert_eq!(n.unread(&b).await.unwrap().len(), 1, "b untouched");
assert!(n.delete(&b, b_id).await.unwrap());
assert_eq!(
n.prune_older_than(Duration::from_secs(3600)).await.unwrap(),
0
);
Entity::update_many()
.col_expr(Column::CreatedAt, Expr::value(now() - 7200))
.exec(&db)
.await
.unwrap();
assert_eq!(
n.prune_older_than(Duration::from_secs(3600)).await.unwrap(),
2,
"{name}"
);
}
}
#[tokio::test]
async fn failing_channel_does_not_stop_the_others() {
let db = dbs().await.remove(0).1;
let n = Notifier::new(db, Mailer::log("app@example.com"));
n.ensure_tables().await.unwrap();
let nobody = U(3, None);
let r = n
.send(&nobody, &Hello(vec![Channel::Mail, Channel::Database]))
.await;
assert!(matches!(r[0], (Channel::Mail, Err(NotifyError::NoAddress))));
assert!(r[1].1.is_ok());
assert_eq!(n.unread(&nobody).await.unwrap().len(), 1);
}
}