dust

SMS

Introduction

Text messages reach users who aren't looking at their email, which makes them a good fit for sign-in codes and urgent alerts. The dust::sms module sends text messages through Telnyx in production, and writes them to your log in development.

When you want to reach users on more than one channel, such as an email and a text message about the same paid invoice, send a notification instead. Notifications send their text messages with the configuration on this page.

Configuration

dust-framework reads its SMS configuration from these environment variables:

Variable Sets Default
SMS_SENDER The default sender log
SMS_FROM The number, short code, or sender ID that messages come from None
SMS_QUEUE_CONNECTION, SMS_QUEUE Where queued messages go The default queue connection and queue

By default, dust-framework uses the log sender so new applications never send real text messages until you configure Telnyx. It logs each recipient at info and the message body at debug. To view message bodies locally, such as sign-in codes during development, raise the log level for SMS:

ini
LOG_LEVEL=info,dust::sms=debug

Telnyx

Create an API key in the Telnyx portal, then select the telnyx sender:

ini
SMS_SENDER=telnyx
SMS_FROM=+15555550100
TELNYX_KEY=KEY0123

Telnyx needs to know which number a message comes from, so set SMS_FROM, TELNYX_MESSAGING_PROFILE_ID, or both. With only a messaging profile, Telnyx picks a number from the profile's number pool.

send returns once Telnyx accepts a message, but a carrier may still refuse to deliver it. US carriers, for example, block messages from numbers that aren't registered for 10DLC. You'll find those failures in the message's status in the Telnyx portal, not in an error from send.

Adding senders

If your application needs a second Telnyx account or messaging profile, such as separating on-call alerts from customer messages, register a named sender in src/app.rs:

rust
use dust::config::sms::Telnyx;Application::configure()    .with_config(|config, env| {        let key: String = env.get("TELNYX_ALERTS_KEY").unwrap_or_default();        config.sms.add_sender(            "alerts",            Telnyx::new(key)                .messaging_profile_id("40017f8e-49bd-4f6a-a7a2-9c1b5d7a2f61")                .from("+15555550150"),        );    })

A sender's from number replaces SMS_FROM for its messages, falling back to SMS_FROM when unset. Setting a number on the message itself overrides both.

To send through the alerts sender, name it with sender. It works with send and queue:

rust
use dust::sms;sms::to("+15555550123").sender("alerts").send("The deploy finished.").await?;

Sending messages

To send a text message, pass the recipient's number to sms::to and the body to send. For example, suppose your application has an Order model and a nullable phone column on users:

rust
use dust::prelude::*;use dust::sms;pub async fn ship(Params(id): Params<i64>) -> dust::Result<Redirect> {    let order = Order::find_or_fail(id).await?;    let customer = User::find_or_fail(order.user_id).await?;    // Ship the order...    if let Some(phone) = &customer.phone {        sms::to(phone).send(format!("Order #{} has shipped.", order.id)).await?;    }    Ok(Redirect::back())}

send waits for the provider to accept the message. To send from a number other than SMS_FROM, pass an sms::Message:

rust
use dust::sms::{self, Message};sms::to("+15555550123")    .send(Message::new("Your order shipped.").from("+15555550199"))    .await?;

dust-framework validates the recipient and body before calling Telnyx, so an invalid number or empty message fails immediately at the send call. Messages are not automatically truncated: Telnyx splits long messages into multiple segments and bills per segment (up to 160 characters for GSM text, or 70 characters when emoji or non-GSM characters are included), so keep alerts and verification codes concise.

Phone numbers

Recipient phone numbers must be in E.164 format with a leading + and country code, such as +15555550123. sms::to accepts &str, String, or PhoneNumber and strips formatting characters such as spaces, dashes, dots, and parentheses (so +1 (555) 555-0123 is valid).

Numbers without a country code (such as 555-0123) fail validation because national numbers are ambiguous across countries, so store user phone numbers in E.164 format when collected.

Queueing messages

Sending SMS synchronously during a request adds external network latency and ties the request's success to Telnyx availability. Call queue instead to deliver messages through a queue worker with automatic retries on failure. Before awaiting, you may delay delivery or pick a specific queue:

rust
use dust::sms;use dust::time::ToSpan;sms::to("+15555550123")    .queue("Your order shipped.")    .delay(5.minutes())    .on_queue("sms")    .await?;

The job holds the message encrypted with your application key, so you may queue sign-in codes. Like every job, it waits for the current database transaction to commit, and a rollback discards it. A retry doesn't text the customer twice, because every attempt sends Telnyx the same idempotency key.

Failure modes

Text messages fail in two different places, and only one of them produces an error:

Symptom Cause What to do
send returns an error An invalid number, an empty body, or a rejected API key Fix the input or key; the request is not retried
send succeeds, but no message arrives A carrier filter, an unregistered sender, or a recipient opt-out Check the message status in the Telnyx portal
A queued message is in failed_jobs Telnyx was unavailable or rejected the request Fix the cause and retry with queue:retry
A short alert is billed as two segments More than 160 GSM characters, or more than 70 with emoji Shorten the message or accept the cost

A successful send only means Telnyx accepted the message. Delivery to the handset is the carrier's decision, so treat SMS as best-effort and offer email or an in-app notice for anything critical.

Testing

You don't want your test suite texting real phones. sms::fake() records messages instead of sending them, and checks each one as a real send would, so an invalid number still fails the test:

rust
use dust::model::create;use dust::sms;use dust::testing::prelude::*;#[dust::test]async fn customers_hear_when_their_order_ships(app: Application) -> dust::Result<()> {    let user = create!(User {        name: "Taylor",        email: "taylor@example.com",        password: "password",        phone: "+15555550123",    })    .await?;    let order = create!(Order { user_id: user.id, total: 2500 }).await?;    let sms = sms::fake();    app.post(format!("/orders/{}/ship", order.id)).await.assert_redirect();    sms.assert_sent_where(|message| {        message.to() == "+15555550123" && message.text().contains("has shipped")    });    Ok(())}

The fake counts send as sent and queue as queued, and has assertions for each:

Method Asserts or returns
assert_sent_where(predicate), assert_queued_where(predicate) A sent, or queued, message matches the predicate
assert_sent_times(count), assert_queued_times(count) Exactly count messages were sent, or queued
assert_nothing_sent() No message was sent or queued
sent(), queued() Each sent, or queued, message, in order

The predicate receives the message, with to(), from(), and text(). A queued message also has connection(), queue(), and delay(), so you may check where its job would go:

rust
sms.assert_queued_where(|message| message.queue() == "sms" && message.delay() == 5.minutes());