Broadcasting
- Introduction
- Configuration
- Broadcasting events
- Authorizing subscriptions
- Receiving broadcasts
- Dispatch options
- One-off broadcasts
- Queues and transactions
- Testing
Introduction
In many modern web applications, WebSockets power realtime, live-updating user interfaces. When an order ships, a deploy finishes, or a teammate joins a room, your application can broadcast its events to the browser over a WebSocket connection instead of having the page poll your server for changes.
Imagine a customer keeping their order page open while the warehouse packs their shipment. When the order ships, your application dispatches an OrderShipped event, and its listeners email the tracking number. With broadcasting, the same event also reaches the customer's browser so the page displays the tracking number without a refresh.
Configuration
The BROADCAST_CONNECTION environment variable controls how dust-framework publishes broadcasts:
| Connection | Behavior |
|---|---|
relay |
Publishes events to a Relay server. |
log |
Writes each broadcast's event name, channels, and payload to the log instead of publishing. New applications use this for local development. |
discard |
Drops all broadcasts without logging. Selected when BROADCAST_CONNECTION is unset or empty. |
To broadcast events to a browser on your machine, you need a running Relay server. For local development, dust-framework includes one behind the relay feature. Add relay to the features your application already enables for dust-framework in Cargo.toml:
[dependencies]dust-framework = { version = "0.1", features = ["database-postgres", "redis", "sqs", "relay"] }Next, switch BROADCAST_CONNECTION to relay and choose credentials in your .env file. The local Relay server reads the same RELAY_APP_ID, RELAY_APP_KEY, and RELAY_APP_SECRET variables as the relay broadcast connection, so values such as these work for local development without extra setup:
BROADCAST_CONNECTION=relay
RELAY_APP_ID=my-app
RELAY_APP_KEY=my-key
RELAY_APP_SECRET=my-secret
RELAY_HOST=localhost
RELAY_PORT=8080
RELAY_SCHEME=httpKeep RELAY_APP_SECRET on the server. The browser only needs the application key.
Start the local Relay server with the relay:start command:
dust relay:startTo learn more about configuring and running the local server, check out the WebSockets guide. In production, use DUST Cloud's managed Relay server instead of running relay:start.
Broadcasting events
Any event can be broadcast by listing its channels in the #[event(broadcast(..))] attribute. For example, this OrderShipped event broadcasts on a private channel for its order:
use dust::event::Event;#[derive(Event)]#[event(broadcast(private = "orders.{order_id}"))]pub struct OrderShipped { pub order_id: i64, pub tracking_number: String, pub(crate) internal_note: String,}Dispatch the event as you normally would, such as from the handler that marks the order as shipped:
use crate::events::OrderShipped;OrderShipped { order_id: 42, tracking_number: "TRACK-123".into(), internal_note: "Packed by warehouse B".into(),}.dispatch().await?;This publishes an OrderShipped event to the private-orders.42 channel with order_id and tracking_number in its payload. Any listeners registered for the event still run as usual.
Channels
Use public, private, or presence to choose each channel's visibility, and repeat them to broadcast on multiple channels. Each {field} placeholder is replaced with the value of that field on the event, including private fields. A model field formats as its route key so your channel authorization callback can bind the model again:
use dust::event::Event;use crate::models::Order;#[derive(Event)]#[event(broadcast( name = "order.shipped", private = "orders.{order}", private = "users.{user_id}", public = "shipping",))]pub struct OrderShipped { pub order: Order, pub user_id: i64,}Use private channels for user-specific or order-specific updates, since anyone can subscribe to a public channel.
| Type | Who may subscribe | Typical use |
|---|---|---|
| Public | Anyone with the channel name | Announcements, live scores, deploy status |
| Private | Only clients whose authorization callback returns true |
A user's orders, a team's private data |
| Presence | Authorized clients, plus a member list visible to everyone on the channel | Chat rooms, who is viewing a document |
Presence channels carry the same authorization requirement as private channels. Returning Some(Member) both authorizes the subscription and publishes that member's data to the other subscribers, so never include fields the room should not see.
By default, an event broadcasts under its struct name, such as OrderShipped. You may override this with the name option. When listening for events in Echo, prefix any custom name containing dots with a leading dot, such as '.order.shipped'.
The payload
dust-framework builds the broadcast payload from the event's pub fields and omits private and pub(crate) fields. Every pub field included in the payload must implement Serialize. You may also rename or exclude individual pub fields using attributes:
use dust::event::Event;#[derive(Event)]#[event(broadcast(private = "orders.{order_id}"))]pub struct OrderShipped { pub order_id: i64, #[event(rename = "trackingNumber")] pub tracking_number: String, #[event(skip)] pub warehouse: String, pub(crate) internal_note: String,}In this example, order_id and trackingNumber are sent to the browser, while warehouse and internal_note are omitted.
Every subscriber on the channel receives the same payload, so only include data that every authorized subscriber is allowed to see.
Custom broadcasts
When the attribute isn't flexible enough, such as when you need a custom payload shape or want to broadcast only under certain conditions, mark the event with #[event(broadcast)] and implement the Broadcast trait. Implement broadcast_on to return the channels, and optionally implement broadcast_with for the payload, broadcast_as for the event name, and broadcast_when to conditionally skip broadcasting:
use dust::broadcast::{Broadcast, Channel};use dust::event::Event;use serde_json::{Value, json};#[derive(Event)]#[event(broadcast)]pub struct OrderUpdated { pub order_id: i64, pub status: String, notify: bool,}impl Broadcast for OrderUpdated { fn broadcast_on(&self) -> dust::Result<Vec<Channel>> { Ok(vec![Channel::private(format!("orders.{}", self.order_id))?]) } fn broadcast_with(&self) -> dust::Result<Value> { Ok(json!({ "id": self.order_id, "status": self.status })) } fn broadcast_when(&self) -> bool { self.notify }}Authorizing subscriptions
Before a browser can subscribe to a private or presence channel, Echo sends an authorization request to your application to verify that the current user may listen. New applications register their channels in src/routes/channels.rs, which src/app.rs passes to routing.channels to serve Echo's requests at POST /broadcasting/auth. Each channel pairs a pattern with an authorization callback that accepts the same arguments as a handler, such as Authenticated<User>, Auth<User>, Inject<T>, Params, and models.
For example, suppose your application has an Order model and each user has a team_id column. The following channel definitions allow signed-in users to subscribe to their own orders and to their team's presence channel:
use dust::broadcast::{Channels, Member};use dust::prelude::*;use serde_json::json;use crate::models::{Order, User};pub fn routes(channel: &mut Channels) { channel.private("orders.{order}", order); channel.presence("teams.{team}", team);}async fn order(order: Order, user: Authenticated<User>) -> bool { order.user_id == user.id}async fn team(Params(team): Params<i64>, user: Authenticated<User>) -> dust::Result<Option<Member>> { if user.team_id != team { return Ok(None); } Ok(Some(Member::new( user.id.to_string(), json!({ "id": user.id, "name": user.name }), )?))}Extracting Authenticated<User> denies guests with a 403 response automatically without calling your callback or redirecting to a login page. If a channel needs to inspect optional authentication state instead, extract Auth<User>.
A private channel callback returns true to authorize the subscription or false to deny it. A presence channel callback returns Some(Member) with the member data visible to other subscribers on the channel, or None to deny the subscription. Only include member fields that every subscriber on the channel may see.
Channel patterns omit the private- or presence- prefix, and each {parameter} matches a single dot-separated segment. Browsers cannot subscribe to any private or presence channel that has not been registered.
Callbacks bind models like handlers do, matching each route parameter by name so order: Order reads {order}. As with nested routes, teams.{team}.orders.{order} scopes the order to that team. If no matching row exists or a parameter fails to parse, dust-framework rejects the subscription with a 403 response without calling your callback:
use dust::broadcast::Channels;use dust::prelude::*;use crate::models::{Order, Team, User};pub fn routes(channel: &mut Channels) { channel.private("teams.{team}.orders.{order}", team_order);}async fn team_order(team: Team, order: Order, user: Authenticated<User>) -> bool { user.team_id == team.id && order.user_id == user.id}New applications include a sample example-channel in src/routes/channels.rs that returns true; replace it with your own channels.
[!WARNING] Registering a channel does not require authentication on its own. A callback that returns
truewithout checking the user allows guests to subscribe as well.
Receiving broadcasts
In the browser, Echo subscribes to channels and listens for events. This guide uses Echo's React bindings; the same channel and event names work with any Pusher-compatible client.
Installing Echo
Relay speaks the Pusher protocol, so install Echo's React package alongside dust-echo and pusher-js:
npm install @dust/echo-react dust-echo pusher-jsExpose the Relay application key, host, port, and scheme to the browser from the page that boots Echo. Only the key belongs in the browser; RELAY_APP_SECRET stays on the server.
Next, configure Echo once where your frontend starts:
import { configureEcho } from '@dust/echo-react';configureEcho({ broadcaster: 'relay', namespace: false,});By default, Echo prefixes event names with App.Events, which dust-framework Rust's events do not use. Setting namespace: false disables that prefix so you can listen for events by the exact name they broadcast with, such as 'OrderShipped'.
Load the configured Echo bundle on the pages that use broadcasts. The default io/ui frontend ships no Node.js build step, so bundle @dust/echo-react only on a page where you add a React surface.
Listening for events
Call useEcho in a component with the channel name, event name, and a callback. Echo authorizes the private channel subscription automatically and leaves the channel when the component unmounts:
import { useEcho } from '@dust/echo-react';export function OrderStatus({ order }) { useEcho(`orders.${order.id}`, 'OrderShipped', (event) => { console.log(event.tracking_number); }); // ...}The callback receives the event's payload. To listen for multiple events on the same channel, pass an array of event names:
useEcho(`orders.${order.id}`, ['OrderShipped', 'OrderCancelled'], (event) => { console.log(event.order_id);});In TypeScript, pass a type parameter to type the event payload:
type OrderShippedPayload = { order_id: number; tracking_number: string;};useEcho<OrderShippedPayload>(`orders.${order.id}`, 'OrderShipped', (event) => { console.log(event.tracking_number);});useEcho also returns helpers to pause listening, resume listening, or leave the channel early:
const { stopListening, listen, leaveChannel } = useEcho( `orders.${order.id}`, 'OrderShipped', (event) => { console.log(event.tracking_number); },);// Stop listening without leaving the channel...stopListening();// Start listening again...listen();// Leave the channel...leaveChannel();[!WARNING] Even with
namespace: false, Echo converts dots inside an event name into backslashes. Prefix any event name that contains dots with a leading dot, such as'.order.shipped'or'.export.progress', so Echo uses the name as written.
Public and presence channels
useEcho subscribes to private channels by default. To subscribe to a public channel, use useEchoPublic:
import { useEchoPublic } from '@dust/echo-react';useEchoPublic('deploys', 'DeployFinished', (event) => { console.log(event.environment);});Presence channels also track who is currently subscribed. Subscribe with useEchoPresence, then attach here, joining, and leaving callbacks to the channel. here receives the list of members already present, while joining and leaving receive a single member as users arrive or depart. Each member object matches the Member payload returned by your channel authorization callback:
import { useEffect, useState } from 'react';import { useEchoPresence } from '@dust/echo-react';export function TeamMembers({ team }) { const [members, setMembers] = useState([]); const { channel } = useEchoPresence(`teams.${team.id}`); useEffect(() => { channel() ?.here((members) => setMembers(members)) .joining((member) => setMembers((members) => [...members, member])) .leaving((member) => setMembers((members) => members.filter((other) => other.id !== member.id), ), ); }, [channel]); return members.map((member) => <span key={member.id}>{member.name}</span>);}Client events
Sometimes a browser needs to notify other browsers directly without hitting your application server, such as showing a "typing" indicator. Send client events through Relay with whisper and receive them with listenForWhisper. Client events work on private and presence channels:
import { useEffect } from 'react';import { useEchoPresence } from '@dust/echo-react';export function MessageBox({ team, user }) { const { channel } = useEchoPresence(`teams.${team.id}`); useEffect(() => { channel()?.listenForWhisper('typing', (event) => { console.log(`${event.name} is typing...`); }); }, [channel]); const typing = () => channel()?.whisper('typing', { name: user.name }); return <textarea onChange={typing} />;}Connection status
To display whether the browser is connected to Relay, call useConnectionStatus. It returns connected, connecting, reconnecting, disconnected, or failed:
import { useConnectionStatus } from '@dust/echo-react';export function ConnectionIndicator() { const status = useConnectionStatus(); return <div>Connection: {status}</div>;}Dispatch options
Often, the browser that triggered an action already reflects the change and doesn't need to receive the broadcast. To exclude the current user's browser tab, dispatch the event with broadcast::event and call to_others:
use dust::broadcast;use crate::events::OrderShipped;broadcast::event(OrderShipped { order_id: 42, tracking_number: "TRACK-123".into(), internal_note: "Packed by warehouse B".into(),}).to_others().await?;to_others reads the socket ID from the request's X-Socket-ID header and excludes only that browser tab, leaving the user's other open tabs subscribed. If the request does not include a socket ID, to_others broadcasts to everyone.
Echo keeps the socket ID in the connected client. To send it with a request, read it with useSocketId and add it to the headers yourself:
import { useSocketId } from '@dust/echo-react';export function RefundButton({ order }) { const socketId = useSocketId(); const refund = () => fetch(`/orders/${order.id}/refund`, { method: 'POST', headers: { 'X-Socket-ID': socketId }, }); return <button onClick={refund}>Refund</button>;}When making requests from outside a browser, such as inside a queued job, exclude a specific socket directly with except_socket("123.456").
broadcast::event dispatches the event and runs its listeners like dispatch, with these additional options:
| Method | Effect |
|---|---|
to_others() |
Excludes the browser tab that sent the current request. |
except_socket(id) |
Excludes the given socket ID. |
via(name) |
Publishes through the named broadcast connection. |
on_connection(name), on_queue(name) |
Delivers the broadcast through the given queue connection or queue. |
One-off broadcasts
Some messages don't warrant a dedicated event struct, such as progress updates from a long-running export. You may publish directly to a channel by passing an event name and payload. For example, a job exporting a report can broadcast its progress using its export_id:
use dust::broadcast;use serde_json::json;broadcast::private(format!("exports.{export_id}")) .send("export.progress", json!({ "percent": 75 })) .await?;broadcast::public, broadcast::private, and broadcast::presence take the channel name without its prefix. send delivers through the queue as broadcast events do, while send_now publishes immediately. Both support all of the dispatch options. Because the event name above contains dots, listen for it in Echo with a leading dot: '.export.progress'.
One-off broadcasts do not dispatch an application event, so no listeners run.
Queues and transactions
Dispatching a broadcast event prepares its channels and payload, then pushes a job onto your queue to publish them. If Relay is temporarily unreachable, the job retries automatically. If Relay rejects the broadcast, such as for an invalid RELAY_APP_SECRET, the job fails immediately with Relay's error message. Inside a database transaction, the broadcast waits until the transaction commits, and a rollback discards it so browsers never receive updates for rolled-back data.
To publish without using the queue, add immediately to the broadcast attribute. Dispatching then publishes right away and returns any Relay error directly. Inside a transaction, the broadcast still waits for the commit, and db::transaction returns any publish failure as an AfterCommitError:
use dust::event::Event;#[derive(Event)]#[event(broadcast(public = "orders", immediately))]pub struct OrderShipped { pub order_id: i64,}Most applications should leave broadcasting on the queue so a Relay outage doesn't fail incoming requests. Reach for immediately only when an update must reach browsers without waiting for a queue worker.
Testing
Call broadcast::fake() in a test to record broadcasts in memory instead of publishing them. The event's listeners still run as normal:
use dust::broadcast;use dust::testing::prelude::*;use crate::events::OrderShipped;#[dust::test]async fn shipping_an_order_broadcasts_it(_app: Application) -> dust::Result<()> { let broadcasts = broadcast::fake(); OrderShipped { order_id: 42, tracking_number: "TRACK-123".into(), internal_note: "Packed by warehouse B".into(), } .dispatch() .await?; broadcasts.assert_broadcasted_where::<OrderShipped>(|event| { event.channels == ["private-orders.42"] && event.payload["tracking_number"] == "TRACK-123" && event.payload.get("internal_note").is_none() }); Ok(())}The broadcast fake also provides assert_broadcasted, assert_broadcasted_times, assert_not_broadcasted, and assert_nothing_broadcasted. To inspect a one-off broadcast, look it up by event name:
use serde_json::json;let records = broadcasts.broadcast_named("export.progress");assert_eq!(records[0].channels, ["private-exports.42"]);assert_eq!(records[0].payload, json!({ "percent": 75 }));An event fake records the event without broadcasting it, so use broadcast::fake() on its own when testing broadcasts.