Notifications
- Introduction
- Writing notifications
- Notifiables
- Sending notifications
- Choosing channels for each notifiable
- Package channels
- Testing
Introduction
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 dust-framework delivers those messages to every user or team you specify.
dust-framework delivers notifications over email, SMS, Slack, and custom package channels such as Discord. Email uses mail and text messages use SMS, 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 directly.
| Channel | Configure with | Notifiable implements | Message method |
|---|---|---|---|
ReceivesMail |
mail |
||
| SMS | SMS | ReceivesSms |
sms |
| Slack | Slack | ReceivesSlack |
slack |
| Package channel | The package's guide | Receives<C> |
A #[via(C)] method |
Every channel is independent. A notification to one user with email and SMS is two jobs, and a text message that fails does not prevent the email from being delivered.
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.
For example, suppose your application has an Invoice model and an InvoicePaidEmail mailable. This notification alerts a user when their invoice is paid:
use dust::mail::Mailable;use dust::notification;use crate::mail::InvoicePaidEmail;pub struct InvoicePaid { pub invoice: Invoice,}#[notification]impl InvoicePaid { fn mail(&self, user: &User) -> impl Mailable { InvoicePaidEmail { name: user.name.clone(), invoice_id: self.invoice.id } } fn sms(&self, _user: &User) -> String { format!("Invoice #{} is paid. Thanks!", self.invoice.id) }}Each method's second argument is the notifiable that receives the message, here a &User. Every method in one impl takes the same notifiable type. To send the notification to teams too, write a second #[notification] impl whose methods take &Team, as the Slack example does.
Channel methods are synchronous, so load any related models or data you need before sending the notification. Because dust-framework calls these methods in the handler or job that dispatches the notification, route URLs, configuration, and context values are available directly. If a channel method can fail (such as when generating a route URL), return a dust::Result instead; any error aborts the send before any messages are delivered.
A notification owns its data, as a mailable does, so the fake can keep it for your tests. When you still need a value after sending, clone it into the notification, as in InvoicePaid { invoice: invoice.clone() }.
Mail messages
mail returns the email one notifiable receives. It may be a derived mailable, a mailable that builds its message itself, or a Message. InvoicePaidEmail is a derived mailable, which renders resources/views/mail/invoice-paid-email.html with its name and invoice_id:
use dust::mail::Mailable;#[derive(Mailable)]#[mail(subject = "Invoice #{invoice_id} is paid")]pub struct InvoicePaidEmail { pub name: String, pub invoice_id: i64,}dust-framework automatically attaches the notifiable's email address as the recipient, so the mailable does not need to specify to. To learn more about views, subjects, and attachments, check out the Mail guide.
SMS messages
sms returns the text as a String or a &str, which goes out from your SMS_FROM number. To send from another number, return an sms::Message instead:
use dust::sms;fn sms(&self, _user: &User) -> sms::Message { sms::Message::new(format!("Invoice #{} is paid.", self.invoice.id)).from("+15555550199")}Slack messages
slack returns a slack::Message, with blocks such as sections and buttons. Slack messages usually go to a team's channel rather than to one user. For example, suppose your application has a Team model with a slack_channel_id column:
use dust::notification;use dust::prelude::*;use dust::slack::{Button, Message, Section};#[notification]impl InvoicePaid { fn slack(&self, _team: &Team) -> dust::Result<Message> { let url = route!(invoices::show, &self.invoice)?; let amount = format!("${:.2}", self.invoice.total as f64 / 100.0); Ok(Message::new(format!("Invoice #{} is paid", self.invoice.id)) .section(Section::new("Invoice paid.").field("Amount", amount)) .actions([Button::link("View invoice", url)])) }}The message goes to the team's Slack route. To set up your Slack app and handle button clicks, check out the Slack guide.
Notifiables
A notifiable is a type that receives notifications, such as User or Team. For each channel it supports, implement ReceivesMail, ReceivesSms, or ReceivesSlack to provide its email address, phone number, or Slack route. Suppose your users table has a nullable phone column:
use dust::mail::Address;use dust::notification::{ReceivesMail, ReceivesSlack, ReceivesSms};use dust::slack::Route;use dust::sms::PhoneNumber;impl ReceivesMail for User { fn mail_address(&self) -> Option<Address> { Some(Address::new(&self.email).with_name(&self.name)) }}impl ReceivesSms for User { fn sms_number(&self) -> Option<PhoneNumber> { self.phone.as_deref().map(PhoneNumber::new) }}impl ReceivesSlack for Team { fn slack_route(&self) -> Option<Route> { self.slack_channel_id.as_deref().map(Route::channel) }}When one of these methods returns None, the send skips that channel for that notifiable without an error. A user who signed up without a phone number still gets the email.
A notifiable needs an implementation for every channel its notifications build. Sending InvoicePaid to a type without ReceivesSms doesn't compile.
Sending notifications
To send a notification, specify its recipients with notification::to, then call queue or send. Most handlers should queue notifications so HTTP responses don't wait on external providers. This handler charges an invoice and notifies the customer:
use dust::notification;use dust::prelude::*;use crate::models::Invoice;use crate::notifications::InvoicePaid;pub async fn pay(Params(id): Params<i64>) -> dust::Result<Redirect> { let invoice = Invoice::query() .with(Invoice::user) .find_or_fail(id) .await?; // Charge the invoice... notification::to(&invoice.user) .queue(InvoicePaid { invoice: invoice.clone() }) .await?; Ok(Redirect::back())}send delivers messages immediately and waits for each provider to accept them. to accepts a reference to a single notifiable, a slice or Vec of notifiables, a Vec of references, an Authenticated<User>, or a loaded relationship such as &invoice.user or &team.members. To notify multiple teams at once:
let teams = Team::all().await?;notification::to(&teams).send(WeeklySummary { report }).await?;When a single notification implements #[notification] for more than one notifiable type, Rust can't infer the target type from &Vec<T>, &Authenticated<T>, or a loaded relationship wrapper. In that case, pass a slice or dereference the wrapper instead:
let teams = Team::all().await?;notification::to(teams.as_slice()).send(InvoicePaid { invoice }).await?;Queueing notifications
queue sends the messages from a queue worker, which retries each message when its provider fails, so start a worker before you queue notifications. Before you await queue, you may delay the messages and choose the queue their jobs go to:
use dust::time::ToSpan;notification::to(&user) .queue(InvoicePaid { invoice }) .delay(5.minutes()) .on_queue("notifications") .await?;queue dispatches one job for each notifiable and channel, as queued mail and queued SMS do. Three users and two channels make six jobs, and a failed text message retries only that text message, never the email.
Without on_connection and on_queue, email jobs use MAIL_QUEUE_CONNECTION and MAIL_QUEUE, text message jobs use SMS_QUEUE_CONNECTION and SMS_QUEUE, and Slack and package channel jobs use the default connection and queue.
If you queue a notification inside a database transaction, dust-framework waits to dispatch the jobs until the transaction commits. If the transaction rolls back, the queued notifications are discarded so users are never notified about changes that were not saved.
Because each message is its own job, a permanently failed message appears in failed_jobs, or in the DUST Cloud dashboard on managed queues, and can be retried on its own with queue:retry. Delivery is at least once, so a provider that accepted a message but lost the response may receive it again; keep messages safe to repeat or rely on the provider's idempotency support.
Choosing channels for each notifiable
By default, a notification is delivered on every channel defined in its #[notification] block. However, you may want to let individual users opt in or out of specific channels, or decide which channels to use based on the notification's data. To control delivery per recipient, add a channels method to your notification. For example, suppose your users table has an sms_alerts column configured on a settings page:
use dust::notification;use dust::notification::{Mail, Selected, Sms};#[notification]impl InvoicePaid { // `mail` and `sms` as before... fn channels(&self, user: &User, channels: &mut Selected<Self, User>) { channels.add(Mail); if user.sms_alerts && self.invoice.total >= 10_000 { channels.add(Sms); } }}channels runs once for each notifiable, before dust-framework 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.
Package channels
Your users may want notifications where dust-framework has no channel, such as Discord. A package can add that channel, and your notifications build its messages next to their email and text messages.
Sending through a package channel
To send through a package channel, annotate a method in your #[notification] impl with #[via(..)] and the channel type. For example, suppose a discord_notifications package provides a Discord channel sending a DiscordMessage to a webhook URL:
use discord_notifications::{Discord, DiscordMessage};use dust::notification;use dust::notification::Receives;#[notification]impl InvoicePaid { // `mail` and `sms` as before... #[via(Discord)] fn discord(&self, _user: &User) -> DiscordMessage { DiscordMessage::new(format!("Invoice #{} is paid.", self.invoice.id)) }}The notifiable implements Receives<Discord>, whose route method returns the destination value defined by the package. Suppose your users table has a nullable discord_webhook_url column:
impl Receives<Discord> for User { fn route(&self) -> Option<String> { self.discord_webhook_url.clone() }}As with built-in channels, a package channel is included by default whenever Receives<Discord>::route returns Some. If your notification defines a channels method to select channels per recipient, include the package channel by passing its channel type to channels.add:
use discord_notifications::Discord;use dust::notification;use dust::notification::{Mail, Selected};#[notification]impl InvoicePaid { // `mail`, `sms`, and `discord` as before... fn channels(&self, user: &User, channels: &mut Selected<Self, User>) { channels.add(Mail); if user.discord_alerts { channels.add(Discord); } }}Passing a channel type to channels.add is type-checked: the code will only compile if the notification defines a #[via(Discord)] method and the notifiable implements Receives<Discord>.
Writing a channel
A channel is a unit struct with #[notification::channel] on its impl. The impl holds an async send function that takes a route and a message, and returns once the provider accepts the message. This is the Discord channel the package would provide:
use dust::http::client;use dust::notification;use serde::{Deserialize, Serialize};#[derive(Clone, Copy)]pub struct Discord;#[derive(Serialize, Deserialize)]pub struct DiscordMessage { pub content: String,}impl DiscordMessage { pub fn new(content: impl Into<String>) -> Self { Self { content: content.into() } }}#[notification::channel(name = "discord")]impl Discord { async fn send(webhook_url: String, message: DiscordMessage) -> dust::Result<()> { client::post(webhook_url).json(&message).ensure_successful().await?; Ok(()) } fn check(message: &DiscordMessage) -> dust::Result<()> { if message.content.chars().count() > 2000 { return Err(dust::abort_with( 500, "a Discord message holds at most 2,000 characters", )); } Ok(()) }}send's argument types become the channel's route and message types. Both must implement Serialize and Deserialize, because a queued job stores them. send runs in the application's context, so it may read configuration and resolve services, such as a config section that holds an API token.
The optional check function runs on each message as the notification builds it. A message the provider would refuse then fails in the code that sends it, and in your tests, rather than on the queue worker. Use it for limits the provider documents, such as Discord's 2,000 characters.
When you queue a notification for a custom channel, dust-framework records the channel's name in the queued job payload so workers know which channel's send function to invoke. If you omit name, dust-framework defaults to the struct's full Rust module path (such as discord_notifications::channels::Discord).
Giving your channel an explicit name decouples queued jobs from your module layout. That way, if you later move the struct to another module or rename it, jobs already sitting in the queue continue to run without failing:
#[notification::channel(name = "discord")]impl DiscordWebhook { async fn send(webhook_url: String, message: DiscordMessage) -> dust::Result<()> { // ... }}Testing
Most tests should check that your code sent a notification, not that a provider delivered it. notification::fake() records notifications instead of sending them. The fake still builds and renders each message as a real send would, so a template error or an invalid phone number fails the test:
use dust::model::create;use dust::notification;use dust::testing::prelude::*;#[dust::test]async fn paying_an_invoice_notifies_the_customer(app: Application) -> dust::Result<()> { let user = create!(User { name: "Taylor", email: "taylor@example.com", password: "password", }) .await?; let invoice = create!(Invoice { user_id: user.id, total: 120_000 }).await?; let notifications = notification::fake(); app.post(format!("/invoices/{}/pay", invoice.id)).await.assert_redirect(); notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| { sent.notification().invoice.id == invoice.id && sent.sms().is_none() }); Ok(())}Every SentNotification passed to a predicate exposes the original notification via notification(), along with queued() to check whether it was queued rather than sent synchronously. You can also inspect the rendered email with mail() or the mailable struct that built it with mailable::<M>():
notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| { sent.queued() && sent .mail() .is_some_and(|email| email.subject() == format!("Invoice #{} is paid", invoice.id)) && sent.mailable::<InvoicePaidEmail>().is_some_and(|mail| mail.name == user.name)});Each channel accessor returns None when that channel was skipped for the notifiable (for example, Taylor above has no phone number, so sent.sms() is None). When an SMS was sent, use sms() to inspect the message:
notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| { sent.sms().is_some_and(|sms| sms.text().contains("Thanks!"))});For Slack and custom package channels, pass the channel type to message::<C>() to inspect the built message:
use discord_notifications::Discord;use dust::notification::Slack;notifications.assert_sent_to_where::<InvoicePaid>(&team, |sent| { sent.message::<Slack>() .is_some_and(|message| message.text().contains(&format!("Invoice #{}", invoice.id)))});notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| { sent.message::<Discord>() .is_some_and(|message| message.content.contains(&format!("Invoice #{}", invoice.id)))});The fake has these assertions:
| Method | Asserts or returns |
|---|---|
assert_sent::<T>() |
A notification of type T was sent or queued at least once |
assert_sent_to::<T>(¬ifiable) |
A notification of type T was sent or queued to this notifiable |
assert_sent_to_where::<T>(¬ifiable, predicate) |
A notification of type T to this notifiable matches the predicate |
assert_not_sent_to::<T>(¬ifiable) |
No notification of type T was sent or queued to this notifiable |
assert_sent_where::<T>(predicate) |
A notification of type T, for one notifiable, matches the predicate |
assert_sent_times::<T>(count) |
Notifications of type T reached exactly count notifiables |
assert_not_sent::<T>() |
No notification of type T was sent or queued |
assert_nothing_sent() |
No notification was sent or queued |
sent::<T>() |
Each SentNotification of type T with its notification, in order |
The fake records both sent and queued notifications; use SentNotification::queued() to distinguish between them.
While the notification fake is active, notifications do not reach the mail fake or SMS fake. Without it, those fakes record notification messages alongside regular emails and text messages.