ryuk 0.1.1

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
Documentation
//! Laravel-style notifications: one message, delivered over several channels
//! (feature `notifications` = `mail` + `db`).
//!
//! A [`Notification`] says which [`Channel`]s it uses and how to render itself for each; a
//! [`Notifiable`] is whoever receives it (usually a user). [`Notifier::send`] delivers it: mail
//! goes through [`Mailer`], the `database` channel stores a row in the `notifications` table
//! (self-created, SQLite/PostgreSQL/MySQL) that the user can later list and mark as read.
//!
//! A failing channel is logged and does not stop the others; `send` returns one result per
//! channel so the caller decides whether that matters.
//!
//! Every read/update/delete is scoped to the owning notifiable, so one user can never see or
//! touch another user's rows, even with a guessed id.
//!
//! ```
//! use ryuk::notifications::{Channel, Notifiable, Notification};
//! use ryuk::mail::Mail;
//!
//! struct User { id: i64, email: String }
//! impl Notifiable for User {
//!     fn notifiable_id(&self) -> i64 { self.id }
//!     fn mail_address(&self) -> Option<String> { Some(self.email.clone()) }
//! }
//!
//! struct Welcome;
//! impl Notification for Welcome {
//!     fn via(&self) -> Vec<Channel> { vec![Channel::Mail, Channel::Database] }
//!     fn to_mail(&self, _to: &dyn Notifiable) -> Mail {
//!         Mail::new().subject("Welcome").text("Glad you are here.")
//!     }
//!     fn to_database(&self) -> serde_json::Value { serde_json::json!({ "msg": "welcome" }) }
//! }
//! # let _ = (User { id: 1, email: "a@b.c".into() }, Welcome);
//! // let results = notifier.send(&user, &Welcome).await;
//! // let unread = notifier.unread(&user).await?;
//! ```
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;

/// `notifications` table.
pub mod stored {
    use sea_orm::entity::prelude::*;
    /// One stored notification.
    #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "notifications")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i64,
        /// Owner (see [`super::Notifiable::notifiable_id`]).
        pub notifiable_id: i64,
        /// Notification type name, from [`super::Notification::kind`].
        pub kind: String,
        /// JSON text from `to_database` (text, so every backend stores it the same way).
        pub data: String,
        /// Unix seconds; `None` while unread.
        pub read_at: Option<i64>,
        /// Unix seconds.
        pub created_at: i64,
    }
    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}
    impl ActiveModelBehavior for ActiveModel {}
}
use stored::{Column, Entity};

/// Where a notification is delivered.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Channel {
    /// Email through the [`Mailer`].
    Mail,
    /// A row in the `notifications` table.
    Database,
}

/// Who receives notifications.
pub trait Notifiable: Send + Sync {
    /// Stable owner id; all stored notifications are scoped to it.
    fn notifiable_id(&self) -> i64;
    /// Email address for the mail channel, `None` if they have none.
    fn mail_address(&self) -> Option<String> {
        None
    }
}

/// A message that can be delivered over several channels.
pub trait Notification: Send + Sync {
    /// Channels to deliver on.
    fn via(&self) -> Vec<Channel>;
    /// Email content. The recipient is filled in from [`Notifiable::mail_address`] when `to` is empty.
    fn to_mail(&self, _notifiable: &dyn Notifiable) -> Mail {
        Mail::new()
    }
    /// Payload stored by the database channel.
    fn to_database(&self) -> serde_json::Value {
        serde_json::Value::Null
    }
    /// Type name stored with the row (default: `"notification"`; override to filter in the UI).
    fn kind(&self) -> String {
        "notification".into()
    }
}

/// Delivery or storage failure.
#[derive(Debug, thiserror::Error)]
pub enum NotifyError {
    /// Database error.
    #[error("database: {0}")]
    Db(#[from] DbErr),
    /// Mail error.
    #[error("mail: {0}")]
    Mail(#[from] MailError),
    /// The mail channel was requested but the notifiable has no address.
    #[error("notifiable has no mail address")]
    NoAddress,
}

/// Sends notifications and manages the stored (database channel) ones.
#[derive(Clone)]
pub struct Notifier {
    db: DatabaseConnection,
    mailer: Mailer,
}

fn now() -> i64 {
    chrono::Utc::now().timestamp()
}

impl Notifier {
    /// Notifier over `db` and `mailer`.
    pub fn new(db: DatabaseConnection, mailer: Mailer) -> Self {
        Self { db, mailer }
    }

    /// Create `notifications` if missing.
    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(())
    }

    /// Deliver `n` to `to` on every channel in `n.via()`. A failing channel is logged and the
    /// rest still run; the result of each is returned in `via()` order.
    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(())
    }

    /// The owner's unread notifications, newest first.
    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
    }

    /// All of the owner's notifications, newest first.
    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
    }

    /// Mark one of the owner's notifications read; `false` if it is not theirs, missing or already read.
    pub async fn mark_as_read(&self, who: &dyn Notifiable, id: i64) -> Result<bool, DbErr> {
        Ok(self.mark(who, Some(id)).await? == 1)
    }

    /// Mark all of the owner's unread notifications read; returns how many.
    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)
    }

    /// Delete one of the owner's notifications; `false` if it is not theirs or missing.
    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)
    }

    /// Delete every owner's notifications older than `age` (a maintenance job, not user-facing);
    /// returns how many.
    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)
    }
}

// shortcut: only the built-in mail and database channels; a pluggable ChannelDriver trait
// (SMS, Slack) is the upgrade when a third channel is needed.

#[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));
            // clean slate for shared external servers
            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;

            // owner scoping: a cannot mark or delete b's row
            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);
    }
}