From 4ca470c9e098dec4cbeed3d96f42bd8f3c2d23f4 Mon Sep 17 00:00:00 2001 From: Ahmet TURGUT <33184485+turgutahmet@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:28:53 +0300 Subject: [PATCH] Add the database notification channel A `database` method in a `#[notification]` impl stores the notification in the `notifications` table for every model it's sent to. Models read their notifications back with `DatabaseNotification::of`, and mark them as read or unread one at a time or all at once. `laravel::notification::table!()` creates the table. --- crates/notifications/src/lib.rs | 6 + crates/notifications/src/notification.rs | 16 + .../src/notification/database.rs | 442 ++++++++++++++++++ docs/migrations.md | 1 + docs/notifications.md | 137 +++++- macros/database/src/lib.rs | 9 +- macros/database/src/tables.rs | 16 + macros/queue/src/notification.rs | 59 ++- src/notification.rs | 26 +- .../2026_01_01_000000_create_devices_table.rs | 10 + ...01_02_000000_create_notifications_table.rs | 14 + ...6_01_01_000000_create_notifiable_tables.rs | 14 + ...01_02_000000_create_notifications_table.rs | 1 + .../2026_01_03_000000_create_jobs_tables.rs | 1 + tests/notifications_database.rs | 354 ++++++++++++++ tests/suite_queue.rs | 2 + 16 files changed, 1097 insertions(+), 11 deletions(-) create mode 100644 crates/notifications/src/notification/database.rs create mode 100644 tests/fixtures/migrations/notifications-uuid/2026_01_01_000000_create_devices_table.rs create mode 100644 tests/fixtures/migrations/notifications-uuid/2026_01_02_000000_create_notifications_table.rs create mode 100644 tests/fixtures/migrations/notifications/2026_01_01_000000_create_notifiable_tables.rs create mode 100644 tests/fixtures/migrations/notifications/2026_01_02_000000_create_notifications_table.rs create mode 100644 tests/fixtures/migrations/notifications/2026_01_03_000000_create_jobs_tables.rs create mode 100644 tests/notifications_database.rs diff --git a/crates/notifications/src/lib.rs b/crates/notifications/src/lib.rs index 540155c9b..11911a6ac 100644 --- a/crates/notifications/src/lib.rs +++ b/crates/notifications/src/lib.rs @@ -42,5 +42,11 @@ pub use laravel_http::url; pub use laravel_http::validation; #[doc(hidden)] pub use laravel_http::view; +#[cfg(feature = "database")] +#[doc(hidden)] +pub use laravel_queue::db; +#[cfg(feature = "database")] +#[doc(hidden)] +pub use laravel_queue::model; #[doc(hidden)] pub use laravel_queue::queue; diff --git a/crates/notifications/src/notification.rs b/crates/notifications/src/notification.rs index d11ef8d8e..249ae761a 100644 --- a/crates/notifications/src/notification.rs +++ b/crates/notifications/src/notification.rs @@ -1,5 +1,7 @@ //! `laravel::notification`, which the `laravel-rust` package documents. +#[cfg(feature = "database")] +mod database; mod fake; mod slack; @@ -20,6 +22,8 @@ use crate::queue::{Attempt, Job, JobOptions, Placement, delivery}; use crate::sms::PhoneNumber; use crate::time::Moment; +#[cfg(feature = "database")] +pub use self::database::{__DatabaseData, DatabaseMessage, DatabaseNotification, DatabaseNotifications, DatabaseRoute}; #[doc(hidden)] pub use self::fake::Fakes; pub use self::fake::{NotificationFake, SentNotification, fake}; @@ -135,6 +139,18 @@ pub struct Sms; #[derive(Debug, Clone, Copy)] pub struct Slack; +/// The database channel, which stores notifications in the `notifications` table for your +/// application to show, such as in a list of unread notifications. +/// +/// A notification stores a row with a `database` method in its +/// [`#[notification]`](macro@crate::notification) impl. The method returns the data to store, +/// any value that implements `Serialize`, and the row's type is the notification struct's name in +/// snake case, such as `invoice_paid`. Every [model](crate::model::Model) receives the channel, +/// under its morph name and key. [`DatabaseNotification::of`] reads a model's notifications back. +#[cfg(feature = "database")] +#[derive(Debug, Clone, Copy)] +pub struct Database; + /// A notification's email for one notifiable. pub trait ToMail { /// Build the email this notifiable receives. diff --git a/crates/notifications/src/notification/database.rs b/crates/notifications/src/notification/database.rs new file mode 100644 index 000000000..7f3058be6 --- /dev/null +++ b/crates/notifications/src/notification/database.rs @@ -0,0 +1,442 @@ +//! The database channel, which stores notifications in the `notifications` table, and the queries +//! that read them back. + +use std::any::Any; +use std::fmt; + +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; + +use super::{Database, Receives}; +use crate::Result; +use crate::db::{self, Builder, Condition, Value, Values, col}; +use crate::model::Model; +use crate::str::Uuid; +use crate::time::Timestamp; + +/// The table that the database channel writes to. +const TABLE: &str = "notifications"; + +/// Where a notifiable's database notifications are stored: its morph name and its key. +/// +/// Every [model](crate::model::Model) receives database notifications under its morph name, such +/// as `user`, and its key, so a notifiable doesn't implement anything for this channel. The +/// morph name defaults to the struct's name in snake case, and `#[model(morph = "..")]` sets +/// another one. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct DatabaseRoute { + notifiable_type: String, + notifiable_id: NotifiableId, +} + +/// A notifiable's key, bound as the type of the `notifiable_id` column that `morphs`, +/// `uuid_morphs`, or `ulid_morphs` creates. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +enum NotifiableId { + Integer(i64), + Uuid(Uuid), + Text(String), +} + +impl NotifiableId { + fn value(&self) -> Value<'static> { + match self { + Self::Integer(id) => (*id).into(), + Self::Uuid(id) => (*id).into(), + Self::Text(id) => id.clone().into(), + } + } +} + +impl DatabaseRoute { + /// The route of this model's notifications. + pub fn of(model: &M) -> Self { + let key = M::META.key.get(model); + if let Some(uuid) = (key as &dyn Any).downcast_ref::() { + return Self { + notifiable_type: M::META.morph.to_owned(), + notifiable_id: NotifiableId::Uuid(*uuid), + }; + } + let notifiable_id = match serde_json::to_value(key) { + Ok(serde_json::Value::Number(number)) => number + .as_i64() + .map_or_else(|| NotifiableId::Text(number.to_string()), NotifiableId::Integer), + Ok(serde_json::Value::String(text)) => NotifiableId::Text(text), + _ => NotifiableId::Text(key.to_string()), + }; + + Self { + notifiable_type: M::META.morph.to_owned(), + notifiable_id, + } + } + + /// The condition that a row of the `notifications` table belongs to this notifiable. + fn condition(&self) -> Condition { + col("notifiable_type").eq(self.notifiable_type.as_str()) & col("notifiable_id").eq(self.notifiable_id.value()) + } + + /// Add the notifiable's columns to a row. + fn fill(&self, row: Values) -> Values { + row.set("notifiable_type", self.notifiable_type.as_str()) + .set("notifiable_id", self.notifiable_id.value()) + } +} + +impl fmt::Debug for DatabaseRoute { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let id: &dyn fmt::Debug = match &self.notifiable_id { + NotifiableId::Integer(id) => id, + NotifiableId::Uuid(id) => id, + NotifiableId::Text(id) => id, + }; + + f.debug_struct("DatabaseRoute") + .field("notifiable_type", &self.notifiable_type) + .field("notifiable_id", id) + .finish() + } +} + +impl Receives for M { + fn route(&self) -> Option { + Some(DatabaseRoute::of(self)) + } +} + +/// A notification's row for one notifiable, which a `database` method in a +/// [`#[notification]`](macro@crate::notification) impl builds from the data it returns. +/// +/// The message gets its ID when it's built, so a queued delivery that runs again doesn't store +/// the notification twice. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct DatabaseMessage { + id: Uuid, + #[serde(rename = "type")] + kind: String, + data: serde_json::Value, +} + +impl DatabaseMessage { + #[doc(hidden)] + pub fn __new(kind: &str, data: &impl Serialize) -> Result { + Ok(Self { + id: crate::str::uuid7(), + kind: kind.to_owned(), + data: serde_json::to_value(data)?, + }) + } + + /// The ID the notification is stored under. + #[must_use] + pub const fn id(&self) -> Uuid { + self.id + } + + /// The notification's type, its struct's name in snake case, such as `invoice_paid`. + #[must_use] + pub fn kind(&self) -> &str { + &self.kind + } + + /// The data that the notification's `database` method returned, as JSON. + #[must_use] + pub const fn data(&self) -> &serde_json::Value { + &self.data + } + + /// The data, deserialized into `T`. + /// + /// # Errors + /// + /// Fails when the data doesn't deserialize into `T`. + pub fn data_as(&self) -> Result { + Ok(T::deserialize(&self.data)?) + } +} + +/// The data a `database` method in a [`#[notification]`](macro@crate::notification) impl +/// returns for notifiable `N`. +#[doc(hidden)] +pub trait __DatabaseData { + fn data(&self, notifiable: &N) -> Result; +} + +#[laravel_rust_queue_macros::notification_channel(name = "laravel.database.deliver.v1")] +impl Database { + async fn send(route: DatabaseRoute, message: DatabaseMessage) -> Result<()> { + let now = crate::now().timestamp(); + let row = Values::new() + .set("id", message.id) + .set("type", message.kind) + .set("data", serde_json::to_string(&message.data)?) + .set("created_at", now) + .set("updated_at", now); + + // A retried delivery reuses the message's ID, so it inserts nothing... + db::table(TABLE).insert_or_ignore(route.fill(row)).await?; + + Ok(()) + } +} + +/// A notification that the database channel stored, as [`DatabaseNotification::of`] reads it. +/// +/// ```no_run +/// # use laravel::model::model; +/// # #[model] pub struct User { pub id: i64 } +/// use laravel::notification::DatabaseNotification; +/// +/// # async fn example(user: User) -> laravel::Result<()> { +/// for notification in DatabaseNotification::of(&user).unread().get().await? { +/// println!("{}: {}", notification.kind, notification.data); +/// } +/// +/// DatabaseNotification::of(&user).unread().mark_as_read().await?; +/// # Ok(()) } +/// ``` +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct DatabaseNotification { + /// The notification's ID. + pub id: Uuid, + /// The notification's type, such as `invoice_paid`. + #[serde(rename = "type")] + pub kind: String, + /// The data the notification's `database` method returned. + pub data: serde_json::Value, + /// When the notifiable read the notification, or `None` while it's unread. + pub read_at: Option, + /// When the notification was stored. + pub created_at: Timestamp, +} + +/// A row of the `notifications` table, before its data is parsed. +#[derive(db::FromRow)] +struct Row { + id: Uuid, + #[db(rename = "type")] + kind: String, + data: String, + read_at: Option, + created_at: Timestamp, +} + +impl TryFrom for DatabaseNotification { + type Error = crate::Error; + + fn try_from(row: Row) -> Result { + Ok(Self { + id: row.id, + kind: row.kind, + data: serde_json::from_str(&row.data)?, + read_at: row.read_at, + created_at: row.created_at, + }) + } +} + +impl DatabaseNotification { + /// The notifications stored for this model, newest first. + pub fn of(notifiable: &M) -> DatabaseNotifications { + DatabaseNotifications { + route: DatabaseRoute::of(notifiable), + read: None, + } + } + + /// Whether the notifiable has read the notification. + #[must_use] + pub const fn is_read(&self) -> bool { + self.read_at.is_some() + } + + /// Whether the notifiable hasn't read the notification yet. + #[must_use] + pub const fn is_unread(&self) -> bool { + self.read_at.is_none() + } + + /// The data, deserialized into `T`, such as the struct the notification's `database` method + /// returned. + /// + /// # Errors + /// + /// Fails when the data doesn't deserialize into `T`. + pub fn data_as(&self) -> Result { + Ok(T::deserialize(&self.data)?) + } + + /// Mark the notification as read now, unless it's read already. + /// + /// # Errors + /// + /// Fails when the update fails. + pub async fn mark_as_read(&mut self) -> Result<()> { + if self.read_at.is_some() { + return Ok(()); + } + let now = crate::now().timestamp(); + db::table(TABLE) + .filter(col("id").eq(self.id)) + .update(Values::new().set("read_at", now).set("updated_at", now)) + .await?; + self.read_at = Some(now); + + Ok(()) + } + + /// Mark the notification as unread. + /// + /// # Errors + /// + /// Fails when the update fails. + pub async fn mark_as_unread(&mut self) -> Result<()> { + if self.read_at.is_none() { + return Ok(()); + } + db::table(TABLE) + .filter(col("id").eq(self.id)) + .update( + Values::new() + .set("read_at", None::) + .set("updated_at", crate::now().timestamp()), + ) + .await?; + self.read_at = None; + + Ok(()) + } + + /// Delete the notification. + /// + /// # Errors + /// + /// Fails when the delete fails. + pub async fn delete(self) -> Result<()> { + db::table(TABLE).filter(col("id").eq(self.id)).delete().await?; + + Ok(()) + } +} + +/// The stored notifications of one notifiable, from [`DatabaseNotification::of`]. +/// +/// Narrow them with [`unread`](Self::unread) or [`read`](Self::read), then read them with +/// [`get`](Self::get), [`count`](Self::count), or [`find`](Self::find), or change them all at once +/// with [`mark_as_read`](Self::mark_as_read), [`mark_as_unread`](Self::mark_as_unread), or +/// [`delete`](Self::delete). For pagination or other clauses, start from [`query`](Self::query). +#[derive(Clone, Debug)] +#[must_use = "the notifications are read only by `get`, `count`, `find`, or another method that runs a query"] +pub struct DatabaseNotifications { + route: DatabaseRoute, + read: Option, +} + +impl DatabaseNotifications { + /// Only the notifications the notifiable hasn't read. + pub fn unread(mut self) -> Self { + self.read = Some(false); + self + } + + /// Only the notifications the notifiable has read. + pub fn read(mut self) -> Self { + self.read = Some(true); + self + } + + /// The query builder for these notifications' rows, without an order, for clauses such as + /// `limit` and pagination. + /// + /// Rows map to [`DatabaseNotification`] fields, apart from `data`, which the table stores as + /// JSON text. + pub fn query(&self) -> Builder { + let query = db::table(TABLE).filter(self.route.condition()); + + match self.read { + Some(true) => query.filter(col("read_at").is_not_null()), + Some(false) => query.filter(col("read_at").is_null()), + None => query, + } + } + + /// The notifications, newest first. + /// + /// # Errors + /// + /// Fails when the query fails or a row's data isn't JSON. + pub async fn get(&self) -> Result> { + let rows: Vec = self.newest_first().get().await?; + + rows.into_iter().map(DatabaseNotification::try_from).collect() + } + + /// The notification with this ID, or `None` when no notification of this notifiable has it. + /// + /// The lookup only finds the notifiable's own notifications, so an ID from a request can't + /// reach someone else's. + /// + /// # Errors + /// + /// Fails when the query fails or the row's data isn't JSON. + pub async fn find(&self, id: Uuid) -> Result> { + let row: Option = self.query().filter(col("id").eq(id)).first().await?; + + row.map(DatabaseNotification::try_from).transpose() + } + + /// How many notifications there are. + /// + /// # Errors + /// + /// Fails when the query fails. + pub async fn count(&self) -> Result { + self.query().count().await + } + + /// Mark the notifications as read now, returning how many were unread. + /// + /// # Errors + /// + /// Fails when the update fails. + pub async fn mark_as_read(&self) -> Result { + let now = crate::now().timestamp(); + + self.query() + .filter(col("read_at").is_null()) + .update(Values::new().set("read_at", now).set("updated_at", now)) + .await + } + + /// Mark the notifications as unread, returning how many were read. + /// + /// # Errors + /// + /// Fails when the update fails. + pub async fn mark_as_unread(&self) -> Result { + self.query() + .filter(col("read_at").is_not_null()) + .update( + Values::new() + .set("read_at", None::) + .set("updated_at", crate::now().timestamp()), + ) + .await + } + + /// Delete the notifications, returning how many there were. + /// + /// # Errors + /// + /// Fails when the delete fails. + pub async fn delete(&self) -> Result { + self.query().delete().await + } + + fn newest_first(&self) -> Builder { + self.query() + .order_by(col("created_at").desc()) + .order_by(col("id").desc()) + } +} diff --git a/docs/migrations.md b/docs/migrations.md index 374344331..6dadb8165 100644 --- a/docs/migrations.md +++ b/docs/migrations.md @@ -83,6 +83,7 @@ laravel::cache::tables!(); | --- | --- | | `laravel::cache::tables!()` | The [cache store's](cache.md#the-database-store) `cache` and `cache_locks` tables | | `laravel::feature::table!()` | The [feature flag store's](feature-flags.md#the-features-table) `features` table | +| `laravel::notification::table!()` | The [database notification channel's](notifications.md#the-notifications-table) `notifications` table | | `laravel::queue::tables!()` | The [queue's](queues.md#the-jobs-table) `jobs`, `failed_jobs`, `job_batches`, and `job_batch_jobs` tables | | `laravel::session::table!()` | The [session driver's](session.md#the-database-session-table) `sessions` table | | `laravel::workflow::tables!()` | The [workflow store's](workflows.md#the-workflow-tables) five `workflow_*` tables | diff --git a/docs/notifications.md b/docs/notifications.md index c4735616e..bec28030b 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -9,6 +9,11 @@ - [Sending notifications](#sending-notifications) - [Queueing notifications](#queueing-notifications) - [Choosing channels for each notifiable](#choosing-channels) +- [Database notifications](#database-notifications) + - [The notifications table](#the-notifications-table) + - [Storing notifications](#storing-notifications) + - [Reading notifications](#reading-notifications) + - [Marking notifications as read](#marking-notifications-as-read) - [Package channels](#package-channels) - [Sending through a package channel](#sending-through-a-package-channel) - [Writing a channel](#writing-a-channel) @@ -19,14 +24,14 @@ When a customer pays an invoice, you might email them, send a text message, and post the payment to their team's Slack channel. A notification describes that event once and builds a message for each channel, and Laravel delivers those messages to every user or team you specify. -Laravel delivers notifications over email, SMS, Slack, and [custom package channels](#package-channels) such as Discord. Email uses [mail](mail.md) and text messages use [SMS](sms.md), inheriting the configuration and queues from those guides, so configure each channel you plan to use first. +Laravel delivers notifications over email, SMS, Slack, the [database](#database-notifications), and [custom package channels](#package-channels) such as Discord. Email uses [mail](mail.md) and text messages use [SMS](sms.md), inheriting the configuration and queues from those guides, so configure each channel you plan to use first. Keep notifications short and informational. To send one email with its own layout and attachments, such as an order receipt, send a [mailable](mail.md) directly. ## Writing notifications -Each notification is a struct holding the data its messages need, paired with an `impl` block annotated with `#[notification]`. Define a `mail`, `sms`, or `slack` method for each channel the notification supports, typically in a module such as `src/notifications.rs`. +Each notification is a struct holding the data its messages need, paired with an `impl` block annotated with `#[notification]`. Define a `mail`, `sms`, `slack`, or `database` method for each channel the notification supports, typically in a module such as `src/notifications.rs`. For example, suppose your application has an `Invoice` [model](models.md) and an `InvoicePaidEmail` [mailable](#mail-messages). This notification alerts a user when their invoice is paid: @@ -238,6 +243,125 @@ impl InvoicePaid { `channels` runs once for each notifiable, before Laravel builds any message. It can't wait or fail, so it can't query the database. Load what it needs onto the notifiable or the notification before you send. + +## Database notifications + +The database channel stores notifications in a `notifications` table, so your application can show them to the user later, such as in a list of unread notifications beside a bell icon. Each row holds the notification's type and the data your notification returns as JSON. + + +### The notifications table + +Create the `notifications` table in a [migration](migrations.md#framework-tables) with `laravel::notification::table!()`: + +```rust +// database/migrations/2026_01_01_000000_create_notifications_table.rs +laravel::notification::table!(); +``` + +The macro stands for this migration. If your notifiable models use UUID or ULID keys, replace the macro with the migration and use `uuid_morphs` or `ulid_morphs` instead of `morphs`: + +```rust +// database/migrations/2026_01_01_000000_create_notifications_table.rs +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.schema() + .create("notifications", |table| { + table.uuid("id").primary(); + table.string("type"); + table.morphs("notifiable"); + table.text("data"); + table.timestamp("read_at").nullable(); + table.timestamps(); + }) + .await +} +``` + + +### Storing notifications + +To store a notification, add a `database` method that returns the data to keep. The data may be any value that implements `Serialize`, such as a struct or a `serde_json::Value` from the `json!` macro: + +```rust +use laravel::notification; +use serde::Serialize; + +#[derive(Serialize)] +pub struct InvoicePaidData { + pub invoice_id: i64, + pub amount: i64, +} + +#[notification] +impl InvoicePaid { + fn database(&self, _user: &User) -> InvoicePaidData { + InvoicePaidData { invoice_id: self.invoice.id, amount: self.invoice.total } + } +} +``` + +The row's `type` column holds the notification struct's name in snake case, such as `invoice_paid`, which your frontend can use to pick how to display each notification. + +Every [model](models.md) receives database notifications, so a notifiable doesn't implement anything for this channel. The row records the model's [morph name](model-relationships.md#declaring-polymorphic-relationships) and key in its `notifiable_type` and `notifiable_id` columns, so a user and a team that share an ID never see each other's notifications. + +A sent notification is stored in the current [database transaction](database.md#transactions), so a rollback leaves it out. A [queued](#queueing-notifications) notification is stored by a queue worker, and a delivery that runs again doesn't store it twice. + + +### Reading notifications + +`DatabaseNotification::of` reads a model's notifications, newest first. Narrow them with `unread` or `read`: + +```rust +use laravel::auth::Authenticated; +use laravel::inertia::{self, Page, props}; +use laravel::notification::DatabaseNotification; + +pub async fn index(user: Authenticated) -> laravel::Result { + let notifications = DatabaseNotification::of(&*user).unread().get().await?; + + Ok(inertia::render("Notifications/Index", props! { notifications })) +} +``` + +`of` takes the model itself, so dereference an `Authenticated` with `&*user`. + +Each `DatabaseNotification` has the notification's `id`, its `kind` (serialized as `type`), its `data` as a `serde_json::Value`, `read_at`, and `created_at`. To read the data back into a struct, call `data_as`: + +```rust +for notification in DatabaseNotification::of(&user).get().await? { + if notification.kind == "invoice_paid" { + let data: InvoicePaidData = notification.data_as()?; + } +} +``` + +`count` counts the notifications, and `find` returns one by its ID. Because `find` only searches the notifiable's own notifications, an ID from a request can't reach anyone else's: + +```rust +let unread = DatabaseNotification::of(&user).unread().count().await?; + +let notification = DatabaseNotification::of(&user).find(id).await?.or_abort(404)?; +``` + +For pagination or any other clause, `query` returns the [query builder](queries.md) for the notifiable's rows. + + +### Marking notifications as read + +Call `mark_as_read` on one notification, or on the notifiable's notifications to mark them all at once. `mark_as_unread` reverses it, and `delete` removes them: + +```rust +let mut notification = DatabaseNotification::of(&user).find(id).await?.or_abort(404)?; +notification.mark_as_read().await?; + +DatabaseNotification::of(&user).unread().mark_as_read().await?; + +DatabaseNotification::of(&user).read().delete().await?; +``` + +To delete old notifications on a schedule, run a query through `db::table("notifications")` from a [scheduled task](scheduling.md). + ## Package channels @@ -412,17 +536,22 @@ notifications.assert_sent_to_where::(&user, |sent| { }); ``` -For Slack and custom package channels, pass the channel type to `message::()` to inspect the built message: +For Slack, database, and custom package channels, pass the channel type to `message::()` to inspect the built message. A database message's `kind()` and `data()` hold what the notification would store: ```rust use discord_notifications::Discord; -use laravel::notification::Slack; +use laravel::notification::{Database, Slack}; notifications.assert_sent_to_where::(&team, |sent| { sent.message::() .is_some_and(|message| message.text().contains(&format!("Invoice #{}", invoice.id))) }); +notifications.assert_sent_to_where::(&user, |sent| { + sent.message::() + .is_some_and(|message| message.kind() == "invoice_paid" && message.data()["invoice_id"] == invoice.id) +}); + notifications.assert_sent_to_where::(&user, |sent| { sent.message::() .is_some_and(|message| message.content.contains(&format!("Invoice #{}", invoice.id))) diff --git a/macros/database/src/lib.rs b/macros/database/src/lib.rs index 924b1b78b..90623aa36 100644 --- a/macros/database/src/lib.rs +++ b/macros/database/src/lib.rs @@ -3,8 +3,8 @@ //! Use these macros through the `laravel` crate, which re-exports and documents them: //! //! - `laravel::db::{query!, raw!, migrations!, schema!, seeder, FromRow, Json, Enum, Newtype, Embed}` -//! - `laravel::cache::tables!`, `laravel::feature::table!`, `laravel::queue::tables!`, -//! `laravel::session::table!`, and `laravel::workflow::tables!` +//! - `laravel::cache::tables!`, `laravel::feature::table!`, `laravel::notification::table!`, +//! `laravel::queue::tables!`, `laravel::session::table!`, and `laravel::workflow::tables!` mod binding; mod embeddable; @@ -79,6 +79,11 @@ pub fn feature_table(input: TokenStream) -> TokenStream { expand(input, |Nothing| Ok(tables::feature())) } +#[proc_macro] +pub fn notification_table(input: TokenStream) -> TokenStream { + expand(input, |Nothing| Ok(tables::notification())) +} + #[proc_macro] pub fn workflow_tables(input: TokenStream) -> TokenStream { expand(input, |Nothing| Ok(tables::workflow())) diff --git a/macros/database/src/tables.rs b/macros/database/src/tables.rs index edf7edd95..c333db1f1 100644 --- a/macros/database/src/tables.rs +++ b/macros/database/src/tables.rs @@ -113,6 +113,22 @@ pub(crate) fn feature() -> TokenStream { }) } +/// The table of the database notification channel. +pub(crate) fn notification() -> TokenStream { + migration(quote! { + tx.schema() + .create("notifications", |table| { + table.uuid("id").primary(); + table.string("type"); + table.morphs("notifiable"); + table.text("data"); + table.timestamp("read_at").nullable(); + table.timestamps(); + }) + .await + }) +} + /// The tables of the `database` workflow store. pub(crate) fn workflow() -> TokenStream { migration(quote! { diff --git a/macros/queue/src/notification.rs b/macros/queue/src/notification.rs index 076186921..1088eb1ac 100644 --- a/macros/queue/src/notification.rs +++ b/macros/queue/src/notification.rs @@ -26,6 +26,7 @@ pub(crate) fn expand(mut implementation: ItemImpl) -> syn::Result { None if name == "mail" => Some(Message::Mail), None if name == "sms" => Some(Message::Sms), None if name == "slack" => Some(Message::Via(quote!(::laravel::notification::Slack))), + None if name == "database" => Some(Message::Database), None if name == "channels" => None, None => { remaining.push(ImplItem::Fn(method)); @@ -60,12 +61,12 @@ pub(crate) fn expand(mut implementation: ItemImpl) -> syn::Result { messages.sort_by_key(|(message, _)| match message { Message::Mail => 0, Message::Sms => 1, - Message::Via(_) => 2, + Message::Via(_) | Message::Database => 2, }); let Some(notifiable) = notifiable.filter(|_| !messages.is_empty()) else { return Err(syn::Error::new_spanned( &implementation.self_ty, - "a notification needs a `mail`, `sms`, or `slack` method, or a `#[via(Channel)]` method", + "a notification needs a `mail`, `sms`, `slack`, or `database` method, or a `#[via(Channel)]` method", )); }; @@ -78,6 +79,7 @@ pub(crate) fn expand(mut implementation: ItemImpl) -> syn::Result { Message::Mail => quote!(::laravel::notification::Mail), Message::Sms => quote!(::laravel::notification::Sms), Message::Via(channel) => channel.clone(), + Message::Database => quote!(::laravel::notification::Database), }) .collect(); let listed = match listed.as_slice() { @@ -94,6 +96,30 @@ pub(crate) fn expand(mut implementation: ItemImpl) -> syn::Result { method.sig.ident = syn::Ident::new("message", method.sig.ident.span()); quote!(ToChannel<#channel, #notifiable>) } + Message::Database => { + let kind = snake_case(&type_name(&implementation.self_ty)); + method.sig.ident = syn::Ident::new("data", method.sig.ident.span()); + let data = quote!(::laravel::notification::__DatabaseData<#notifiable>); + let to = quote!(::laravel::notification::ToChannel<::laravel::notification::Database, #notifiable>); + return quote! { + #[allow(refining_impl_trait)] + impl #impl_generics #data for #ty #where_clause { + #method + } + + impl #impl_generics #to for #ty #where_clause { + #[allow(refining_impl_trait)] + fn message( + &self, + __laravel_notifiable: &#notifiable, + ) -> ::laravel::Result<::laravel::notification::DatabaseMessage> { + // The stored type is the struct's name, which the `database` method can't see... + let __laravel_data = ::data(self, __laravel_notifiable)?; + ::laravel::notification::DatabaseMessage::__new(#kind, &__laravel_data) + } + } + }; + } }; quote! { #[allow(refining_impl_trait)] @@ -127,6 +153,33 @@ enum Message { Sms, /// A package channel, from `#[via(Slack)]`. Via(TokenStream), + /// The database channel, from a `database` method that returns the notification's data. + Database, +} + +/// The name of the notification's struct, without its module or generic arguments. +fn type_name(ty: &Type) -> String { + match ty { + Type::Path(path) => path + .path + .segments + .last() + .map_or_else(String::new, |segment| segment.ident.to_string()), + ty => ty.to_token_stream().to_string(), + } +} + +/// `InvoicePaid` as `invoice_paid`, the type a database notification is stored under. +fn snake_case(name: &str) -> String { + let mut snake = String::with_capacity(name.len() + 4); + for (index, character) in name.chars().enumerate() { + if character.is_uppercase() && index > 0 { + snake.push('_'); + } + snake.extend(character.to_lowercase()); + } + + snake } /// Remove the method's `#[via(Channel)]` attribute, returning the channel... @@ -262,7 +315,7 @@ fn wrap_in_result(method: &mut ImplItemFn) { method.sig.output = parse_quote!(-> ::laravel::Result<#ty>); } -/// The notifiable type that a `mail`, `sms`, `slack`, `#[via]`, or `channels` method takes as `&N`, after `&self`... +/// The notifiable type that a channel's method or `channels` takes as `&N`, after `&self`... fn notifiable_of(method: &ImplItemFn) -> syn::Result<&Type> { let name = &method.sig.ident; if let Some(asyncness) = &method.sig.asyncness { diff --git a/src/notification.rs b/src/notification.rs index a32be0b23..475720b4f 100644 --- a/src/notification.rs +++ b/src/notification.rs @@ -1,8 +1,8 @@ -//! Notify users by email, text message, Slack, and package [channels](Channel). +//! Notify users by email, text message, Slack, the database, and package [channels](Channel). //! //! When something happens that a user should hear about, such as a paid invoice, a notification //! tells them on each channel they use. A notification is a struct with [`#[notification]`](macro@crate::notification) on the impl -//! holding its `mail`, `sms`, `slack`, and `#[via(Channel)]` methods. The attribute implements +//! holding its `mail`, `sms`, `slack`, `database`, and `#[via(Channel)]` methods. The attribute implements //! [`Notification`], [`ToMail`], [`ToSms`], and [`ToChannel`] from them. `notification::to` //! names the notifiables, and `send` or `queue` delivers the notification to each of them: //! @@ -56,6 +56,9 @@ //! //! [notifications guide]: https://github.com/laravel/rust-framework/blob/0.x/docs/notifications.md +#[cfg(feature = "database")] +#[doc(hidden)] +pub use laravel_notifications::notification::__DatabaseData; #[doc(hidden)] pub use laravel_notifications::notification::__Deliver; pub(crate) use laravel_notifications::notification::*; @@ -65,3 +68,22 @@ pub use laravel_notifications::notification::{ PendingQueue, PendingSend, Receives, ReceivesMail, ReceivesSlack, ReceivesSms, Selected, SentNotification, Slack, Sms, ToChannel, ToMail, ToSms, channel, fake, to, }; +#[cfg(feature = "database")] +#[doc(inline)] +pub use laravel_notifications::notification::{ + Database, DatabaseMessage, DatabaseNotification, DatabaseNotifications, DatabaseRoute, +}; + +/// Create the `notifications` table, which the [`Database`] channel stores notifications in. +/// +/// Put the macro alone in a migration file, and it creates the table. To change the table, such +/// as for notifiables with UUID keys, replace the macro with the migration the +/// [notifications guide](https://github.com/laravel/rust-framework/blob/0.x/docs/notifications.md#the-notifications-table) +/// shows, then edit it. +/// +/// ``` +/// // database/migrations/0001_01_01_000003_create_notifications_table.rs +/// laravel::notification::table!(); +/// ``` +#[cfg(feature = "database")] +pub use laravel_rust_database_macros::notification_table as table; diff --git a/tests/fixtures/migrations/notifications-uuid/2026_01_01_000000_create_devices_table.rs b/tests/fixtures/migrations/notifications-uuid/2026_01_01_000000_create_devices_table.rs new file mode 100644 index 000000000..fc41f57e1 --- /dev/null +++ b/tests/fixtures/migrations/notifications-uuid/2026_01_01_000000_create_devices_table.rs @@ -0,0 +1,10 @@ +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.schema() + .create("devices", |table| { + table.uuid("id").primary(); + table.string("name"); + }) + .await +} diff --git a/tests/fixtures/migrations/notifications-uuid/2026_01_02_000000_create_notifications_table.rs b/tests/fixtures/migrations/notifications-uuid/2026_01_02_000000_create_notifications_table.rs new file mode 100644 index 000000000..fb37a6d99 --- /dev/null +++ b/tests/fixtures/migrations/notifications-uuid/2026_01_02_000000_create_notifications_table.rs @@ -0,0 +1,14 @@ +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.schema() + .create("notifications", |table| { + table.uuid("id").primary(); + table.string("type"); + table.uuid_morphs("notifiable"); + table.text("data"); + table.timestamp("read_at").nullable(); + table.timestamps(); + }) + .await +} diff --git a/tests/fixtures/migrations/notifications/2026_01_01_000000_create_notifiable_tables.rs b/tests/fixtures/migrations/notifications/2026_01_01_000000_create_notifiable_tables.rs new file mode 100644 index 000000000..edb92a471 --- /dev/null +++ b/tests/fixtures/migrations/notifications/2026_01_01_000000_create_notifiable_tables.rs @@ -0,0 +1,14 @@ +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + for name in ["users", "organizations"] { + tx.schema() + .create(name, |table| { + table.id(); + table.string("name"); + }) + .await?; + } + + Ok(()) +} diff --git a/tests/fixtures/migrations/notifications/2026_01_02_000000_create_notifications_table.rs b/tests/fixtures/migrations/notifications/2026_01_02_000000_create_notifications_table.rs new file mode 100644 index 000000000..f26bfac10 --- /dev/null +++ b/tests/fixtures/migrations/notifications/2026_01_02_000000_create_notifications_table.rs @@ -0,0 +1 @@ +laravel::notification::table!(); diff --git a/tests/fixtures/migrations/notifications/2026_01_03_000000_create_jobs_tables.rs b/tests/fixtures/migrations/notifications/2026_01_03_000000_create_jobs_tables.rs new file mode 100644 index 000000000..8e80c3bc0 --- /dev/null +++ b/tests/fixtures/migrations/notifications/2026_01_03_000000_create_jobs_tables.rs @@ -0,0 +1 @@ +laravel::queue::tables!(); diff --git a/tests/notifications_database.rs b/tests/notifications_database.rs new file mode 100644 index 000000000..4b2582030 --- /dev/null +++ b/tests/notifications_database.rs @@ -0,0 +1,354 @@ +use laravel::Application; +use laravel::config::Env; +use laravel::config::database::ConnectionConfig; +use laravel::crypt::{Cipher, Encrypter}; +use laravel::db; +use laravel::foundation::ApplicationBuilder; +use laravel::model::{create, model}; +use laravel::notification; +use laravel::notification::{Channel, Database, DatabaseMessage, DatabaseNotification, DatabaseRoute}; +use laravel::str::Uuid; +use laravel::testing::{InteractsWithDatabase, MakesConsoleRequests}; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +#[model] +pub struct User { + pub id: i64, + pub name: String, +} + +#[model(morph = "team")] +pub struct Organization { + pub id: i64, + pub name: String, +} + +#[model] +pub struct Device { + pub id: Uuid, + pub name: String, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +struct Invoice { + number: u64, + amount: u64, +} + +struct InvoicePaid { + number: u64, +} + +#[notification] +impl InvoicePaid { + fn database(&self, _user: &User) -> Invoice { + Invoice { + number: self.number, + amount: 4_200, + } + } +} + +struct Welcome { + by: &'static str, +} + +#[notification] +impl Welcome { + fn database(&self, user: &User) -> serde_json::Value { + json!({ "user": user.name, "by": self.by }) + } +} + +#[notification] +impl Welcome { + fn database(&self, team: &Organization) -> serde_json::Value { + json!({ "team": team.name, "by": self.by }) + } +} + +struct Paired; + +#[notification] +impl Paired { + fn database(&self, device: &Device) -> serde_json::Value { + json!({ "device": device.name }) + } +} + +fn configure(connection: ConnectionConfig) -> ApplicationBuilder { + Application::configure() + .replace_env(Env::from_iter([("APP_ENV", "testing")])) + .with_config(move |config, _| { + config.app.key = Some(Encrypter::generate_key(Cipher::Aes256Cbc)); + config.database.default = "primary".into(); + config.database.connections.insert("primary".into(), connection); + }) + .refresh_database() +} + +fn app_on(connection: ConnectionConfig) -> Application { + configure(connection) + .with_migrations(db::migrations!("tests/fixtures/migrations/notifications")) + .create() +} + +fn uuid_app_on(connection: ConnectionConfig) -> Application { + configure(connection) + .with_migrations(db::migrations!("tests/fixtures/migrations/notifications-uuid")) + .create() +} + +fn app() -> Application { + app_on(ConnectionConfig::new("sqlite::memory:")) +} + +async fn users() -> laravel::Result<(User, User)> { + let taylor = create!(User { name: "Taylor" }).await?; + let abigail = create!(User { name: "Abigail" }).await?; + + Ok((taylor, abigail)) +} + +#[tokio::test] +async fn notifications_are_stored_read_and_marked_on_sqlite() { + stored_notifications_contract(&app()).await; +} + +#[tokio::test] +async fn notifiables_with_uuid_keys_receive_notifications_on_sqlite() { + uuid_contract(&uuid_app_on(ConnectionConfig::new("sqlite::memory:"))).await; +} + +#[cfg(feature = "database-postgres")] +#[tokio::test] +#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"] +async fn notifications_are_stored_read_and_marked_on_postgres() -> laravel::Result<()> { + let url = std::env::var("LARAVEL_TEST_POSTGRES_URL")?; + stored_notifications_contract(&app_on( + crate::support::fresh_database(&url, "laravel_notifications").await?, + )) + .await; + uuid_contract(&uuid_app_on( + crate::support::fresh_database(&url, "laravel_notifications").await?, + )) + .await; + + Ok(()) +} + +#[cfg(feature = "database-mysql")] +#[tokio::test] +#[ignore = "requires LARAVEL_TEST_MYSQL_URL pointing to a disposable MySQL or MariaDB database"] +async fn notifications_are_stored_read_and_marked_on_mysql() -> laravel::Result<()> { + let url = crate::support::mysql_or_mariadb_url().await?; + stored_notifications_contract(&app_on( + crate::support::fresh_database(&url, "laravel_notifications").await?, + )) + .await; + uuid_contract(&uuid_app_on( + crate::support::fresh_database(&url, "laravel_notifications").await?, + )) + .await; + + Ok(()) +} + +async fn stored_notifications_contract(app: &Application) { + app.scope(async || { + let (taylor, abigail) = users().await?; + let team = create!(Organization { name: "Laravel" }).await?; + assert_eq!(team.id, taylor.id); + + for number in 1..=3 { + notification::to(vec![&taylor, &abigail]) + .send(InvoicePaid { number }) + .await?; + } + notification::to(&taylor).send(Welcome { by: "Abigail" }).await?; + notification::to(&team).send(Welcome { by: "Taylor" }).await?; + + let stored = DatabaseNotification::of(&taylor).get().await?; + assert_eq!(stored.len(), 4); + assert!(stored.iter().all(DatabaseNotification::is_unread)); + let welcome = stored.iter().find(|stored| stored.kind == "welcome").unwrap(); + assert_eq!(welcome.data, json!({ "user": "Taylor", "by": "Abigail" })); + let third_invoice = stored + .iter() + .find(|stored| stored.kind == "invoice_paid" && stored.data["number"] == 3) + .unwrap(); + assert_eq!( + third_invoice.data_as::()?, + Invoice { + number: 3, + amount: 4_200 + } + ); + + let teams = DatabaseNotification::of(&team).get().await?; + assert_eq!(teams.len(), 1); + assert_eq!(teams[0].data, json!({ "team": "Laravel", "by": "Taylor" })); + + let mut newest_invoice = third_invoice.clone(); + newest_invoice.mark_as_read().await?; + assert!(newest_invoice.is_read()); + assert_eq!(DatabaseNotification::of(&taylor).unread().count().await?, 3); + assert_eq!( + DatabaseNotification::of(&taylor).read().get().await?, + vec![newest_invoice.clone()] + ); + assert_eq!(DatabaseNotification::of(&taylor).unread().mark_as_read().await?, 3); + assert_eq!(DatabaseNotification::of(&abigail).unread().count().await?, 3); + assert_eq!(DatabaseNotification::of(&team).unread().count().await?, 1); + + newest_invoice.mark_as_unread().await?; + assert!(newest_invoice.is_unread()); + assert_eq!(DatabaseNotification::of(&taylor).unread().count().await?, 1); + assert_eq!(DatabaseNotification::of(&taylor).mark_as_unread().await?, 3); + + let theirs = DatabaseNotification::of(&abigail).get().await?.remove(0); + assert_eq!(DatabaseNotification::of(&taylor).find(theirs.id).await?, None); + assert_eq!( + DatabaseNotification::of(&abigail).find(theirs.id).await?.as_ref(), + Some(&theirs) + ); + + let types: Vec = DatabaseNotification::of(&abigail) + .query() + .limit(2) + .pluck("type") + .await?; + assert_eq!(types, ["invoice_paid", "invoice_paid"]); + + theirs.delete().await?; + assert_eq!(DatabaseNotification::of(&abigail).count().await?, 2); + assert_eq!(DatabaseNotification::of(&taylor).read().delete().await?, 0); + assert_eq!(DatabaseNotification::of(&taylor).delete().await?, 4); + + Ok::<_, laravel::Error>(()) + }) + .await + .unwrap(); + + app.assert_database_count("notifications", 3).await; + app.assert_database_has( + "notifications", + json!({ "notifiable_type": "team", "notifiable_id": 1 }), + ) + .await; + app.assert_database_missing( + "notifications", + json!({ "notifiable_type": "user", "notifiable_id": 1 }), + ) + .await; +} + +async fn uuid_contract(app: &Application) { + app.scope(async || { + let phone = create!(Device { name: "Phone" }).await?; + let laptop = create!(Device { name: "Laptop" }).await?; + + notification::to(&phone).send(Paired).await?; + + let stored = DatabaseNotification::of(&phone).get().await?; + assert_eq!(stored.len(), 1); + assert_eq!(stored[0].kind, "paired"); + assert_eq!(stored[0].data, json!({ "device": "Phone" })); + assert_eq!(DatabaseNotification::of(&laptop).count().await?, 0); + assert_eq!(DatabaseNotification::of(&phone).unread().mark_as_read().await?, 1); + + Ok::<_, laravel::Error>(()) + }) + .await + .unwrap(); + + app.assert_database_count("notifications", 1).await; +} + +#[tokio::test] +async fn a_queued_notification_is_stored_once_even_when_its_delivery_runs_again() { + let app = app(); + let taylor = app + .scope(async || { + let (taylor, _) = users().await?; + notification::to(&taylor).queue(InvoicePaid { number: 9 }).await?; + + Ok::<_, laravel::Error>(taylor) + }) + .await + .unwrap(); + app.assert_database_empty("notifications").await; + + app.command("queue:work --stop-when-empty").await.assert_successful(); + + app.scope(async || { + let stored = DatabaseNotification::of(&taylor).get().await?; + assert_eq!(stored.len(), 1); + assert_eq!( + stored[0].data_as::()?, + Invoice { + number: 9, + amount: 4_200 + } + ); + + let message = DatabaseMessage::__new("invoice_paid", &json!({ "number": 10 }))?; + ::send(DatabaseRoute::of(&taylor), message.clone()).await?; + ::send(DatabaseRoute::of(&taylor), message.clone()).await?; + + let stored = DatabaseNotification::of(&taylor).find(message.id()).await?.unwrap(); + assert_eq!(stored.data, json!({ "number": 10 })); + + Ok::<_, laravel::Error>(()) + }) + .await + .unwrap(); + + app.assert_database_count("notifications", 2).await; +} + +#[tokio::test] +async fn a_notification_sent_in_a_rolled_back_transaction_isnt_stored() { + let app = app(); + app.scope(async || { + let (taylor, _) = users().await?; + + let failed: laravel::Result<()> = db::transaction(async |_| { + notification::to(&taylor).send(InvoicePaid { number: 1 }).await?; + Err(laravel::Error::msg("payment reversed")) + }) + .await; + + assert!(failed.is_err()); + Ok::<_, laravel::Error>(()) + }) + .await + .unwrap(); + + app.assert_database_empty("notifications").await; +} + +#[tokio::test] +async fn the_fake_records_the_message_instead_of_storing_it() { + let app = app(); + app.scope(async || { + let (taylor, _) = users().await?; + let notifications = notification::fake(); + + notification::to(&taylor).send(InvoicePaid { number: 5 }).await?; + + notifications.assert_sent_where::(|sent| { + sent.message::().is_some_and(|message| { + message.kind() == "invoice_paid" + && message.data_as::().is_ok_and(|invoice| invoice.number == 5) + }) + }); + + Ok::<_, laravel::Error>(()) + }) + .await + .unwrap(); + + app.assert_database_empty("notifications").await; +} diff --git a/tests/suite_queue.rs b/tests/suite_queue.rs index 3a4825b33..89957562a 100644 --- a/tests/suite_queue.rs +++ b/tests/suite_queue.rs @@ -8,6 +8,8 @@ mod event_transactions; mod events; mod mail; mod notifications; +#[cfg(feature = "database-sqlite")] +mod notifications_database; mod processes; mod queue; #[cfg(feature = "database-sqlite")]