Events
- Introduction
- Defining events
- Defining listeners
- Dispatching events
- Queued listeners
- Database transactions
- Testing events
Introduction
Events provide a clean way to decouple parts of your application so a single action can trigger multiple side effects. When a customer places an order, you may want to email a receipt, record an audit log entry, and notify the warehouse. Rather than growing your order logic with every new step, dispatch an OrderPlaced event and let independent listeners react to it.
An event is a plain Rust struct, and a listener is an async function marked with #[listener]. dust-framework discovers your listeners automatically when the application boots, so no manual registration is required. Models also dispatch model events when created, updated, or deleted, and broadcasting lets you push events to the browser over WebSockets.
Events are one tool among several; pick the one that matches the coupling you want:
| Approach | Coupling | When to use it |
|---|---|---|
| A direct function call | The caller knows the callee | The step is part of the operation's contract |
| An inline listener | The caller knows only the event | Several cheap reactions, and the caller should wait |
| A queued listener | The caller knows only the event | A slow or unreliable reaction that must retry |
| A broadcast | The browser knows only the channel | A live update for connected clients |
An event with several listeners is not a transaction. Inline listeners run in order and the first error stops the rest, while queued listeners are separate jobs that succeed or fail independently.
Defining events
An event is a struct that derives Event. New applications keep events in src/events/:
use dust::event::Event;#[derive(Event)]pub struct OrderPlaced { pub order_id: i64, pub email: String, pub total: i64,}Events store owned values (such as String rather than &str), so clone or copy any data your listeners need instead of borrowing from the request.
Name an event after the fact that already happened, in the past tense: OrderPlaced, InvoicePaid, UserVerified. A listener that reacts to it reads as a sentence, and the name stays accurate as you add reactions. Name listeners after the effect they produce, such as send_receipt, so logs and queued job names describe what ran.
Defining listeners
A listener is an async function annotated with #[listener]. Its first parameter is Event<T>, which dereferences to your event struct, and it returns either () or dust::Result<()>. New applications keep listeners in src/listeners/. For example, this listener emails an OrderReceipt mailable:
use dust::event::{Event, listener};use dust::mail;use crate::events::OrderPlaced;use crate::mail::OrderReceipt;#[listener]pub async fn send_receipt(event: Event<OrderPlaced>) -> dust::Result<()> { mail::to(&event.email) .send(OrderReceipt { order_id: event.order_id, }) .await?; Ok(())}Like HTTP handlers, listeners may accept services via Inject<T> and config sections via Section<T> in any order after the event parameter.
Discovering tagged listeners
dust-framework automatically discovers #[listener] functions in your application's app library crate. You may place them in any module as long as src/lib.rs declares the module so it is compiled. New applications declare pub mod listeners and mark listeners pub so tests can reference them directly.
Packages opt into listener discovery inside their service provider's register method:
use dust::container::Registrar;fn register(&self, app: &mut Registrar) { app.events().discover(env!("CARGO_CRATE_NAME"));}If your application's library crate is not named app, call events.discover(env!("CARGO_CRATE_NAME")) inside with_events in src/app.rs.
Registering listeners
To register a listener without #[listener] (such as an inline closure or a function defined in another crate), call events.listen inside with_events in src/app.rs. dust-framework infers the event type from the listener's first argument:
use dust::event::Event;Application::configure() .with_events(|events, _config| { events.listen(async |event: Event<OrderPlaced>| { tracing::info!(order_id = event.order_id, "Order placed"); }); })Packages can register listeners manually in their service provider's register method using app.events().listen(..).
[!WARNING] Do not also pass a
#[listener]function toevents.listen, or it will run twice for every dispatch.
Dispatching events
Call dispatch on an event instance to notify its listeners. For example, given an Order model, this function creates an order and dispatches OrderPlaced:
use dust::model::create;use crate::events::OrderPlaced;use crate::models::{Order, User};pub async fn place_order(user: &User, total: i64) -> dust::Result<Order> { let order = create!(Order { user_id: user.id, total, }) .await?; OrderPlaced { order_id: order.id, email: user.email.clone(), total, } .dispatch() .await?; Ok(order)}dispatch invokes the event's listeners sequentially and resolves once all of them finish.
[!NOTE] Inline listeners share the caller's request context and run in the order they were registered. Queued listeners are independent jobs that may run on different workers and in a different order. Do not rely on the order across a mix of inline and queued listeners; encode any required sequence inside one listener or use a job chain.
Failures
If a listener returns an error, any remaining listeners are skipped and dispatch returns that error. A handler propagating the error with ? returns an error response. To prevent a failing listener from failing the request, report the error instead of returning it:
let event = OrderPlaced { order_id: order.id, email: user.email.clone(), total,};if let Err(error) = event.dispatch().await { dust::report(error);}Inside a database transaction, listeners run after the transaction commits, so listener errors are returned by db::transaction instead.
Background dispatch
When a request does not need to wait for listeners to complete, call dispatch_background. It launches the listeners in a background task within the current process and returns immediately without .await:
OrderPlaced { order_id: order.id, email: user.email.clone(), total,}.dispatch_background()?;Because no caller awaits the task, dust-framework reports any listener errors automatically. Inside a database transaction, the background task starts only after the transaction commits, and a rollback discards it. During graceful shutdown, the server waits for in-flight background events up to SERVER_SHUTDOWN_TIMEOUT.
[!WARNING] Background events are kept only in memory and are not retried, so a crash or restart can lose them. For work that must complete reliably, use a queued listener.
Queued listeners
When a listener performs slow work such as sending an email or calling a third-party API, run it on your queue with #[listener(queued)]. Because the queue serializes the event until a worker processes it, the event must also derive Queueable:
use dust::event::{Event, listener};use dust::mail;use dust::queue::Queueable;use crate::mail::OrderReceipt;#[derive(Event, Queueable)]pub struct OrderPlaced { pub order_id: i64, pub email: String, pub total: i64,}#[listener(queued)]pub async fn send_receipt(event: Event<OrderPlaced>) -> dust::Result<()> { mail::to(&event.email) .send(OrderReceipt { order_id: event.order_id, }) .await?; Ok(())}Dispatching the event now pushes a job containing the event so a queue worker executes the listener asynchronously, while any non-queued listeners still run inline. Inside a database transaction, the job is pushed only after the transaction commits, like any queued job.
Queued listeners behave like jobs. After Event<T>, they may accept Inject<T> services, Section<T> config sections, and &Attempt to release, delete, or fail the job. Event fields may also hold models, which the worker reloads from the database before invoking the listener. If a model's row has been deleted by then, the worker deletes the job without invoking the listener, unless the listener has the fail_when_missing_models option.
Queue options
#[listener(queued, ..)] supports all #[job] options (such as queue, tries, backoff, and timeout), as well as connection and delay:
#[listener( queued, connection = "redis", queue = "emails", delay = 10.minutes(), tries = 3, backoff = 1.minutes(),)]pub async fn send_receipt(event: Event<OrderPlaced>) -> dust::Result<()> { // Email the receipt... todo!()}dust-framework identifies the queued job using the listener's module path, such as app::listeners::send_receipt. Before renaming or moving a listener that may still have queued jobs in flight, preserve compatibility by setting name = "app::listeners::send_receipt".
Listener structs
When a queued listener needs additional hooks beyond handle, place #[listener(queued)] on a unit struct's impl block. Implement an async handle function along with any of the optional hooks below (none take self):
| Function | Parameters | Purpose |
|---|---|---|
handle |
Event<T>, plus services, config sections, and &Attempt |
Executes the listener on the worker. |
failed |
Event<T>, &dust::Error, plus services, config sections, and &Attempt |
Cleans up when the job fails permanently. |
should_queue |
&T |
Returns false to skip queueing the listener for this event. |
middleware |
&T |
Returns job middleware wrapping the listener. |
debounce_id |
&T |
Groups debounced listener runs. |
For example, this listener awards a gift card for orders of $50 or more (total in cents) and logs a warning if all retries fail:
use dust::event::{Event, listener};use dust::model::create;use crate::events::OrderPlaced;use crate::models::GiftCard;pub struct RewardGiftCard;#[listener(queued, queue = "rewards", tries = 3)]impl RewardGiftCard { fn should_queue(event: &OrderPlaced) -> bool { event.total >= 5000 } async fn handle(event: Event<OrderPlaced>) -> dust::Result<()> { create!(GiftCard { order_id: event.order_id, amount: 500, }) .await?; Ok(()) } async fn failed(event: Event<OrderPlaced>, error: &dust::Error) { tracing::warn!( order_id = event.order_id, %error, "Couldn't reward a gift card", ); }}should_queue runs before the job is pushed, so skipped listeners never touch the queue.
Debouncing listeners
When an event fires repeatedly in quick succession, you may want to handle only the final occurrence. For instance, a user saving their profile five times in a minute should receive one confirmation email, not five. Listen for the Updated<User> model event with debounce_for and a debounce_id that groups related events:
use dust::event::{Event, listener};use dust::mail;use dust::model::Updated;use crate::mail::ProfileUpdated;use crate::models::User;pub struct SendProfileUpdatedEmail;#[listener(queued, debounce_for = 1.minutes())]impl SendProfileUpdatedEmail { fn debounce_id(event: &Updated<User>) -> i64 { event.model.id } async fn handle(event: Event<Updated<User>>) -> dust::Result<()> { mail::to(&event.model.email) .send(ProfileUpdated { user: event.model.clone(), }) .await?; Ok(()) }}Each user now receives a single email one minute after their last update. Without debounce_id, every Updated<User> event would share a single debounce key across all users. To guarantee the listener still runs if a user keeps saving continuously, cap the wait with max_wait, such as #[listener(queued, debounce_for = 1.minutes(), max_wait = 5.minutes())].
Debounced jobs are tracked in your default cache store, so use a shared store like database or redis when running multiple servers. You can learn more about debouncing options in the debounced jobs documentation.
Database transactions
Events dispatched inside a database transaction wait until the outermost transaction commits before running their listeners. If the transaction rolls back, the pending events are discarded so listeners never send receipts or read uncommitted rows. Outside a transaction, dispatch runs listeners immediately. Jobs and broadcasts also wait for transactions to commit.
For example, this version of place_order saves an order and its payment atomically and dispatches OrderPlaced only once both commit:
use dust::db;use dust::model::create;use crate::events::OrderPlaced;use crate::models::{Order, Payment, User};pub async fn place_order(user: &User, total: i64) -> dust::Result<Order> { let order = db::transaction(async |_| { let order = create!(Order { user_id: user.id, total, }) .await?; create!(Payment { order_id: order.id, amount: total, }) .await?; OrderPlaced { order_id: order.id, email: user.email.clone(), total, } .dispatch() .await?; Ok(order) }) .await?; Ok(order)}Inside the transaction, dispatch returns Ok immediately and defers execution until commit. If a deferred listener fails after commit, db::transaction returns an AfterCommitError while the database changes remain committed. Avoid retrying the transaction, since the order is already saved. You can learn more about handling after-commit failures in the database transactions documentation.
Running listeners in the transaction
Some listeners must participate in the transaction itself, such as reserving inventory that should succeed or roll back alongside the order. Annotate those listeners with #[listener(at_dispatch)] so they run immediately when dispatch is called instead of waiting for commit:
use dust::event::{Event, listener};use dust::model::create;use crate::events::OrderPlaced;use crate::models::Reservation;#[listener(at_dispatch)]pub async fn reserve_stock(event: Event<OrderPlaced>) -> dust::Result<()> { create!(Reservation { order_id: event.order_id, }) .await?; Ok(())}Because dispatch runs at_dispatch listeners before returning, their database writes commit or roll back with the enclosing transaction, and propagating an error with ? rolls the transaction back. All other listeners for the event still wait for commit. Keep at_dispatch listeners fast, since the transaction holds its row locks while they execute.
To run every listener of an event at dispatch time, mark the event struct with #[event(at_dispatch)]. When registering a listener manually in with_events, call events.listen_at_dispatch(reserve_stock).
Testing events
When testing code that dispatches events, you typically want to assert that the expected event was dispatched while testing listeners separately. Call event::fake() to record dispatched events without executing their listeners, then run assertions on the returned fake:
use dust::event;use dust::model::create;use dust::testing::prelude::*;use serde_json::json;use app::events::OrderPlaced;use app::models::User;#[dust::test]async fn placing_an_order_dispatches_an_event(app: Application) -> dust::Result<()> { let user = create!(User { name: "Taylor", email: "taylor@example.com", password: "password", }) .await?; let events = event::fake(); app.post("/orders") .acting_as(&user) .json(json!({ "total": 2500 })) .await .assert_created(); events.assert_dispatched::<OrderPlaced>(); events.assert_dispatched_where::<OrderPlaced>(|event| { event.email == "taylor@example.com" && event.total == 2500 }); events.assert_dispatched_times::<OrderPlaced>(1); Ok(())}You may also call assert_not_dispatched::<T>(), assert_not_dispatched_where, and assert_nothing_dispatched(). To inspect recorded events directly, events.dispatched::<OrderPlaced>() returns them in dispatch order.
The fake stays active for the lifetime of its handle; dropping the handle restores normal event dispatch. Each test application maintains an isolated fake, so concurrent tests never see each other's events.
Faking selected events
To fake only specific events while allowing all other events to run their listeners normally, chain .only::<T>() before exercising your application:
let events = event::fake() .only::<OrderPlaced>() .only::<OrderCancelled>();To fake every event except specific ones, chain .except::<T>(), such as event::fake().except::<OrderShipped>().
Testing a listener
To test a single listener in isolation without running other listeners for the same event, pass the listener and event instance to app.listener. The listener resolves its injected services normally, so swapped fakes and helpers like the mail fake work as expected:
use dust::mail;use dust::testing::prelude::*;use app::events::OrderPlaced;use app::listeners::send_receipt;use app::mail::OrderReceipt;#[dust::test]async fn customers_get_a_receipt(app: Application) -> dust::Result<()> { let mail = mail::fake(); app.listener( send_receipt, OrderPlaced { order_id: 42, email: "taylor@example.com".into(), total: 2500, }, ) .await?; mail.assert_sent_where::<OrderReceipt>(|email| email.has_to("taylor@example.com")); Ok(())}app.listener returns any error produced by the listener. For a queued listener, app.listener pushes its job onto the queue; because tests use the sync queue connection even when a listener specifies a custom connection, the job executes before app.listener returns.
Testing queued listeners
A queued listener pushes a Queued<L> job that dereferences to the event. To verify that dispatching an event queued the listener, use the queue fake:
use dust::event::Queued;use dust::model::create;use dust::queue;use dust::testing::prelude::*;use serde_json::json;use app::listeners::send_receipt;use app::models::User;#[dust::test]async fn placing_an_order_queues_the_receipt(app: Application) -> dust::Result<()> { let user = create!(User { name: "Taylor", email: "taylor@example.com", password: "password", }) .await?; let queue = queue::fake(); app.post("/orders") .acting_as(&user) .json(json!({ "total": 2500 })) .await .assert_created(); queue.assert_pushed_where::<Queued<send_receipt>>(|job| { job.email == "taylor@example.com" && job.queue() == "emails" }); Ok(())}Because event::fake() prevents listeners from running at all, nothing reaches the queue when both are active. Use queue::fake() on its own when testing queued listeners.
To test how a single job attempt behaves (such as a release or failure), run the queued listener job directly with app.job:
app.job(Queued::<send_receipt>::new(OrderPlaced { order_id: 42, email: "taylor@example.com".into(), total: 2500,})).await.assert_succeeded();