dustapp.dev

A field guide to the full stack

The dust book

Twenty-six chapters through a full-stack Rust framework: from the first route to requests, models, queues, real time, security, modules, the command line, and the long road to production.

Start reading

dust 0.1.4 · MIT · about 90 minutes

j / k to turn pages

Chapter 01

The application

An application is a directory, a configuration, and one binary. Before the first route, it helps to see the shape of the thing.

dust new storefront creates a complete project: the application's code in src/, configuration in config/, migrations in database/, templates in resources/views, served files in public/, and runtime files in storage/. There is no package manager step and no asset pipeline between you and a running server.

The code is ordinary Rust modules. A handler is a function, a model is a struct, and the application's configuration is a function that returns a configured builder. Nothing is generated at runtime and nothing is hidden in a global registry you cannot read.

A new project

In plain words

An application is a folder with a fixed shape. Once you know where things live, you always know where to look.

dust new writes the folders below and refuses to overwrite an existing directory. It also writes .env with a generated APP_KEY and a SQLite database URL, copies the io/ui assets, and puts the framework's guides in storage/docs.

storefront/
src/          routes, handlers, models, services
config/       TOML documents for the application
database/     migrations and seeders
modules/      features with their own boundary
public/       files served as-is, including io/ui
resources/    views and other compiled assets
storage/      logs, caches, uploads, and the guides

The split is deliberate. src/ is the application you write. modules/ is where a feature moves when it deserves its own routes, tables, and views. storage/ is the only folder you expect to grow at runtime, so deployments can replace everything else.

One binary

The application compiles to a single binary. Views, guides, and the io/ui assets are already in the project; there is no Node.js step between you and cargo run.

Configuration is Rust

In plain words

There is no magic configuration file to learn: src/app.rs is Rust code that builds the application, and every line says what it adds.

The builder collects migrations, services, middleware, and routes. Each method returns the builder, so the chain reads from top to bottom: start an application, add migrations, add services, mount routes.

src/app.rs
use dust::foundation::ApplicationBuilder;
use dust::prelude::*;

pub fn configure() -> ApplicationBuilder {
    Application::configure()
        .with_migrations(dust::db::migrations!("database/migrations"))
        .with_services(crate::modules::register)
        .with_routing(|routing, _| {
            routing.web(crate::routes::web::routes);
        })
}

main stays tiny: configure the application, then run it. The same configuration serves requests, console commands, queue workers, and the cron daemon, so a job sees the same services and the same database as a request.

src/main.rs
fn main() -> ExitCode {
    app::configure().run()
}

Values that change between environments, such as the database URL or the mail transport, live in .env and in the TOML files under config/. The code that reads them stays the same; only the environment changes.

Services and middleware

In plain words

A service is a shared object a handler asks for. Middleware is a layer every request passes through. Both are registered once, in the builder.

Services are values the container owns: a payment client, a report generator, a mail transport. A handler asks for one with Inject<T>, and the same instance is reused. with_services registers a closure that has access to the application and its configuration.

Middleware wraps requests. with_middleware configures the global stack, such as trusting a load balancer's proxy headers. Route middleware is attached where it belongs, which the routing chapter covers in detail.

src/app.rs
Application::configure()
    .with_middleware(|middleware, _| {
        middleware.trust_proxies(["127.0.0.1", "::1"]);
    })
    .with_services(|app| {
        app.singleton(async |app| {
            let key = &app.config().section::<StripeConfig>().key;

            Ok(Stripe::new(key))
        });
    })

The order matters. Global middleware runs before routing; route middleware runs after a route matches. A service is created the first time it is resolved, so an expensive client does not start until a handler needs it.

Modules and the console

In plain words

A module is a feature with its own boundary. The console is how you create, run, inspect, and repair the application.

A module lives in modules/ and can bring routes, migrations, views, and services. It compiles into the application — no extra crate, no extra build — but you can disable it without deleting its code. A blog, a shop, or an admin panel is a module; a single handler is not.

console
$ dust module:make blog
$ dust module:list --enabled
$ dust status

The console also runs migrations, queue workers, schedules, and the local relay. dust status reads the live services and reports the database, queue, cache, cron, relay, and frontend versions. The CLI chapter covers every command.

Read the guides on the server

dust docs:install writes AGENTS.md and the version-matched guides into storage/docs. They describe the exact version in Cargo.lock.

Chapter 02

Routing

A route is a promise: this URL, this handler, these parameters. dust keeps the promise in one place and checks the types.

A request arrives with a method and a URI. Routing is the part that decides which function should answer it. The decision lives in a route file, not in the handler, so you can read the application's URL map in one sitting.

This chapter starts with one route and grows the map step by step: parameters, constraints, models, middleware, groups, domains, links, and resources. Every feature is shown with the exact code you would add.

Simple routes

In plain words

A route says: when someone asks for this URL with this method, run this code. The simplest route pairs a path with a small function.

Routes live in src/routes/web.rs and src/routes/api.rs. A route file is a function that receives the router; every line registers one method on one path. The shortest route uses a closure:

src/routes/web.rs
use dust::prelude::*;

pub fn routes(route: &mut Router) {
    route.get("/greeting", async || "Hello World");
}

Closures are fine for a page or two. As the application grows, they make the route file a pile of page logic. The usual pattern is one handler per page, in its own module under src/http, so the route file stays a short list of URLs:

src/routes/web.rs
use crate::http::handlers::posts;

pub fn routes(route: &mut Router) {
    route.get("/", home::index);
    route.get("/posts", posts::index);
    route.get("/posts/{post}", posts::show);
    route.post("/posts", posts::store);
}

The router has a method for each HTTP verb: get, post, put, patch, delete, and options. A handler is an async function; its arguments are things the request provides, and its return value becomes the response.

Read it out loud

“A GET to /posts runs posts::index.” If a route is hard to say that way, it is probably doing too much.

Route parameters

In plain words

A parameter is a hole in the URL. The hole has a name, the handler asks for its value, and dust converts it to the Rust type you asked for.

Write a hole with braces. The handler receives it with Params<T>, and a value that does not parse into T is a 404 before the handler runs. A handler never has to check whether the ID is a number.

src/http/posts.rs
pub async fn show(Params(id): Params<u64>) -> dust::Result<View> {
    let post = Post::find(id).await?.or_abort(404)?;

    Ok(view("posts.show", data! { post }))
}

Several parameters arrive as a tuple, in the order the URI names them. When the parameters have different meanings, a struct keeps them named and prevents a mix-up:

src/http/archive.rs
#[derive(Deserialize)]
pub struct ArchiveParams {
    pub year: u16,
    pub month: u8,
}

pub async fn show(Params(params): Params<ArchiveParams>) -> String {
    format!("Archive for {}/{}", params.year, params.month)
}

Add ? to make a segment optional; optional parameters must come last. A wildcard, written {*path}, captures everything that follows, including slashes.

src/routes/web.rs
route.get("/archive/{year?}/{month?}", archive::show);
route.get("/files/{*path}", files::show);
The type is the check

Params<u64> means “this segment must be a number.” A request for /posts/hello never reaches the handler; it is a 404.

Constraints and models

In plain words

You can narrow a parameter with a type, an enum, or a model. The check happens before your code, so the handler only sees valid values.

The simplest constraint is the Rust type. A u16 accepts numbers that fit a u16; a Date accepts a date; an enum accepts only its variants. This handler on /categories/{category} accepts songs and rejects podcasts with a 404:

src/http/categories.rs
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Category {
    Movies,
    Songs,
    Paintings,
}

pub async fn show(Params(category): Params<Category>) -> &'static str {
    match category {
        Category::Movies => "Movies",
        Category::Songs => "Songs",
        Category::Paintings => "Paintings",
    }
}

Models in the URL

When a parameter holds a model's key, take the model itself as a handler argument. dust loads it before the handler runs and returns a 404 if no row matches. The handler gets a real Post, not an ID it must look up again.

src/http/posts.rs
pub async fn show(post: Post) -> String {
    post.title
}

To look a model up by another column, such as a slug, name the column after a colon: /blog/{post:slug}. Outside a handler, ask the request for the model with request.model("post").await?.

One query, not two

Model binding is not a shortcut around the database; it is the lookup you would have written, moved to the edge of the request where it belongs.

Middleware

In plain words

Middleware is a layer around a request. It can check, change, or reject the request before the handler sees it.

Attach middleware to one route with .middleware. Inside a group, the route's own middleware runs after the group's, so the group can establish a rule and the route can add another.

src/routes/web.rs
use dust::auth::{Authenticate, RequireVerifiedEmail};

route.prefix("/admin").middleware(Authenticate).group(|route| {
    route.get("/", admin::dashboard);
    route.get("/billing", admin::billing).middleware(RequireVerifiedEmail);
});

Sometimes one route in a group should skip one of the group's rules. Call without_middleware on that route. A status page under /admin may be public even though the rest of the group requires a login:

src/routes/web.rs
route.prefix("/admin").middleware(Authenticate).group(|route| {
    route.get("/status", admin::status).without_middleware::<Authenticate>();
});

Middleware may take arguments too. A route middleware that needs the session takes Session; one that needs the current tenant takes the request. The middleware guide lists the ones that ship with the framework and how to write your own.

Order is visible

Global middleware runs before routing, then the group's middleware, then the route's, then the handler. When a rule seems to be skipped, read that order.

Groups and prefixes

In plain words

A group lets many routes share a prefix and a stack of rules, so you write them once instead of on every route.

prefix adds a URI prefix; middleware adds a layer. Both are set before group, and the closure receives the router for the group. Groups nest: an inner prefix comes after the outer one, and both middleware stacks run.

src/routes/web.rs
route.prefix("/admin").group(|route| {
    route.get("/users", admin::users::index);

    route.prefix("/reports").group(|route| {
        route.get("/sales", admin::reports::sales);
    });
});

The inner route matches /admin/reports/sales. The prefix is only one shared attribute; a group can also carry head metadata, middleware, and a domain, which the next pages cover.

Use groups to express a boundary: everything under /admin needs a login, everything under /api is stateless, every tenant route carries a domain. A reader can see the rule at the group, not hunt for it on thirty routes.

Domain routing

In plain words

A domain route only matches a particular host. The host can even contain a parameter, which is how one application serves many tenants.

Use domain before group. A fixed host is the simple case; a host with a parameter captures that part of the hostname and passes it to the handler before the path parameters.

src/routes/web.rs
route.domain("admin.example.com").group(|route| {
    route.get("/dashboard", admin::dashboard);
});

route.domain("{account}.example.com").group(|route| {
    route.get("/users/{user}", users::show);
});

A request to acme.example.com/users/42 reaches the second group. The handler receives the account from the host and the user from the path, always in that order:

src/http/users.rs
pub async fn show(Params((account, user)): Params<(String, u64)>) -> String {
    format!("User {user} on the {account} account")
}

Routes with a domain take precedence over routes without one. Among domain routes, registration order matters: register the specific host before the pattern. In production the framework only answers hosts in APP_URL and its subdomains, so add any other domain to the trusted hosts list.

Multi-tenant, one binary

One deployment serves every account. The host decides the tenant; the path decides the resource; the handler receives both.

Resources, fallbacks, and forms

In plain words

Resources register the seven CRUD routes at once. A fallback catches URLs that match nothing, and form spoofing lets HTML send PUT and DELETE.

A module of handlers named after the actions can register the whole set. resource! wires the table below from the module name, so photos becomes /photos and {photo}.

src/routes/web.rs
use dust::routing::{Action, resource};

resource!(photos);
resource!(invoices::{index, show});
resource!(photos).except([Action::Create, Action::Edit]);

Without a fallback, an unmatched URL is a 404. route.fallback(pages::not_found) gives it a handler of your own. Static files are served from public/ before the fallback, so /logo.svg never reaches a handler.

HTML forms can only send GET and POST. Add a hidden _method field to reach a PUT, PATCH, or DELETE route; routing and middleware see the spoofed method as if the browser had sent it.

resources/views/posts/edit.html
<form action="/posts/1" method="POST">
    <input type="hidden" name="_method" value="DELETE">
    {{ csrf_field() }}
</form>
Put _method first

Place the hidden field before any file input, so the parser reads it before the upload.

Chapter 03

Requests

The request carries everything a handler needs: the path, the query, the body, the session, and who is asking.

A handler does not open a socket or parse a body by hand. It lists the things it needs as arguments, and the framework supplies them from the request. If an argument cannot be supplied, the request fails before the handler runs.

That is the whole idea of an extractor: the signature is the contract. A function that takes Params<u64> can only run for a request whose path contains a number.

Extractors

In plain words

An extractor is an argument that the framework fills from the request. Ask for what you need; do not fetch it yourself.

These are the extractors you will reach for most. Each one is a type in the handler's signature, and each one either produces a value or stops the request with the right status.

  • Params<T>: route parameters, typed.
  • Query<T>: the query string, parsed into a #[dust::query] struct.
  • Valid<T>: the body, validated into a #[dust::input] struct.
  • ValidRequest<T>: the validated input and the request together.
  • Request: the raw request, with headers, IP, session, and user.
  • Session: the session, on routes that start one.
  • Authenticated<User>: the logged-in user, or a redirect to login.
  • Inject<T>: a service from the container.
src/http/posts.rs
pub async fn index(
    post: Post,
    Params(sort): Params<String>,
    Inject(reports): Inject<Reports>,
) -> dust::Result<View> {
    // post is loaded, sort is typed, reports is the shared service
    // ...
}

Reading the body consumes it. A handler cannot take both Valid<T> and Request; use ValidRequest<T> when you need both, which the body page shows.

Fail early

A bad parameter, a missing required field, or a guest on a protected route fails before your code. The handler stays focused on the happy path.

Query strings

In plain words

Filters, pages, and sorts arrive after the question mark. Describe them as a struct, and dust parses text into numbers, dates, and enums.

Mark a struct with #[dust::query] and take Query<T>. Fields with a default are lenient: a missing or malformed optional filter falls back to None or its default instead of breaking the page.

src/http/products.rs
#[dust::query]
pub struct ProductFilters {
    pub q: Option<String>,
    #[default = 1]
    pub page: u32,
    pub status: Option<Status>,
}

pub async fn index(Query(filters): Query<ProductFilters>) -> dust::Result<View> {
    let products = Product::query()
        .paginate(15)
        .page(filters.page)
        .await?;

    Ok(view("products.index", data! { products, filters }))
}

The query extractor reads only the query string; it ignores any body. A field without a fallback is required and fails with a 400 when missing or invalid. That line is deliberate: a filter should never break a listing page, but a required parameter should not be silently invented.

Validation still applies

Rules such as #[validate(min_value(1))] work on query structs too, and a failing optional value falls back instead of failing the request.

The body

In plain words

The body is the data the user submitted. Validation turns it into a struct; the handler receives it only if every rule passed.

A handler that stores a form takes Valid<T> as its last argument. The input struct declares the fields and the rules; the extractor runs them and hands over the value.

src/http/posts.rs
pub async fn store(Valid(form): Valid<StorePost>) -> dust::Result<Redirect> {
    let post = create!(Post { ..form }).await?;

    Ok(redirect!(show, post.id))
}

Sometimes the handler needs the request as well, for example to record the client's IP with the post. ValidRequest<T> gives you both: into_parts returns the input and the request.

src/http/posts.rs
pub async fn store(input: ValidRequest<StorePost>) -> dust::Result<Redirect> {
    let (form, request) = input.into_parts();

    let post = create!(Post {
        ip_address: request.ip().to_string(),
        ..form
    })
    .await?;

    Ok(redirect!(show, post.id))
}

File uploads arrive with the same form. The input struct declares a file field and its rules; the handler receives the stored file or its metadata, depending on the field type. The validation guide covers the file rules.

Last argument

Reading the body consumes the request, so a body extractor must be the handler's last argument. The compiler and the framework agree on this.

Headers, session, and user

In plain words

Not everything is in the body. The request also knows the headers, the client, the session, and who is logged in.

Request is the escape hatch. It reads a header, the bearer token, the client IP, the full URL, and the content negotiation helpers. Each method returns an Option or a plain value, so the handler decides what a missing header means.

src/http/locale.rs
pub async fn locale(request: Request) -> String {
    let language = request.header("accept-language").unwrap_or("en");
    let client = request.ip();

    format!("{language} from {client}")
}

The session is a typed key-value store attached by the web middleware group. Take Session to read and write it; take Authenticated<User> when a page requires a logged-in user. A guest is redirected to the login page, or gets a 401 for a JSON request.

src/http/dashboard.rs
pub async fn show(user: Authenticated<User>, session: Session) -> View {
    session.put("last_page", "/dashboard");

    view("dashboard", data! { user })
}
API routes have no session

The web group starts a session and adds CSRF. The API group is stateless. Taking Session on an API route is a bug, not a convenience.

Chapter 04

Validation

Validation is a type. Describe the input once, attach the rules, and the handler only sees data that passed.

A form is a promise from the browser: these are the fields, and this is what they mean. Validation is where the application decides whether to believe it. In dust, that decision is written on a struct, next to the fields it protects.

The payoff is a handler that never checks whether a title is empty again. If the request reaches the handler, the title exists, fits the limit, and is unique.

Input structs

In plain words

An input struct says which fields a request may write and what each field must look like. The handler receives the struct, not a bag of strings.

#[dust::input] derives the decoding and the validation. fills = Post also makes it a fill struct, so the handler can copy it into a model without repeating the column list. The rules sit on each field.

src/http/posts.rs
#[dust::input(fills = Post)]
#[validate(anyone)]
pub struct StorePost {
    #[validate(required, max_length(255), unique(Post::title))]
    pub title: String,
    #[validate(required)]
    pub body: String,
}

The handler takes Valid<StorePost> as its last argument. If the rules fail, the handler never runs. A fill struct also limits the columns a request may write: a submitted field that the struct does not declare is ignored, so a user cannot add is_admin=1 to the form.

src/http/posts.rs
use dust::model::create;

pub async fn store(Valid(form): Valid<StorePost>) -> dust::Result<Redirect> {
    let post = create!(Post { ..form }).await?;

    Ok(redirect!(show, post.id))
}
The struct is the allow-list

If a column is not in the input struct, a request cannot write it. That is the simplest security rule in the book.

The rule set

In plain words

Rules are named checks. They cover text, numbers, dates, formats, and the database, and they read like the sentence you would say to a user.

Rules are written as arguments to #[validate(...)]. They run in the order you write them, and the first failure on a field stops that field's remaining rules unless you configure otherwise.

src/http/events.rs
#[dust::input]
#[validate(authenticated)]
pub struct StoreEvent {
    #[validate(required, max_length(120))]
    pub name: String,
    #[validate(required, email)]
    pub contact: String,
    #[validate(required, min_value(1))]
    pub seats: u32,
    #[validate(required, date)]
    pub starts_on: Date,
    #[validate(exists(venues::id))]
    pub venue_id: i64,
}

The rule families are text and choices (required, max_length, in), numbers (min_value, max_value), dates (date, after), formats (email, url, uuid), presence (accepted, confirmed), database records (unique, exists), passwords, and files.

A rule that names a column, such as unique(Post::title), asks the database. That is the right place for the check: the database is the only thing that can answer it correctly under concurrency.

Read the rule guide

The validation guide lists every rule with its exact arguments. This page is the map; the guide is the dictionary.

Optional and partial input

In plain words

An empty field and a missing field are different. A PATCH must know which one the user meant.

An Option<T> field may be empty; the default middleware turns an empty text input into null, which arrives as None. That is right for a field the user may clear, such as a bio or a publish date.

For a partial update, a missing field means “keep the current value” and a null means “clear it”. Neither Option nor String can express that difference, so use Sometimes<T>.

src/http/profile.rs
#[dust::input]
#[validate(authenticated)]
pub struct EditProfile {
    #[validate(required, max_length(255))]
    pub name: Sometimes<String>,
    #[validate(max_length(1000))]
    pub bio: Sometimes<Option<String>>,
}

Sometimes::Missing skips every rule, including required. Sometimes::Present runs the rules as usual. The handler matches on the value to decide whether to update the column.

Forms send everything

An HTML form sends every field, so Option is often enough. Sometimes matters for JSON PATCH requests, where an absent key is a real signal.

Authorization and errors

In plain words

The same struct says who may submit it. When a rule fails, the user gets the form back with the errors; an API client gets JSON.

Every validated type names who may submit it. anyone is for a contact form; authenticated is for a logged-in user; an authorize function is for everything else. A type without one does not compile.

src/http/teams.rs
async fn authorize(request: &Request) -> dust::Result<bool> {
    let admin = request
        .user::<User>()
        .await?
        .is_some_and(|user| user.is_admin);

    if !admin {
        dust::abort!(403, "Only team admins can rename a team.");
    }

    Ok(true)
}

An HTML form that fails goes back to the page with the errors and the old input. A JSON request gets a 422 with the failing fields. Tests can assert both with assert_invalid, which the testing chapter covers.

Authorization runs before validation. A rejected request never runs the rules, and a guest never learns whether their payload would have been valid.

Two answers, one type

The same struct serves the form and the API. Only the response format changes; the rules and the authorization stay in one place.

Chapter 05

Responses

Handlers return values, not plumbing. dust turns strings, JSON, views, redirects, files, and streams into responses.

The end of a handler is a value. That value already knows how to become an HTTP response: a string is text, Json is JSON, View is HTML, Redirect is a 302. You spend your attention on the value, not on status lines and headers.

When you do need the details, they are small additions: a tuple for a status code, a method for a header, a cookie on a redirect.

Values and status

In plain words

Return the thing the client should receive. The framework fills in the status, the content type, and the body.

These four cover most pages. A string is plain text; Json serializes a value; View renders a template; Redirect sends the browser elsewhere. A handler may return any of them, or a Result of one.

src/http/posts.rs
pub async fn health() -> &'static str {
    "ok"
}

pub async fn show(Params(id): Params<u64>) -> dust::Result<Json<Post>> {
    Ok(Json(Post::find_or_fail(id).await?))
}

pub async fn page(Params(id): Params<u64>) -> dust::Result<View> {
    let post = Post::find_or_fail(id).await?;

    Ok(view("posts.show", data! { post }))
}

A status code is a tuple: the code first, the body second. For a code you already have as a constant, that is the whole ceremony.

src/http/exports.rs
pub async fn store() -> (StatusCode, &'static str) {
    (StatusCode::ACCEPTED, "Your export is being prepared.")
}

Headers and cookies chain onto the value. A JSON response can carry a cache header; a redirect can set a preference cookie. The chain still returns the same response type.

One value, one response

If you can describe the result as a value, return it. Reach for a builder only when the response is genuinely unusual.

Redirects

In plain words

After a form is saved, send the browser to the page that shows the result. A redirect is how a POST ends cleanly.

redirect! builds the URL from a handler and returns the redirect. Redirect::to takes a path or a full URL; Redirect::back returns to the previous page. All of them may carry flashed data, a cookie, or both.

src/http/posts.rs
pub async fn store(Valid(form): Valid<StorePost>) -> dust::Result<Redirect> {
    let post = create!(Post { ..form }).await?;

    Ok(redirect!(show, post.id))
}

pub async fn update() -> Redirect {
    Redirect::back().with("status", "Profile updated!")
}

The flashed value lives for exactly one request, which makes it a good fit for a success banner. A view reads it from the session on the next page and the value disappears.

When a guest is sent to login, the authentication middleware remembers the page they wanted. Redirect::intended sends them there after login, with a fallback for the case where there was no intended page.

Post, redirect, get

A redirect after a POST stops the browser from resubmitting the form when the user refreshes. It is not a style preference; it is the pattern.

Files, streams, and cookies

In plain words

Not every response is a page. A report is a download, a progress bar is a stream, and a theme choice is a cookie.

File::download sends a file as an attachment and sets the content type from its extension; File::new displays it inline. Both support conditional and range requests, so a browser can cache a file and resume an interrupted download.

src/http/reports.rs
pub async fn download() -> dust::Result<File> {
    Ok(File::download("storage/reports/q3.pdf")
        .name("Q3 Report.pdf"))
}

An EventStream sends server-sent events as they happen: job progress, a live feed, a notification. Pass an async closure, send values with sender.send, and the browser receives them over one long response. Streamed does the same for plain chunks.

src/http/exports.rs
use dust::http::sse::EventStream;

pub async fn progress() -> EventStream {
    EventStream::channel(async |sender| {
        for step in ["Building", "Migrating", "Done"] {
            sender.send(step).await?;
        }

        Ok(())
    })
}

Cookies ride on any response. with_cookie sets one, without_cookie removes one, and both accept the name and value you would see in the browser. A redirect is the usual place to set a preference the next page will read.

src/http/theme.rs
Redirect::back().with_cookie(("theme", "dark"))
Make session changes before streaming

The session is saved when the handler returns, before the stream starts. Change it in the handler, not inside the producer closure.

Chapter 06

Views

A view is HTML with holes for your data. MiniJinja fills the holes, escapes the values, and sends the page.

Templates and data

In plain words

A template is an HTML file with named holes. Your handler fills the holes with values, and the engine writes the finished page.

The frontend is server-rendered: the handler returns a view, the engine writes the HTML, and the browser receives a complete page. Templates live under resources/views. A file at resources/views/posts/show.html is named posts.show: the path inside that folder, with dots for directories and no extension. The handler passes the name to view, and the data through data!. A page with no data passes ().

data! { post } passes a local variable under its own name. data! { users, title => "Users" } adds a second name. Any struct that derives Serialize works too, and each field becomes a variable; that is the better choice when several handlers render the same page, because the compiler checks that every field is present.

src/http/posts.rs
pub async fn show(Params(id): Params<u64>) -> dust::Result<View> {
    let post = Post::find(id).await?.or_abort(404)?;

    Ok(view("posts.show", data! { post }))
}

The template reads the field directly: <h1>{{ post.title }}</h1>. Every {{ ... }} is HTML-escaped, so a title containing <script> appears as text, not as a script. None prints nothing, booleans print true or false, and a list prints in a debug form such as ["a", "b"]; join it for readers. Escaping is the default because most values come from users.

Missing data is an error, not a blank. Referencing or looping over a variable the handler did not pass fails the render with a 500; in debug mode the error page names the template file and line. Guard optional values with {% if user is defined %}, or give a fallback with {{ title|default(app_name) }}. app_name and app_url are always available.

Gotcha

A missing variable is a 500, not an empty string. If a value is optional, guard it with is defined or give it a default. Remember that is defined still passes for None, so check is not none too when the field may be null.

Layouts, blocks, and includes

In plain words

A layout holds the parts every page repeats. A child page fills only the holes it cares about, and an include drops a smaller piece into either one.

A layout marks replaceable sections with block. A page starts with {% extends "layouts.app" %} and overrides the blocks it needs with {% block content %}...{% endblock %}. Any block the page doesn't override keeps the layout's default content. To keep that content and add to it, call {{ super() }} inside the child block.

resources/views/layouts/app.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>{% block title %}{{ app_name }}{% endblock %}</title>
    <link rel="stylesheet" href="/vendor/io-ui/paz.css">
</head>
<body>
    {% include "partials.nav" %}

    <main class="container">
        {% block content %}{% endblock %}
    </main>

    <script type="module" src="/vendor/io-ui/paz.js"></script>
</body>
</html>

An include embeds another template and inherits all variables from the current template. To pass extra values without leaking them into the rest of the page, wrap the include in with. Add ignore missing when the file is optional, as in {% include "partials.promo" ignore missing %}; without it, a missing file fails the render.

resources/views/users/index.html
{% extends "layouts.app" %}

{% block title %}Users{% endblock %}

{% block content %}
    {% with heading = "Users" %}
        {% include "partials.header" %}
    {% endwith %}

    <ul>
        {% for user in users %}
            <li>{{ user.name }}</li>
        {% endfor %}
    </ul>
{% endblock %}

Keep one layout for the shell and use includes for pieces such as navigation, flash messages, or a footer. A layout may extend another layout, but a long inheritance chain hides where the markup actually comes from. If a section renders empty, compare the block names in the layout and the child first; a misspelled block is simply never overridden.

Gotcha

Block names must match exactly. A child that writes {% block contents %} silently leaves the layout's content block untouched, so the page looks like the child was ignored.

Components and fragments

In plain words

A macro is a reusable piece of markup with parameters. A fragment renders one named block by itself, which is what a partial page update needs.

Define small UI pieces as macros in a shared template. A macro accepts positional or keyword arguments, and an argument with a default may be omitted. Import the file under a short namespace, then call the macro like a function. A call block passes inner markup to the macro, and the macro renders it where {{ caller() }} appears.

resources/views/components.html
{% macro button(label, type="button", variant="primary") %}
    <button type="{{ type }}" class="button button-{{ variant }}">{{ label }}</button>
{% endmacro %}

{% macro card(title) %}
    <section class="card">
        <h2>{{ title }}</h2>
        {{ caller() }}
    </section>
{% endmacro %}

Elsewhere, {% import "components" as ui %} makes {{ ui.button("Save", type="submit") }} work. For a card with a body, write {% call ui.card("Orders") %}, put the markup inside, and close with {% endcall %}. To import names without a namespace, use {% from "components" import button, card %}. When a component needs arbitrary attributes, accept an attrs={} map and render it with attributes(attrs).merge(...).

A fragment is a block you can request alone. Wrap a section in {% block results %}...{% endblock %}, then return view("users.index", data! { users }).fragment("results"). The response contains only that block, with the template's imports and variables still in scope. Use fragment_if(partial, "results") when one handler serves both the full page and the partial update.

Split by purpose: a layout is the page shell, an include is static shared markup, a macro is a widget with parameters, and a fragment is a section a script swaps in place. If a block is only ever rendered as part of the page, it does not need to become a fragment.

Gotcha

A fragment renders the named block alone, without the layout around it. That is the point for a search-results update, but it means the response is not a full HTML document; do not return it for a normal page load.

Filters and control flow

In plain words

Conditions decide which markup exists, loops repeat it, and filters reshape the values that go inside.

Use if, elif, and else for branches, and for for lists. A for may have an else branch for the empty case, and a loop can be filtered inline with if. Inside the loop, loop.index starts at 1, loop.first and loop.last mark the ends, and loop.cycle("odd", "even") alternates values. Tests such as defined, odd, and divisibleby(3) read naturally in a condition. For a value chosen inline, {{ "Active" if user.active else "Inactive" }} avoids a whole block.

Filters chain left to right with |. length counts, join(", ") turns a list into text, upper and title change case, and round(2) formats a number. Dates have their own filters: created_at|date renders October 5, 2026, created_at|date("%b %-d, %H:%M") renders Oct 5, 14:30, and created_at|date(tz="America/Chicago") chooses a timezone. for_humans gives 3 minutes ago; compact_for_humans gives 3m ago.

resources/views/orders/index.html
{% if orders %}
    <ul>
    {% for order in orders %}
        <li>
            {{ order.number }} · {{ order.total|round(2) }}
            <time>{{ order.created_at|date("%b %-d") }}</time>
        </li>
    {% endfor %}
    </ul>
{% else %}
    <p>No orders yet.</p>
{% endif %}

Escaping happens when the value is output, so transforming a value with a filter does not make untrusted HTML safe. The safe filter turns escaping off, and Html::raw with with_html marks markup as trusted before it reaches the template. Use either only on HTML you built or sanitized, never on a value the user typed. For data inside a script or a quoted attribute, use the js filter, which encodes quotes and angle brackets for that context.

Gotcha

safe is an escape hatch, not a formatter. Applying it to a user-authored field is a cross-site scripting bug; the same is true of tojson inside a double-quoted attribute, where a quote in the data can break out.

io/ui and assets

In plain words

io/ui is the component library that ships with the application: one stylesheet, one module, and a small boot script, with no package manager at runtime.

A new application writes io/ui to public/vendor/io-ui. The default layout loads preferences-boot.js in the head, then paz.css, and finally paz.js as a module. The boot script is a classic script and must run before the stylesheet paints, because it applies the saved text size, font, accent, and contrast. Loading it late causes a visible reflow for anyone who chose larger text.

resources/views/layouts/app.html
<script src="/vendor/io-ui/preferences-boot.js"></script>
<link rel="stylesheet" href="/vendor/io-ui/paz.css">
<script type="module" src="/vendor/io-ui/paz.js"></script>

Use io/ui classes on semantic elements: btn btn-primary on a <button>, card on an <article>, table on a real table, badge badge-success on a status span. Behavior comes from data attributes such as data-theme-toggle and data-dropdown="#account-menu". Because paz.js watches the document, markup added by a fragment or your own script keeps working without re-initialization.

Files in public/ are served at their real paths, so your own CSS goes at /css/app.css with no manifest. An asset shipped by a package uses vendor_asset, which adds the package namespace and a content hash, so browsers may cache it indefinitely. Refresh io/ui with dust ui:update; --check only prints the installed and latest versions, and --force downloads even when they match. The command writes version.json beside the assets.

Gotcha

Do not edit public/vendor/io-ui by hand. ui:update replaces those files, and your changes disappear on the next update; put your own rules in a stylesheet loaded after paz.css.

Forms, CSRF, and old input

In plain words

A form post carries a token that proves it came from your page. When validation fails, the redirect brings back the errors and what the user typed.

Every form that posts to a route in the web group needs {{ csrf_field() }} inside it. The helper writes the hidden _token input with the session's current token. A GET form does not change state and needs no token. Always give the form an explicit action and method: a form without an action posts to the current URL, which is rarely what you want after a validation redirect. A missing or stale token produces 419 Page Expired.

HTML forms send only GET and POST. For a PUT, PATCH, or DELETE route, post normally and add <input type="hidden" name="_method" value="DELETE">. Put that field before any file input, because the framework reads it while parsing the form. The spoofed method is what routing and middleware see.

After a failed validation, the view receives error("field") for the first message and old("field", default) for the submitted value. Use {% if error("email") %} to show a message, and put old(...) in the input's value. The errors map holds every message per field, so {% for message in errors.email %} lists them all. On a page with several forms, pass the form name to error("email", form="login") and read form_errors.login.

resources/views/posts/edit.html
<form method="POST" action="{{ route("posts::update", post) }}" enctype="multipart/form-data">
    {{ csrf_field() }}
    <input type="hidden" name="_method" value="PATCH">

    <label for="title">Title</label>
    <input id="title" name="title" value="{{ old("title", post.title) }}">
    {% if error("title") %}
        <p class="error">{{ error("title") }}</p>
    {% endif %}

    <input type="file" name="cover">
    <button type="submit">Save</button>
</form>

A form with uploads needs enctype="multipart/form-data"; without it the browser sends only the file's name. The handler receives an Option<UploadedFile> field, or a Vec<UploadedFile> for a multiple input. Old input never includes passwords or uploaded files, so those fields come back empty and the user chooses again.

Gotcha

Two mistakes account for most broken upload forms: a missing enctype, and _method placed after the file input. The first drops the file, the second leaves the request as a POST and misses the PATCH route.

Chapter 07

Database

One schema API and one query API for SQLite, PostgreSQL, and MySQL. The driver changes; the application doesn't.

A database is two things at once: a history of schema changes and a set of typed queries. dust gives each a home. Migrations describe the schema in Rust; models and the query builder read and write rows in Rust.

The point is not to hide SQL. It is to make the common path typed and portable, and to leave raw SQL available where it says what you mean.

Connections and drivers

In plain words

A connection is where the queries go. Choose a driver with a Cargo feature and a URL with an environment variable.

Enable one driver feature on dust-framework: database-sqlite, database-postgres, or database-mysql. The application reads DATABASE_URL and opens a pool; the default pool size is ten connections, tunable with DB_MAX_CONNECTIONS.

A named connection lets one part of the application read a replica or a separate database. Look it up by name and pass it to the query:

src/http/reports.rs
let reporting = db::connection("reporting")?;

let rows = db::using_connection(reporting, async {
    db::table("invoices").get::<Invoice>().await
})
.await?;

Writes and read replicas can use different URLs: DB_WRITE_URL defaults to DATABASE_URL. Transactions always use the writer, because a read replica cannot commit one.

SQLite is a real choice

It serializes writes and keeps a single file. That is a feature for a small application, not a failure. Move to PostgreSQL when concurrent writers need it.

Migrations and schema

In plain words

A migration is a Rust function that changes the schema. It runs once, in order, and is tracked by its file name.

tx.schema().create("posts", |table| { ... }) defines a table. Columns, indexes, and foreign keys are methods on the blueprint. The migration runs inside a transaction when it accepts &mut AnyTransaction.

database/migrations/2026_01_01_000000_create_posts.rs
use dust::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> dust::Result<()> {
    tx.schema()
        .create("posts", |table| {
            table.id();
            table.foreign_id("user_id").constrained().cascade_on_delete();
            table.string("title");
            table.timestamp("published_at").nullable();
            table.timestamps();

            table.index(["user_id", "published_at"]);
        })
        .await
}

Migrations are forward-only. There is no down function and no rollback command; a schema change in production is a new migration. The file name is the migration's identity, so never rename one that has run.

database/migrations/2026_02_01_000000_add_slug_to_posts.rs
tx.schema()
    .alter("posts", |table| {
        table.string("slug").nullable();
    })
    .await
Data is a migration too

A backfill is a migration that runs queries. Keep it idempotent if it can commit in batches; the migrations guide shows the pattern.

Queries

In plain words

Start from a table or a model, chain filters and ordering, then run it with get, count, or paginate.

The query builder speaks in typed columns when it starts from a model, and in strings when it starts from a table. Both end with an awaited method that runs the SQL.

src/http/posts.rs
let posts = Post::query()
    .filter(Post::published_at.is_not_null() & Post::votes.gt(100))
    .order_by(Post::published_at.desc())
    .limit(10)
    .get()
    .await?;

let total = db::table("users").count().await?;

Conditions compose with & and |, and the column type checks the value: comparing a text column to a number is a compile error, not a runtime surprise. Joins, groups, and subqueries are builder methods too.

When SQL is clearer than the builder, db::query! binds values safely and returns typed rows. The macro interpolates values as parameters, so a user input never becomes SQL text.

src/http/reports.rs
let rows = db::query!(
    "SELECT status, COUNT(*) AS total FROM orders GROUP BY status"
)
.get::<StatusCount>()
.await?;
Typed beats clever

A query that reads like the table it touches is easier to review than a clever one-liner. The builder rewards the boring version.

Models and relations

In plain words

A model is a struct that maps to a table row. Its columns are fields; its relations are fields that point at other models.

#[model] derives the column metadata and the query helpers. Each field is a column; #[default] marks a column the database fills; a relationship field is not a column.

src/models/post.rs
use dust::model::{BelongsTo, model};

#[model]
pub struct Post {
    pub id: i64,
    pub user_id: i64,
    pub title: String,
    #[default]
    pub votes: i64,
    pub published_at: Option<Timestamp>,

    #[belongs_to]
    pub user: BelongsTo<User>,
}

A relation is loaded on demand or eagerly with with. Eager loading avoids the query-per-row problem: one query for the posts, one for their users, instead of one per post.

src/http/posts.rs
let posts = Post::query()
    .with(Post::user)
    .with(Post::comments.with(Comment::user))
    .get()
    .await?;

Route binding uses the model too: a handler that takes post: Post receives a loaded row, or a 404. To bind by a slug, write {post:slug} in the route.

Load what the page reads

Eager loading is not an optimization you add later; it is part of describing what the page needs.

Pagination and transactions

In plain words

Pagination turns a long list into pages. A transaction makes several writes succeed or fail together.

paginate(15) runs a count query and returns a paginator; page(n) selects the page. The paginator carries the items, the totals, and the navigation URLs, and it serializes for a JSON API.

src/http/posts.rs
let posts = Post::query()
    .order_by(Post::published_at.desc())
    .paginate(15)
    .page(page)
    .await?;

Ok(view("posts.index", data! { posts }))

When the UI only needs previous and next links, simple_paginate skips the count query. On a very large table, that is the difference between a page and a wait.

A transaction groups writes. db::transaction runs an async closure; it commits when the closure returns Ok and rolls back on error. Every query on the transaction handle participates.

src/http/transfers.rs
db::transaction(async |tx| {
    db::query!(tx, "UPDATE accounts SET balance = balance - {amount} WHERE id = {from}")
        .update()
        .await?;

    db::query!(tx, "UPDATE accounts SET balance = balance + {amount} WHERE id = {to}")
        .update()
        .await?;

    Ok(())
})
.await?
Keep write transactions short

SQLite serializes writers, and every database holds locks. Do the slow work outside the transaction and the writes inside it.

Chapter 08

Background

Some work should not wait for the response: a webhook, a receipt, a report at 08:00. dust gives each kind its own tool.

There are three different kinds of “later”, and mixing them up causes most of the bugs in background work. Work that must happen needs a queue. Work that can overlap a request needs a task. Work that happens on a clock needs a scheduler.

This chapter keeps them separate, then shows where they meet: a queued job can start a workflow, and a schedule can dispatch one. Scheduling, cron, and workflows have their own chapter; this one stays with the queue and the task.

Queues and connections

In plain words

A connection is the place where jobs are stored. A queue is a named list inside it. Your request leaves a note on the list; a separate program reads the note and does the work.

A queue is a to-do list that lives outside your application. The request writes down “process podcast 42” and returns to the visitor. A long-running worker process reads the note and does the work. If the web server crashes between the two, the note is still there when it comes back.

Two words do different jobs, and dust uses them precisely. A connection is the backend that stores jobs: your database, a Redis server, or an SQS queue. A queue is a named list inside that connection. One connection can hold many lists, such as high, default, and emails. Dispatch without naming either, and the job goes to the default connection and its default queue.

dust defaults to the database driver, which keeps jobs in a jobs table and permanently failed jobs in failed_jobs. Redis, SQS, and DUST Cloud are available behind a feature and an environment variable, but the job code does not change; only the place where the payload waits changes. New applications create the jobs and failed_jobs tables in their jobs migration, which contains only the macro:

database/migrations/0001_01_01_000002_create_jobs_table.rs
dust::queue::tables!();

Run dust migrate before the first dispatch. Then choose the queues a worker should drain, in priority order, with dust queue:work --queue=high,default.

Gotcha

Every driver delivers at least once. A worker may run a job again after a crash, a timeout, or a lost reservation, so write handle so that running it twice has the same effect as running it once.

Defining a job

In plain words

A job is a small struct that says what to do, plus a handle method that does it. You put it in a file; dust finds it.

A job is a struct that derives Queueable, paired with a #[job] impl containing an async handle method. You may place jobs in any module, such as src/jobs/. dust discovers them automatically, so there is nothing to register and no list to keep in sync.

handle consumes self and returns () or dust::Result<()>. Alongside self, it may accept services through Inject<T>, config sections through Section<T>, and the current &Attempt, in any order. Each job runs in a fresh application context, so config, resolve, URL generation, and logging all work, though there is no HTTP request or session. Context values present at dispatch time, such as the active tenant, travel with the job.

A job may also store models directly. dust serializes only each model's primary key at dispatch and reloads the row before handle runs, so the job always works with fresh data. If the row is gone, the worker deletes the job without running it, unless you add fail_when_missing_models.

src/jobs/process_podcast.rs
use dust::queue::{Queueable, job};

use crate::models::Podcast;

#[derive(Queueable)]
pub struct ProcessPodcast {
    pub podcast_id: i64,
}

#[job]
impl ProcessPodcast {
    async fn handle(self) -> dust::Result<()> {
        let podcast = Podcast::find_or_fail(self.podcast_id).await?;

        // Process the uploaded podcast...

        Ok(())
    }
}
Gotcha

A job is serialized until a worker picks it up, so carry plain data or models, never a database connection or an open file handle. If you rename or move the struct, give it #[job(name = "podcasts.process")] so jobs already on the queue still resolve.

Dispatching

In plain words

Dispatching means putting the note on the list. You choose where it goes and when it may start, then await. Until you await, nothing has happened.

Call dispatch on the struct and await it. Awaiting pushes the job onto the default connection and returns its JobId, which also identifies the job in queue:failed and in attempt.id(). You can dispatch from a route handler, a console command, a scheduled task, an event listener, or another job.

Before awaiting, choose the route: on_connection picks the backend, on_queue picks the list, and delay holds the job for a span or until a timestamp. on_group assigns an SQS FIFO message group, so jobs for one customer run one at a time in order. The calls chain in one expression:

src/http/podcasts.rs
ProcessPodcast { podcast }
    .dispatch()
    .on_connection("redis")
    .on_queue("podcasts")
    .delay(10.minutes())
    .await?;

Inside a database transaction, dispatch waits for the commit and is discarded on rollback, so no worker sees a row that is not there yet. dispatch_sync is the opposite: it runs the job immediately in this process and returns its error, which makes it useful in tests and for work that must not wait. To send many jobs at once, use queue::bulk; to run them one after another, queue::chain; to run them in parallel and be told when all finish, queue::batch, which returns a BatchId and can run then, catch, and finally callbacks.

Gotcha

dispatch() returns a pending value; the job exists only once you await it. And a delay is not universal: the sync connection ignores it, while an SQS FIFO queue refuses it, so send delayed jobs to a standard queue.

Retries and failures

In plain words

By default a job is tried once. You can give it more attempts, a pause between them, and a deadline. When every attempt is used up, it lands in failed_jobs for you to inspect.

Retries are job options, written on the #[job] attribute. tries sets the maximum number of attempts, including releases. backoff is the wait before each retry, either one duration or a list whose last entry repeats. timeout caps a single attempt at 60 seconds by default. retry_for replaces tries with a time window, and max_errors stops a job that keeps releasing itself.

While an attempt is retryable, the worker logs the error as a warning. Once the job fails permanently, the worker writes it to failed_jobs, runs the job's optional failed hook, and reports the error to your error handler. A timeout cancels the job at its next .await point, because a Rust future cannot be stopped anywhere else; keep CPU-heavy work out of handle.

src/jobs/process_podcast.rs
#[job(
    queue = "podcasts",
    tries = 3,
    backoff = [10.seconds(), 1.minutes()],
    timeout = 2.minutes(),
)]
impl ProcessPodcast {
    // ...
}

To see what failed, run dust queue:failed; the newest is first. dust queue:retry <id> puts one job back on its original connection and queue with a fresh attempt count, and dust queue:retry all retries every one. dust queue:forget <id> deletes a single record, while dust queue:flush --hours=48 deletes records older than 48 hours.

Gotcha

A release counts toward tries. A job that releases itself while waiting on a rate limit can exhaust its attempts while the real work has not failed once, so pair retry_for with max_errors instead of raising tries.

Running workers

In plain words

A worker is a program that stays running and asks the queue for the next job. One worker can handle several jobs at once; several workers can share the same queue.

Start one with dust queue:work. It runs until you stop it, printing each job's name without the leading app::, its outcome, and how long it took. That output makes the worker the first place to look when a job does not seem to run. Run your migrations first, because the worker needs the jobs and failed_jobs tables.

By default it processes the default queue on the default connection. Pass a connection name, or list queues in priority order with --queue=high,default. --concurrency=8 runs several jobs at once inside one process, which suits I/O-bound work; CPU-heavy work belongs in task::spawn_blocking so it does not stall the others. --max-jobs, --max-time, and --stop-when-empty let a worker exit on its own. However many workers you run, each job is claimed by only one of them.

In production, put the worker under a supervisor so it restarts when it exits. When it receives SIGTERM, it stops claiming new jobs and waits for the ones in flight:

/etc/systemd/system/app-worker.service
[Unit]
Description=Queue worker
After=network.target

[Service]
WorkingDirectory=/srv/app
ExecStart=/srv/app/bin/your-app queue:work --concurrency=4
Restart=always
KillSignal=SIGTERM
TimeoutStopSec=150

[Install]
WantedBy=multi-user.target

Set the stop timeout above twice your longest job's timeout, so a final attempt can still run its failed hook. On every deploy, run dust queue:restart: workers keep the binary they started with, and the signal asks them to finish the current job and exit. To stop one queue without stopping the worker, use dust queue:pause database:emails and resume it with dust queue:continue database:emails.

Gotcha

Deploying new job code is not enough. Existing workers keep executing the old binary until queue:restart or a supervisor restart replaces them, which is how a fixed job keeps failing after the fix shipped.

Tasks beside the request

In plain words

A task is work you start now, either next to other work or just after the response. It is fast and shares the request's context, but nothing retries it.

The dust::task module is for work that belongs to the current process, not to a queue. task::try_join! runs independent operations together and returns their results in order, so a dashboard waits for the slowest query instead of the sum of all of them. It short-circuits on the first error; task::join! is the version for operations that cannot fail, and task::select! returns whichever finishes first and cancels the rest.

task::background starts work immediately while the handler returns its response. The task carries the application context and tracing span, so config, the database, and logging keep working. During graceful shutdown the server waits for it, up to SERVER_SHUTDOWN_TIMEOUT. Errors are reported the way handler errors are, but the task is never retried.

task::timeout puts a deadline on one operation and returns a task::TimedOut error when it expires, which dust renders as 504 Gateway Timeout. task::map processes a collection with a concurrency limit and preserves the input order. task::spawn gives you a handle to collect later, and task::spawn_blocking moves synchronous or CPU-heavy code off the async thread.

src/http/dashboard.rs
let (users, orders) = task::try_join!(
    db::table("users").count(),
    db::table("orders").count(),
)?;

let rates = task::timeout(
    3.seconds(),
    client::get("https://rates.example.com/latest"),
)
.await??;

task::background(async move {
    client::post("https://example.com/webhooks/shipped")
        .ensure_successful()
        .await?;

    Ok(())
})?;
Gotcha

task::background is not a queue. It is not retried and it is lost if the process dies, so it suits a best-effort webhook, never a receipt or a charge. If the work must finish, survive a deploy, or be retried, dispatch a job instead.

Chapter 09

Real-time

An event can do two things at once: run a listener and reach a browser. Broadcasting is the second half.

Most pages answer when asked. A real-time page is told. The bridge is an event: the application already dispatches events for work it does, and a broadcast event also travels to every browser subscribed to a channel.

The pieces are small: a struct, a channel name, a Relay server, and Echo in the browser. None of them require a second application.

Events and broadcasting

In plain words

An event is a fact: “the order shipped.” Broadcasting sends that fact to browsers as well as to the application's own listeners.

#[derive(Event)] makes a struct dispatchable. The #[event(broadcast(...))] attribute adds channels. Listeners still run as usual, so one event can send the email and update the page.

src/events/order_shipped.rs
use dust::event::Event;

#[derive(Event)]
#[event(broadcast(private = "orders.{order_id}"))]
pub struct OrderShipped {
    pub order_id: i64,
    pub tracking_number: String,
}

Dispatch it from a handler or a job. Delivery goes through the queue, so the handler does not wait for the browser and a slow subscriber does not slow the response.

src/http/orders.rs
OrderShipped {
    order_id: 42,
    tracking_number: "TRACK-123".into(),
}
.dispatch()
.await?;
Broadcast the fact

Send the event, not the whole page. The browser decides how to show the new tracking number.

Channels and authorization

In plain words

A channel is an address. Public channels are open; private and presence channels ask your rules before anyone can listen.

The attribute chooses the visibility: public = "orders", private = "orders.{order_id}", or presence = "room.{room_id}". A private channel name is not a secret; it is a claim that your application checks.

Channel authorization is a callback that receives the request and the channel's parameters. It returns whether this user may listen. A customer may listen to their own order and not to someone else's; the rule is ordinary Rust.

src/routes/channels.rs
use dust::broadcast::Channels;

pub fn routes(channel: &mut Channels) {
    channel.private("orders.{order}", order);
}

async fn order(order: Order, user: Authenticated<User>) -> bool {
    order.user_id == user.id
}

Presence channels carry who is listening. They are useful for a room, a document, or a support conversation; the server tracks the members and tells everyone when the list changes.

Authorize before subscribe

The name is public; the permission is not. Check it in the channel callback, not in the browser.

Relay and Echo

In plain words

Relay is the WebSocket server on your machine. Echo is the browser client that subscribes to a channel and receives events.

Relay ships behind the relay feature. Start it beside the application, point BROADCAST_CONNECTION at relay, and set the app credentials in .env. The local server reads the same variables as the broadcast connection.

console
$ dust relay:start
$ dust serve

In the browser, Echo subscribes to the channel. The private channel is authorized with the session; the callback above decides whether the subscription succeeds.

resources/js/orders.js
Echo.private(`orders.${orderId}`)
    .listen("OrderShipped", (event) => {
        document.querySelector("#tracking").textContent = event.tracking_number;
    });

In production the same API talks to managed Relay. The application's code, the event, and the channel names stay the same; only the connection configuration changes.

Local, then managed

Relay exists so the real-time loop works on a laptop without an external service. Production swaps the server, not the code.

Chapter 10

Mail & notifications

Email is a view with an envelope. A mailable is the envelope; the view is the letter.

Transactional email has three parts: the data, the template, and the transport. dust names the first two with a mailable and leaves the third to configuration, so the same email can go through the log, Resend, or SES without changing the code that sends it.

Notifications go one step further: one notification can reach a user by mail, SMS, or Slack, and each channel decides how to render it. This chapter follows an email from its struct, through a mailer, to a provider, then applies the same shape to notifications.

Mailables and views

In plain words

A mailable is a struct that describes one kind of email. Its fields become the template's data, and its name becomes the template's name.

Write one struct for each kind of email, usually in src/mail.rs, and derive Mailable. OrderShipped renders resources/views/mail/order-shipped.html, named after the struct in kebab case, and the template reads each field by name, as {{ order_id }} or {{ url }}. Every field's type must implement Serialize, because the fields are the view's data. Views live in resources/views and usually extend dust::mail.message, which supplies the responsive layout, header, and footer.

The subject is an attribute. Without one, the framework turns the struct name into words, so OrderShipped becomes “Order Shipped”. A subject may interpolate fields with {field} placeholders, and view overrides the default template path. Compute values such as route URLs in a constructor, because the constructor runs where the request context is available.

src/mail.rs
use dust::mail::{Attachment, Mailable};

#[derive(Mailable)]
#[mail(subject = "Order #{order_id} has shipped")]
pub struct OrderShipped {
    pub order_id: i64,
    pub url: String,
    #[mail(attach)]
    pub invoice: Attachment,
}

By default the HTML view is the whole email: the framework also renders it with simplified component markup and converts the result into a plain-text body, so clients and spam filters get both formats. Pass text when you want a dedicated text template, or pass text alone for a text-only email. During the text render the mail_text variable is true, so a view can leave out images that make no sense as text.

Attachments are fields too. #[mail(attach)] attaches an Attachment without exposing it to the template. Build one with from_bytes, from_path, from_url, from_upload, or from_storage_disk, and override its filename or MIME type with .name(..) and .content_type(..). An email's attachments may total up to 25 MiB.

Gotcha

Subject placeholders name fields of the struct itself, not paths. {order_id} works; {order.id} does not. Format specs such as {total:.2} are allowed.

Sending and mailers

In plain words

Sending names a recipient and hands the mailable to a mailer. The code does not know whether the mailer writes to a log or calls a provider.

mail::to starts a message and names its recipients. send delivers it and waits for the provider, queue pushes it onto the queue, and send_background hands it to an in-process task. Most handlers should queue, so the response does not wait on Resend or SES and a transient failure is retried.

Recipients may be a &str, a String, an (email, name) pair, an Address, or a collection of any of them. Implement From<&User> for Address once, and mail::to(&user), &order.user, and Authenticated<User> all work; loaded relationships such as &team.members convert the same way. Add copies with cc and bcc.

A named mailer sends one message through a different transport: mail::mailer("ses").to(...). The sender comes from MAIL_FROM_ADDRESS and MAIL_FROM_NAME unless the message sets its own. If a mailable declares #[mail(to)], skip mail::to and call mail::queue(mailable) directly; the recipient then lives next to the data it belongs to.

src/http/orders.rs
mail::to(&order.user)
    .cc("sales@example.com")
    .queue(OrderShipped::new(order)?)
    .await?;

All three methods render and validate the email before returning, so a broken template or an invalid address fails at the call site. They also take ownership of the mailable: clone it first if you need the value afterwards.

Gotcha

send waits for the provider and does not retry. In a request, prefer queue; reserve send for a command or a job that already handles retries.

Transports

In plain words

A transport is the road an email takes out of your application. Configuration chooses the road; the mailable stays the same.

Each mailer is a name plus a transport. Out of the box you get log, resend, ses behind the ses feature, and failover. There is no bundled SMTP transport; applications and packages add one by implementing the Transport trait and registering the driver in src/app.rs.

log is the default, so a new application sends nothing until you choose a provider. Resend needs only RESEND_API_KEY. SES reads AWS_DEFAULT_REGION, the access key variables, and SES_CONFIGURATION_SET, falling back to the AWS SDK's own chain, such as an instance's IAM role. The ses mailer needs the Cargo feature enabled. Reading the configuration never contacts a provider; the first send does.

.env
MAIL_MAILER=resend
RESEND_API_KEY=re_123
MAIL_FROM_ADDRESS=orders@example.com
MAIL_FROM_NAME="Acme Orders"

failover tries resend, then ses, and logs a warning when a mailer fails before moving on. Select it with MAIL_MAILER=failover, or define another order with MailerConfig::failover(["ses", "resend"]). A custom transport is selected like any other mailer, by name.

You can also add a mailer for a second account, such as a marketing Resend key, in src/config/mail.rs. Start from Mail::from_env, call add_mailer, and send through it with mail::mailer("marketing"). A custom transport receives an email that is already rendered and validated, and returns a SentMessage.

Gotcha

Failover protects against an outage, not against duplicates. If a provider accepts an email and then times out, the next mailer sends it again. Resend sends an idempotency key; SES has none.

Delivery and failure

In plain words

queue turns a send into a job. The request returns, a worker delivers, and a failure can be retried without the user waiting.

queue renders the email now, encrypts it with the application key, and pushes a job. A worker delivers it with automatic retries, and the job survives a restart or a deploy. send waits for the provider and does not retry; send_background neither waits nor survives a restart. Only queue retries; send returns the error, and send_background reports it.

All three render and validate immediately, so a template error or an invalid address surfaces at the call site. When a queued email fails for good, the provider's error is recorded in failed_jobs; inspect it with queue:failed, fix the cause, and retry with queue:retry. A 4xx rejection other than 408, 409, or 429 fails at once, because repeating it would receive the same answer.

Before awaiting queue, you may delay the job and choose its connection and queue. Delays use the same ToSpan values as other jobs, and the defaults come from MAIL_QUEUE_CONNECTION and MAIL_QUEUE.

src/http/orders.rs
use dust::time::ToSpan;

mail::to(&order.user)
    .queue(OrderShipped::new(order)?)
    .delay(10.minutes())
    .on_connection("redis")
    .on_queue("mail")
    .await?;

During development the log mailer writes the sender, recipients, subject, and plain-text body at info, and the HTML body at debug. Read that output before you blame a provider; it is the exact email the other transports would receive.

Gotcha

A queued email's content is fixed when you queue it. A delayed email shows the order as it was then. If it must show current data, dispatch a job that loads the order and calls send.

Notifications

In plain words

A notification is one message with several possible channels. The notification decides what to say; each channel decides how to say it.

A notification is a struct holding the data its messages need, paired with an #[notification] impl. Define a mail, sms, or slack method for each channel it supports. Every method in one impl takes the same notifiable type, usually &User; to notify teams too, write a second impl whose methods take &Team.

A notifiable is a type that can receive, such as User or Team. Implement ReceivesMail, ReceivesSms, or ReceivesSlack to return its address, phone number, or Slack route. Returning None skips that channel for that notifiable without an error, so a user without a phone still gets the email. A notification that builds an SMS must be sent to a type that implements ReceivesSms; otherwise it does not compile.

src/notifications/invoice_paid.rs
use dust::mail::Mailable;
use dust::notification;

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.", self.invoice.id)
    }
}

notification::to(&invoice.user).queue(...) dispatches one job per notifiable and channel. Three users and two channels make six jobs, and a failed text message retries only itself. send delivers immediately and waits for each provider instead.

A channels method can add or remove channels per recipient, which is how a user opts out of SMS. It runs once per notifiable before any message is built, and it cannot wait or fail, so it cannot query the database. Package channels join the same list through a #[via(Discord)] method.

Gotcha

Channel methods are synchronous, so load related models before you send. If a method can fail, such as when building a route URL, return dust::Result; the error aborts the send before any message goes out.

Mail, SMS and Slack messages

In plain words

Each channel has its own message type. Mail builds a mailable, SMS builds text, and Slack builds blocks with buttons and fields.

The mail method returns any Mailable: a derived struct, a manual implementation, or a Message. The notifiable's email address is attached automatically, so the mailable does not need to. Views, subjects, and attachments work exactly as they do for mail you send yourself. Slack messages usually go to a team's channel rather than one person, so the slack impl often takes &Team.

The sms method returns a String or &str, which goes out from SMS_FROM. Return sms::Message to choose another sender with .from(...). Messages are not truncated: long bodies are split into segments and billed per segment, so keep alerts short.

The slack method returns a slack::Message with fallback text and blocks. A Section holds text and up to ten fields; actions holds buttons and menus. Button::link opens a URL, while Button::action triggers a Slack action in your application and requires the interactions endpoint. Build the URL with route! so the link matches your routes.

src/notifications/invoice_paid.rs
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)]))
    }
}

Slack reads &, <, and > as markup, so the framework escapes them in every string you pass. Use slack::markdown! with slack::mention or slack::link when you do want a mention or a formatted link. Slack's block limits are checked before the message is sent.

Gotcha

The fallback text is what Slack shows in notifications and reads to screen readers. Keep it a real summary of the blocks, not a placeholder such as “New message”.

Testing notifications and mail

In plain words

A fake records what your code would have sent, so a test can assert on the recipient, the subject, and the content without reaching a provider.

mail::fake() records email instead of sending it. It still renders each mailable and reads files attached with from_path or from_storage, so a template error or a missing attachment fails the test, even for a queued email. assert_queued_where::<OrderShipped> receives the recorded email with has_to, subject(), html(), text(), and mailable(). The predicate sees both the rendered message and the original mailable, so a wrong subject or a missing field fails the test.

tests/shipping.rs
#[dust::test]
async fn shipping_an_order_emails_the_customer(app: Application) -> dust::Result<()> {
    let user = create!(User { name: "Taylor", email: "taylor@example.com", password: "password" }).await?;
    let order = create!(Order { user_id: user.id, total: 2500 }).await?;
    let mail = mail::fake();

    app.post(format!("/orders/{}/ship", order.id)).await.assert_redirect();

    mail.assert_queued_where::<OrderShipped>(|queued| {
        queued.mailable().order_id == order.id && queued.has_to("taylor@example.com")
    });

    Ok(())
}

notification::fake() records notifications. assert_sent_to_where::<InvoicePaid>(&user, ...) gives you the original notification, queued(), mail(), sms(), and message::<Slack>(). A channel accessor is None when that channel was skipped, so the absence of a phone number is visible in the test.

To test one mailable on its own, call mail::render and inspect the returned Email; no route and no fake are needed. The mail fake has assertions for sent, queued, times, and nothing sent; the notification fake mirrors them for sent notifications, with queued() to tell the two apart.

Gotcha

While the notification fake is active, notification messages do not reach the mail or SMS fakes. That is deliberate: one fake owns the assertion, so a message is not counted twice.

Chapter 11

Security & sessions

Most security is a few decisions made once: who can log in, who can act, what a request carries, and how often it may try.

Authentication answers “who are you?”. Authorization answers “may you do this?”. Sessions remember the answer between requests, and CSRF and rate limiting protect the requests themselves.

The framework provides the machinery; the policy is yours. This chapter shows where each decision lives.

Authentication

In plain words

Logging in proves who a user is. After that, the session carries the user's identity from request to request.

A handler that requires a logged-in user takes Authenticated<User>. A guest never reaches it: the framework redirects a browser to the login page and returns a 401 to a JSON request. The extractor dereferences to the user, so the handler reads user.name directly.

src/http/dashboard.rs
use dust::auth::Authenticated;

pub async fn show(user: Authenticated<User>) -> View {
    view("dashboard", data! { user })
}

Login, registration, and email verification pages get an attribute that tells the framework where they are. The authentication middleware then knows where to send a guest and where to send a logged-in user.

src/http/auth.rs
#[dust::auth::page(login)]
pub async fn show_login() -> View {
    view("auth.login", data! {})
}
Guests are not errors

A guest asking for a protected page is a normal redirect, not a 403. The 403 is for a user who is logged in but not allowed.

Registration, login, and verification

In plain words

Registering creates a user row, logging in proves the password belongs to that row, and verification proves the email address belongs to the person.

Registration is a handler like any other: it reads a form, creates a row, and signs the new user in. The login handler takes Auth<User> and calls attempt, which finds the user by email, checks the password, regenerates the session ID, and stores the user in the session. Pass the value of a “remember me” checkbox to remember, and redirect with Redirect::intended so the user lands on the page they originally wanted.

Tell the framework where your core authentication pages are with #[dust::auth::page(..)]: login, home, reset_password, verification_notice, and verify_email. The attribute does not change the handler; it only lets the authentication middleware send a guest to your login form, a logged-in user to your home page, and reset and verification emails to the right routes. Mark only the pages your application actually uses.

Sign-up creates the row with create!, which hashes the password because the field is a PasswordHash, so the plain text never reaches the database. auth.login(&user) signs the new user in without checking a password, and verification.send_link(&user) queues a VerificationEmail with a signed link valid for 60 minutes. It does nothing if the address is already verified.

src/http/auth.rs
use dust::auth::{Auth, EmailVerification};
use dust::model::create;
use dust::prelude::*;

pub async fn sign_up(
    auth: Auth<User>,
    verification: EmailVerification<User>,
    Valid(form): Valid<SignUp>,
) -> dust::Result<Redirect> {
    let user = create!(User {
        name: &form.name,
        email: &form.email,
        password: &form.password,
    })
    .await?;

    auth.login(&user).await?;
    verification.send_link(&user).await?;

    Ok(redirect!(dashboard::show))
}

Verification needs three routes behind Authenticate: a notice page, a resend handler, and the handler for the link itself. EmailVerification<User> reads the {id} and {hash} from the link; verify() checks the signature and the user's current address, sets email_verified_at, and succeeds harmlessly when the same link is opened twice. The resend handler sends a fresh link, and both it and the notice page send an already-verified user on to the page they wanted. Throttle the resend and verify routes with separate buckets, as the verification guide does, so one cannot flood an inbox while the other is brute-forced.

Gotcha

A verification link is tied to the address it was sent to. Changing the email clears email_verified_at and invalidates every older link, so clear the timestamp in the same update and send a new link to the new address.

Passwords and reset

In plain words

A password is stored as a one-way hash, never as text. A reset is how someone who forgot theirs proves they control the inbox and chooses a new one.

dust hashes passwords with bcrypt at a cost factor of 12 by default. Raise BCRYPT_ROUNDS as hardware gets faster; existing hashes keep working, and attempt rehashes each one on the user's next login. Because the stored hash changes, that login also signs the user out of their other devices.

Declare password fields as dust::hash::Password, not String, so the plain text stays out of logs. Bcrypt reads only the first 72 bytes, so a Password field fails validation on longer input instead of silently truncating it. A sign-up form uses #[validate(required, password, confirmed)]; create! hashes the value into a PasswordHash, which cannot be serialized into JSON by accident.

A reset needs four routes: the forgot-password form and its POST, then the form that sets a new password and its POST. Put them behind RedirectIfAuthenticated and inside the web group, because the reset token lives in the cache and the email is queued. send_reset_link returns the same response whether or not the address exists, which keeps the form from revealing registered accounts.

The email links to /reset-password/{token}?email=…; the token travels in a hidden field because the form posts to a different URI. Tokens are single-use and valid for 60 minutes, and an invalid one is a validation error on email. Call validate when showing the form to catch an expired link before the user types a new password — it does not consume the token. For a signed-in user changing their password, validate current_password and call update_password; it keeps the current device signed in and logs out every other session.

src/http/passwords.rs
pub async fn reset_password(
    passwords: Passwords<User>,
    auth: Auth<User>,
    Valid(form): Valid<ResetPassword>,
) -> dust::Result<Redirect> {
    let user = passwords
        .reset(&form.email, &form.token, &form.password)
        .await?;

    auth.login(&user).await?;

    Ok(redirect!(dashboard::show))
}
Gotcha

A reset logs the user out everywhere, including sessions an attacker holds. Keep the token out of logs and analytics: it is as sensitive as the password it replaces.

Social login

In plain words

Social login hands the proof of identity to Google, GitHub, or Microsoft. Your application receives a profile and still decides which local user it belongs to.

Create an OAuth application in the provider's console, then add its client ID and secret to .env under the provider's prefix. The callback URL you register must match /auth/{provider}/callback on your application's URL, or the URL in GOOGLE_REDIRECT_URI, GITHUB_REDIRECT_URI, or MICROSOFT_REDIRECT_URI. Microsoft also needs the xms_edov optional claim so work and school addresses count as verified.

.env
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=

GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=

MICROSOFT_CLIENT_ID=
MICROSOFT_CLIENT_SECRET=

Two routes serve every provider: one redirects the user to the provider, one receives the callback. Register both in the web group behind RedirectIfAuthenticated, because the OAuth state is stored in the session. The link on your login page must be a normal navigation — an <a> tag, not a fetch — so the browser can follow the provider's redirect.

social::user(provider) verifies the state and returns a profile with a stable provider ID and the user's email, marked verified or not. Look a returning user up by provider and provider_id first, never by email alone, because the address can change at the provider. For a new user, create the account, mark the email verified since the provider confirmed it, and call auth.login. For an existing account, link it only through verified_email(); if its address was never verified, clear the password before linking so nobody can sign in with a password chosen before the link.

Failure has a shape. Cancelling returns social::Error::Denied (403 if propagated), an old or mismatched callback returns InvalidState (403), and a provider error returns Provider (502). A provider with no client ID or secret returns 404 at the redirect route. When the provider sends no verified address, send the user back to login with a status message instead of creating an account.

Gotcha

Never link an account by an address the provider has not verified. An administrator of a Microsoft or Okta tenant can hand one of their users your customer's address; only verified_email() is safe for linking.

Authorization

In plain words

A policy is a struct that answers “may this user update this post?”. The answer is ordinary Rust, checked at the call site.

Policies group the rules for one model. Each method takes the user first and the record second, and returns whether the action is allowed. Mark the impl with #[policy].

src/policies/post.rs
#[policy]
impl PostPolicy {
    pub fn update(user: &User, post: &Post) -> bool {
        user.id == post.user_id
    }

    pub fn delete(user: &User, post: &Post) -> bool {
        user.id == post.user_id || user.is_admin
    }
}

Call the policy method at the point where the action happens. Passing the method itself means a misspelled ability or the wrong model type is a compile error.

src/http/posts.rs
pub async fn destroy(user: Authenticated<User>, post: Post) -> dust::Result<Redirect> {
    user.authorize(PostPolicy::delete, &post).await?;

    post.delete().await?;

    Ok(Redirect::back())
}
One place per rule

A policy is not a second controller. It answers one question and returns a boolean; the handler still decides what to do with the answer.

Sessions and cookies

In plain words

A session is server-side data tied to a cookie. The cookie is only an ID; the values stay on the server.

The web middleware group starts the session and saves it after the handler returns. Take Session to read and write values; take Request and call request.session() when the route might not have one.

src/http/theme.rs
pub async fn show(session: Session) -> String {
    let theme: Option<String> = session.get("theme");

    theme.unwrap_or_else(|| "light".to_owned())
}

Cookies are for values the browser should keep, such as a theme or a consent choice. Set one on any response with with_cookie; remove one with without_cookie. The session cookie itself is managed by the framework.

src/http/theme.rs
Redirect::back().with_cookie(("theme", "dark"))
Server-side by default

Do not put a role or a price in a cookie. The browser can read it and change it. Put it in the session and read it on the server.

CSRF and rate limiting

In plain words

CSRF stops another site from submitting your forms. Rate limiting stops one client from trying too often.

Every web form includes a token that proves it came from your page. Call csrf_field() inside the form; the framework renders the hidden field and checks it on the way in. API routes are stateless and do not use it.

resources/views/posts/create.html
<form method="POST" action="/posts">
    {{ csrf_field() }}
    <input name="title">
</form>

A throttle is middleware. Apply it to one route, a group, or the whole API. The token bucket allows a burst and then refills steadily; a bucket name isolates a route's counter from the shared one.

src/routes/web.rs
use dust::rate_limit::Throttle;

route
    .post("/login", auth::login)
    .middleware(Throttle::per_minute(5).bucket("login"));

For an API, append the throttle to the api group in src/app.rs. Attach it after authentication so the counter is per user, not per IP.

Test the lock, not the key

Write a test that sends too many requests and asserts the 429. A limit you never exercised is a limit you do not know.

Chapter 12

Filesystem & media

A file needs three decisions: where it lives, who may read it, and which model owns it.

An avatar, an invoice, a video, a nightly export: sooner or later an application keeps something that is not a row. dust calls each place a file can live a disk, and gives every disk the same small API.

This chapter configures disks, reads and writes through them, separates what the public may see from what it may not, and attaches uploads to models with the media library.

Disks and configuration

In plain words

A disk is a name for a place files live. Your code asks for the name; the configuration decides whether that place is a folder on this server or a bucket somewhere else.

dust configures three disks out of the box. local writes to storage/app/private and is the default; public writes to storage/app/public and is served at /storage; s3 writes to the bucket named by AWS_BUCKET. FILESYSTEM_DISK chooses the default disk, so a production server can switch to s3 without a code change.

A disk is declared in src/config/filesystems.rs. This is Rust configuration, not a TOML document: the compiler checks the names, and a misspelling is a compile error instead of a runtime surprise. Start from Filesystems::from_env(env) so the built-in disks and environment variables remain, then add your own. Register the module in src/config/mod.rs with mod filesystems;.

src/config/filesystems.rs
use dust::config::filesystems::{Filesystems, LocalDisk};
use dust::config::{self, Env};

#[config::section]
fn filesystems(env: &Env) -> Filesystems {
    let mut filesystems = Filesystems::from_env(env);

    filesystems.add_disk(
        "documents",
        LocalDisk::new("storage/app/documents").mount("/documents"),
    );

    filesystems
}

LocalDisk::new takes a root relative to the application's base path. .mount("/documents") serves the disk at that URL, and .public() lets anyone download from it; without .public(), only signed temporary URLs work. S3Disk::new(bucket, region) is the same idea for an object store, and needs the s3 Cargo feature. The built-in s3 disk reads AWS_BUCKET, AWS_DEFAULT_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_ENDPOINT, AWS_USE_PATH_STYLE_ENDPOINT, and AWS_URL. Leave the keys out to use the AWS SDK's default credential chain, such as an instance role.

A read-through disk helps during a migration. ReadThroughDisk::new("s3", "local") writes to s3 and reads s3 first, falling back to local on a miss. By default a fallback hit is copied to the primary; .without_promotion() leaves it in place, and .throw_on_promotion_failure() makes a failed copy fail the read. Deletes remove the file from both disks.

The default disk is private

local stores under storage/app/private and has no public URL. Calling url on it returns an error; serve the file with download or a temporary URL. If you want direct links, use the public disk deliberately.

Writing and reading files

In plain words

A disk handle reads and writes paths relative to its root. The calls are the same whether the bytes land in a folder or a bucket.

storage::put writes to the default disk. For a named disk, call storage::disk("s3")? once and use the returned handle; it has the same methods. put replaces the file at the path and accepts a string or a byte slice. get returns Bytes, a cheap buffer that dereferences to [u8].

get and json hold the whole file in memory and refuse anything over 8 MiB with storage::TooLarge. Use get_with_limit to raise the ceiling, or read_stream and write_stream to move large files in chunks. exists and missing answer without reading; delete removes a file and succeeds when it is already gone. size, mime_type, last_modified, and metadata describe a file without loading it.

Paths are relative to the disk's root: reports/monthly.csv on local is storage/app/private/reports/monthly.csv. A path starting with / or containing a .. segment is rejected with storage::InvalidPath, so never build one straight from user input. On a local disk, full_path gives the file on the server; on S3 there is no local path and the call fails. The rest of the API does not care.

src/http/exports.rs
use dust::prelude::*;
use dust::storage;

pub async fn export() -> dust::Result<Redirect> {
    let reports = storage::disk("s3")?;

    reports
        .put("reports/monthly.csv", "name,total\nTaylor,42\n")
        .await?;

    if reports.exists("reports/monthly.csv").await? {
        let metadata = reports.metadata("reports/monthly.csv").await?;

        if metadata.size > 0 {
            // ...
        }
    }

    Ok(Redirect::back())
}
MIME is a hint, not a check

mime_type comes from the filename or the storage backend, not from inspecting the bytes. Do not use it to decide whether a file is safe; validate uploads with the image or mimes rules instead.

Public and private files

In plain words

Two folders look similar and mean different things: public/ is served to the world, storage/ is not. A file becomes public when it lands on a public disk.

The public disk writes to storage/app/public, and dust serves that directory at /storage. A file stored as avatars/1.png is therefore available at https://example.com/storage/avatars/1.png. Build the address with storage::disk("public")?.url("avatars/1.png").await?; the path is encoded for you.

Keep the two trees separate. public/ holds the site's own assets: CSS, JavaScript, logos, fonts, robots.txt, and the io/ui vendor files. storage/ holds files the application produces or receives: uploads, invoices, exports, and conversions. A user upload never belongs directly in public/, because the name and the type come from the browser, and a file there is downloadable by anyone who guesses the path.

A custom local disk can have its own mount. .mount("/images") publishes it under /images, but only signed URLs can fetch from it until you add .public(). The longest matching mount wins, and an application route on the same path takes precedence. For a private file, storage::temporary_url("invoices/1.pdf", 5.minutes()).await? signs a link with APP_KEY on a local disk; on S3 and DUST Cloud it is a presigned bucket URL.

When the check is more than a signature, serve the file through a handler. storage::download returns a response the browser saves, and storage::response displays it inline. Both stream the file and return 404 when it is missing, so authorize before you return one.

src/http/invoices.rs
use dust::prelude::*;
use dust::storage::{self, FileResponse};

use crate::models::User;

pub async fn invoice(
    user: Authenticated<User>,
    Params(id): Params<u64>,
) -> dust::Result<FileResponse> {
    // Check that this invoice belongs to the user...

    Ok(storage::download(&format!("invoices/{id}.pdf"))?
        .name("Invoice.pdf"))
}
Public means public

/storage has no authentication. A URL is not a secret: anyone who has it, or guesses it, can fetch the file. Put invoices, exports, and anything tied to a user on a private disk.

The media library

In plain words

The media library stores a file for a model, records it in a table, and can make resized copies. The model declares which collections it accepts.

The library is optional. A new application enables the medialib feature and ships the media migration; on an older application, add the feature and run dust migrate. Every attachment becomes one row in media and one file on a disk. The row stores the owning model's morph name and key, the collection, the display name, the file name on disk, the MIME type, the disk, the size, and the generated conversions.

A model takes part by implementing HasMedia. register_media_collections declares groups such as images or documents. The rules live on the collection: disk("s3") stores it elsewhere, single_file() keeps only the newest file, accepts(["image/*"]) rejects other types, and conversions(...) names the sizes to generate.

src/models/post.rs
use dust::medialib::{HasMedia, MediaCollections};

impl HasMedia for Post {
    fn register_media_collections(collections: &mut MediaCollections) {
        collections.add("images").single_file().accepts(["image/*"]);
        collections.add("documents");
    }
}

let media = post
    .add_media("storage/app/photo.jpg")
    .to_media_collection("images")
    .await?;

Attach a file with add_media for a path, add_media_bytes for bytes already in memory, or add_media_url for an http(s) URL. Chain .named("Cover photo") to change the display name, .on_disk("s3") to override the collection's disk, or .max_bytes(..) to raise the 10 MiB download limit for a URL. Path and byte attachments infer the MIME type from the filename's extension; a URL uses its Content-Type header. The method returns a Media row once the file and its conversions are stored.

Read it back with post.get_media("images"), post.get_first_media("images"), or post.get_first_media_url("images"). For a query across models, MediaQuery::new().model("post").collection("images").mime("image/*").limit(20).get() uses the same filters as the console command. Media exposes uuid, name, file_name, mime_type, size, disk_name, path(), and the URL methods.

A collection is a rule

single_file deletes the previous file after the new one is stored; accepts checks the type the library inferred. If media:* commands must reach a model's collections, register it once at startup with dust::medialib::register::<Post>();.

Conversions and commands

In plain words

A conversion is a second version of an image at another size or shape. The original is never changed; the copy sits beside it under a named folder.

Declare conversions on the collection. crop(w, h) fills the box and trims the overflow; fit(w, h) keeps the whole image inside it; width and height resize one side and preserve the ratio; rotate turns the image; quality sets the encoder quality for lossy formats; format chooses JPEG, PNG, or WebP. A custom step implements Manipulation and is added with manipulate.

src/models/post.rs
collections.add("images").conversions(|conversions| {
    conversions.add("thumb").crop(200, 200);
    conversions.add("preview").fit(800, 600);
    conversions.add("large").width(1600).quality(90);
});

Conversions are generated when the file is attached, before to_media_collection returns. Only raster images are converted: an SVG keeps the original only. The output keeps the source format by default—PNG stays PNG, WebP stays WebP, everything else becomes JPEG. Read a conversion with media.url_with_conversion("thumb").await?; when it wasn't generated, you get the original's URL.

On disk, a media file lives under media/<model>/<id>/<uuid>/<file>, for example media/post/42/3f2a.../photo.jpg. Each conversion is stored at media/<model>/<id>/<uuid>/conversions/<name>/<stem>.<ext>. The path is relative to the disk named on the row, so a move to another disk keeps the same layout.

Four commands manage the library. Run them through dust, from the application directory. --name sets the display name, and media:add takes --max-bytes to cap a URL download.

shell
dust media:add storage/app/photo.jpg --model=post --id=42 --collection=images
dust media:add https://example.com/photo.jpg --model=post --id=42 --collection=images --disk=s3

dust media:list --model=post --collection=images --mime='image/*' --limit=20
dust media:list --disk=public --oldest --json

dust media:move <uuid> --disk=s3
dust media:delete <uuid>

media:delete removes the original, every generated conversion, and the row; a file already missing is skipped. media:move copies the original and its conversions, updates the row, and only then deletes the old copies, so a failed move leaves the old disk intact. post.clear_media_collection("images") does the same for every file in a collection. Register each model once at startup with dust::medialib::register::<Post>(); so the commands can find its collections.

Attaching is part of the request

Conversions run before the attach returns, so a large original adds its processing time to that HTTP response. For big uploads, attach the file from a queued job instead.

Uploads in a handler

In plain words

An upload arrives with a form, not as a string. Receive it as an UploadedFile, let validation check it, then copy it somewhere durable before the request ends.

Declare the file as a field on a #[dust::input] struct and take Valid<T> in the handler. Put the rules on the field: required, image, mimes("pdf"), extensions("csv"), max_kilobytes(4096). image and mimes read the bytes, so a renamed text file fails; SVG fails image. Use Option<UploadedFile> when the file is optional and Vec<UploadedFile> for a multiple input. A failed rule redirects a browser back with the errors, and an API client gets a 422.

The temporary file is deleted when the request ends, so copy it before you return. form.photo.store("avatars").disk("public").await? writes a random 40-character name plus the extension detected from the contents, and returns a path such as avatars/7kQ2...png. store_as lets you choose the name; never choose client_name, because the user controls it. If the file belongs to a model, the media library does the copy instead.

src/http/posts.rs
use dust::http::UploadedFile;
use dust::prelude::*;

#[dust::input]
#[validate(authenticated)]
pub struct UploadPhoto {
    #[validate(required, image, max_kilobytes(4096))]
    photo: UploadedFile,
}

pub async fn store(
    post: Post,
    Valid(form): Valid<UploadPhoto>,
) -> dust::Result<Redirect> {
    let extension = form.photo.extension().unwrap_or("jpg");
    let bytes = form.photo.bytes().await?;

    post
        .add_media_bytes(bytes, format!("photo.{extension}"))
        .to_media_collection("images")
        .await?;

    Ok(Redirect::back())
}

pub async fn show(post: Post) -> dust::Result<View> {
    let image = post.get_first_media_url("images").await?;

    Ok(view("posts.show", data! { post, image }))
}

The handler attaches the upload to the post's images collection. extension() reads the contents, so the name passed to add_media_bytes matches the real format. The attach stores the original, inserts the media row, and generates the declared conversions before it returns. Authorize the post first: #[validate(authenticated)] proves someone is logged in, not that they may edit this post. There is no second path to keep—the row points at the file and the disk.

To render it, read the first file's URL with post.get_first_media_url("images") and pass it to the view, or keep the returned Media and call url_with_conversion("thumb") for a smaller copy. The URL is None when the collection is empty, so the template can show a placeholder. For a plain path stored on a column, build the URL with storage::disk("public")?.url(&path).await?.

Validate, then store

Validation runs before the handler, so image has already read the bytes. Do not skip it because the file “looks like” a PNG; the extension and content type sent by the browser are claims. Raise LimitUploads above max_kilobytes when a form may exceed the 16 MB default.

Chapter 13

Modules

A module is a feature with a boundary: its own routes, tables, views, and services, compiled into the application but able to leave.

Every application starts with one place for code. Eventually a feature grows its own URLs, its own tables, and its own screens, and it starts to feel like a tenant inside the application. A module gives that feature a front door.

Modules are not crates. They compile with the application, so there is no second package to publish or version, and a disabled module is still type-checked.

What a module is

In plain words

A module is a folder that owns a feature end to end. It sits beside src/, not inside it, and the application decides whether it runs.

A blog, a shop, or an admin panel is a module. A single handler, a policy, or a helper is not; those belong in src/. The test is whether the feature has all three: its own URLs, its own tables, and a boundary you might want to turn off.

modules/blog/
mod.rs          pub struct Blog; impl Module for Blog
routes.rs       the module's URLs
handlers/       one function per page
migrations/     the module's tables
views/          templates under the blog:: namespace
services.rs     shared objects, registered on boot

The module's name is its folder and its view namespace. A view called blog::posts.show resolves to modules/blog/views/posts/show.html. Because the code is compiled in, a module can use the application's services and models directly.

Compiled, not installed

A disabled module still compiles, so it cannot rot silently. It simply does not register its routes, migrations, or services at boot.

Creating a module

In plain words

Run one command, then fill in the folder it creates. The registry is updated for you.

dust module:make blog creates the folder and adds it to modules/mod.rs. The module's mod.rs implements Module; only name is required, and every other method has a default.

modules/blog/mod.rs
use dust::modulis::Module;
use dust::routing::Router;

pub mod handlers;
pub mod routes;

pub struct Blog;

impl Module for Blog {
    fn name() -> &'static str {
        "blog"
    }

    fn routes(route: &mut Router) {
        routes::routes(route);
    }
}

Register it in modules/mod.rs; the generated registry calls each module once at boot. The order is the order they register, so put foundational modules first.

modules/mod.rs
use dust::container::Registrar;

pub fn register(app: &mut Registrar) {
    dust::modulis::register::<blog::Blog>(app);
    dust::modulis::register::<shop::Shop>(app);
}
No route prefix by default

The module chooses its URLs. A blog may live at /blog; an admin module may live at /admin. The framework does not guess.

Routes, migrations, views, services

In plain words

A module plugs into the same four places as the application: routes, migrations, views, and services. Nothing new to learn.

The routes function receives the router and registers ordinary routes. They appear in dust route:list and work with route! like any other URL.

modules/blog/routes.rs
use dust::prelude::*;
use crate::modules::blog::handlers;

pub fn routes(route: &mut Router) {
    route.get("/blog", handlers::posts::index);
    route.get("/blog/{post:slug}", handlers::posts::show);
}

Migrations are returned from the module and run with the application's. Views use the module namespace. Services are registered in register, after routes and migrations, and land in the application's container.

modules/blog/mod.rs
fn migrations() -> Migrations {
    dust::db::migrations!("modules/blog/migrations")
}

fn register(app: &mut Registrar) {
    app.singleton(async |_app| Ok(BlogFeed::new()));
}
Same rules, one boundary

A module is not a different framework. The value is the folder and the switch, not a second way to write a handler.

Module services and middleware

In plain words

Some parts of a module are not routes. A service is an object other code shares; middleware is a step every matching request passes through. Both are registered in one place.

The module's register method runs after its routes and migrations are added, and it receives the same Registrar a package uses. Register a shared service with singleton, which builds the object once and hands the same instance to every request that asks for it.

modules/blog/mod.rs
use dust::container::Registrar;

use crate::modules::blog::services::Feed;

impl Module for Blog {
    // ...

    fn register(app: &mut Registrar) {
        app.singleton(async |_app| Ok(Feed::new()));
        app.middleware().web(|web| {
            web.append(RecordBlogVisit);
        });
    }
}

The service lands in the application's container, so any handler may ask for it by type, including handlers outside the module. Give the type a name that includes the module when a clash is possible, such as BlogFeed rather than Feed. A module's attribute-discovered items, such as #[command] functions and listeners, work too, because the module is compiled into the application.

Middleware is the part to watch. app.middleware().web(...) appends it to the whole web group, not only the module's URLs, so RecordBlogVisit also runs on the shop's pages. If the step belongs only to the module, attach it to the module's own route group instead of the global group.

Scope is the trap

A module's routes belong to its own paths, but its middleware does not. Registering middleware on the web group is a decision that affects every request, so say so in the module's docs.

Module views and namespaces

In plain words

A module's templates live under its own namespace. The name in view(...) says which module owns the file, and the finder knows where to look.

The module's name is its view namespace. A handler renders blog::posts.show, which resolves to modules/blog/views/posts/show.html; the module's views method may replace that default directory. Handlers use the ordinary view helper and the ordinary data! macro, so a module template gets the same variables as any other.

modules/blog/handlers/posts.rs
use dust::prelude::*;

use crate::modules::blog::models::Post;

pub async fn show(post: Post) -> View {
    view("blog::posts.show", data! { post })
}

You can customize a module's template without editing the module. Place your file at resources/views/vendor/blog/index.html and the finder uses it before the module's own copy, the same override rule packages follow. That keeps a downloaded module replaceable by module:update while your changes stay in the application.

Templates are not the whole front end. Static assets are still files under public/, served at their path with no route and no controller; a module does not get a second asset pipeline or a separate public directory. Link the files the application ships, exactly as its own templates do.

A module is compiled into the application, so it is tested through the same test client. Point the test at the module's URLs, and enable refresh_database in src/testing.rs when the module ships migrations or fixtures the test database needs.

tests/blog.rs
use dust::testing::prelude::*;

#[dust::test]
async fn the_blog_lists_published_posts(app: Application) {
    app.get("/blog").await.assert_ok().assert_see("First post");
}
Keep the prefix

Dropping the namespace, as in view("posts.show", ...), points the finder at the application's resources/views, not the module's folder. The prefix is what selects the module.

Enabling and installing

In plain words

A module can be enabled, disabled, installed from the registry, or deleted. Disabling keeps the code; deleting removes it.

The module commands cover the lifecycle. A disabled module stays compiled and type-checked, but its routes, migrations, and services are skipped at boot; its tables stay in the database.

console
$ dust module:list
$ dust module:list --enabled
$ dust module:disable blog
$ dust module:enable blog
$ dust module:delete blog --force

module:download installs a module from the registry, module:update moves installed modules to newer releases, and module:make creates a local one. A downloaded module is ordinary code in modules/; read it like your own.

console
$ dust module:download pulse
$ dust module:update
$ dust module:update pulse --version 1.3.0
Disable is the safe switch

Disabling is reversible and keeps the data. Deleting is for code you no longer want; take a backup first if the module owns tables.

Chapter 14

Helpers & utilities

The small functions that keep application code short: paths, URLs, responses, and the runtime itself.

Not every useful function belongs to a class or a service. Some are one line you reach for everywhere: the path to a directory, the URL of a route, a redirect, an abort. dust exposes them at the crate root and in dust::sys, so a handler can stay about the page.

Paths and URLs

In plain words

Stop building paths with string concatenation. Ask the application where its folders are, and ask it for the absolute URL.

The path helpers read APP_BASE_PATH and join the directory you name. The URL helpers read APP_URL and, during a request, the scheme and host the request arrived with.

src/http/reports.rs
let root = dust::base_path();
let file = dust::storage_path("reports/q3.pdf");
let view = dust::resource_path("views");
let home = dust::base_url();
let post = dust::url("/posts/42");

The full set is base_path, app_path, config_path, database_path, public_path, resource_path, and storage_path. For URLs there is base_url, url, and asset; url is the same function as url::to.

Absolute paths, not guesses

A relative path depends on where the process started. storage_path does not. Use it in a job, a console command, and a request alike.

Response and view helpers

In plain words

These helpers turn a handler into a link, a redirect, a page, or a clean stop. They are the vocabulary of every route.

route! builds a URL from a handler; redirect! builds a redirect from the same handler; view renders a template. data! names the values the template receives.

src/http/posts.rs
let url = route!(posts::show, id)?;
let response = redirect!(posts::show, id);

Ok(view("posts.show", data! { post }))

abort! ends the request with a status and a message. abort_if and abort_unless do it from a condition, which reads better than an if with an early return. report sends an error to the reporter without stopping the request.

src/http/posts.rs
dust::abort_unless(user.is_admin, 403)?;

if upload.is_suspicious() {
    report(dust::Error::from(std::io::Error::other("suspicious upload")));
}
One vocabulary

Learn six helpers and most handlers read like a sentence: route it, redirect to it, view it, or abort.

Runtime helpers

In plain words

The application itself is reachable from anywhere it runs: its configuration, its services, its clock, and its error reporter.

config() returns the configuration; resolve::<T>() returns a service from the container. once computes a value once per application, which is useful for an expensive lookup that several requests share.

src/http/status.rs
let name = &dust::config().app.name;
let reports = dust::resolve::<Reports>().await?;

format!("{name}: {} reports", reports.count())

now() reads the application clock, so tests can move time without sleeping. report sends an error to the reporter; logs, traces, and the test response use the same path.

src/http/status.rs
let started = dust::now();

// ... work ...

tracing::info!(elapsed = ?dust::now() - started, "report built");
Context, not globals

These helpers read the current application context. In a request, a command, or a task spawned by the framework, they work. Outside it, they tell you so.

Chapter 15

The CLI

One command builds the application, one command runs it, and one command tells you what is happening. The rest are the verbs of an ordinary week.

dust is both the framework's command and the name of the application's console. dust new and dust build work on the project; dust migrate and dust queue:work compile the application and run its own commands.

This chapter is a map, not a manual. Each command gets one clear sentence and the situation it belongs to.

Creating and building

In plain words

dust new starts a project. dust build turns it into runnable binaries in bin/.

dust new storefront writes the project, a generated APP_KEY, a SQLite URL, io/ui, AGENTS.md, and the guides. It refuses a directory that already has files. dust docs:install writes the same instructions and guides into an older application.

console
$ dust new storefront
$ cd storefront
$ dust dev

dust dev runs the development server. dust build --release compiles the application and copies it, with dust-cron, into bin/. Deploy from bin/, not from Cargo's target directory: it is the stable place the install and daemon commands expect.

console
$ dust build --release
$ ls bin/
storefront  dust-cron

dust update refreshes the framework source, rebuilds, and updates io/ui. Use --pull for a git checkout or --download for a plain folder; --no-ui skips the frontend refresh.

bin/ is the deployment surface

A running binary can be replaced in place: the build writes a temporary file and renames it, so a deploy never leaves a half-written executable.

Installing and operating

In plain words

install is the one command for a fresh server. status is safe to run any time; it only reads.

dust install runs pending migrations, sets up the schedule, and starts the cron daemon. It does not start the web server; your process manager does. It is safe to run again, and --force skips the production migration prompt.

console
$ dust install --force
$ dust status
$ dust restart

status reports the application, database and migration count, queue, cache, cron, relay, and io/ui version. A stopped daemon shows as stopped instead of failing the command. restart restarts the cron daemon, the supervisor, and the relay server; the HTTP process is restarted by your process manager.

key:generate writes a new APP_KEY; --show prints it instead. Rotating the key does not re-encrypt existing values by itself; keep the old key in APP_PREVIOUS_KEYS until they are re-encrypted.

Read status first

When something is wrong, run dust status before changing anything. It tells you which service is actually down.

Database and queue

In plain words

Migrations move the schema forward. The queue commands show and repair the work that did not finish.

migrate applies pending migrations; migrate:status lists them; migrate:fresh drops every table and starts over, which is a local command. db:seed runs the seeders, and schema:dump writes the schema for a fresh database.

console
$ dust migrate
$ dust migrate:status
$ dust migrate:fresh   # local only
$ dust db:seed

queue:work runs a worker until stopped. The supervisor starts one process per worker, restarts it, and reports its CPU and memory. queue:failed lists failed jobs; queue:retry runs one again; queue:flush clears them.

console
$ dust queue:work
$ dust queue:failed
$ dust queue:retry 12
$ dust queue:flush

queue:pause and queue:continue stop and resume new work. queue:restart asks workers to exit after their current job, which is how a deploy replaces code without killing a job in flight.

Fresh is not a deploy command

migrate:fresh drops data. Keep it on a laptop, and make production changes with new migrations.

Schedule and cron

In plain words

The schedule is the list of timed tasks. The cron daemon is the process that looks at the clock and starts them.

schedule:list prints the tasks and their next run. schedule:run runs the tasks due in the current minute and exits; schedule:work calls it every minute for local development. schedule:setup prepares the cron entry, and schedule:clear-cache clears the scheduler's lock state.

console
$ dust schedule:list
$ dust schedule:run
$ dust schedule:work

dust-cron is the daemon. cron:start starts it, cron:restart restarts it, and cron:list and cron:runs answer what is scheduled and what happened. Expressions carry seconds, and every run records its exit code, output, error, CPU time, and memory.

console
$ dust cron:list
$ dust cron:runs
$ dust cron:restart
No system crontab

The schedule lives in the application and ships with it. There is no separate file on the server to keep in sync.

Modules, routes, and tools

In plain words

These are the day-to-day verbs: make a module, list the routes, refresh the UI, start the relay.

The module commands cover the lifecycle: module:make, module:download, module:update, module:list, module:enable, module:disable, and module:delete. A disabled module stays compiled but does not register at boot.

console
$ dust module:make blog
$ dust module:list --enabled
$ dust module:disable blog

route:list prints every registered route with its method, URI, and handler. ui:update refreshes the io/ui assets; relay:start runs the local WebSocket server; media:add, media:list, media:move, and media:delete manage media files.

console
$ dust route:list
$ dust ui:update
$ dust relay:start

dust list shows the application's own commands next to the framework's. A command you write with #[command] becomes another verb in the same grammar.

One grammar

Framework commands and your commands share the same console. The only difference is who wrote them.

Chapter 16

Testing & deployment

A framework is only as good as the loop around it: a test that runs the whole stack, and a binary you can put on a server.

The last chapter closes the loop. A feature test sends a request through the real middleware, routing, policies, and handler without binding a port. The build turns the same code into one binary, and the server runs it under a process manager.

If the test and the deploy use the same stack, the gap between “works here” and “works there” gets very small.

Feature tests

In plain words

A feature test is a request without a network. It runs the same code a browser would trigger and lets you assert on the answer.

#[dust::test] runs a synchronous or asynchronous test. With an Application argument, it gets a fresh application scoped to the test; the request goes through the real stack.

tests/posts.rs
use dust::testing::prelude::*;

#[dust::test]
async fn the_feed_lists_posts(app: Application) {
    app.get("/posts")
        .await
        .assert_ok()
        .assert_see("Latest posts");
}

Requests can carry a body, a token, a session, or a logged-in user. app.post with .form sends a form; .json sends JSON; .token sets a bearer token. The response has the status, the headers, and the body.

tests/posts.rs
app.post("/posts")
    .form([("title", "Hello"), ("body", "World")])
    .await
    .assert_redirect();
No server to start

The test client dispatches in-process. CI does not need a port, a browser, or a running server.

Assertions

In plain words

Assert the part the user cares about: the status, the text, the JSON shape, or the validation error.

The response assertions cover the common cases. assert_ok checks 200; assert_redirect checks a redirect; assert_see checks that the body contains text, matching both plain and HTML-escaped forms.

tests/posts.rs
app.get("/posts/42")
    .await
    .assert_ok()
    .assert_see("Dust 0.1.4")
    .assert_dont_see("Draft");

For an API, assert_json does a partial match from the root: name the fields you care about and ignore the rest. Validation has its own assertions: assert_invalid names the fields that should fail, and assert_valid names the ones that should pass.

tests/posts.rs
app.post("/posts")
    .form([("title", "")])
    .await
    .assert_invalid(&["title"]);
One assertion per test

A test that fails should say which promise broke. If a test needs a paragraph to explain, split it.

Databases and fakes

In plain words

Each test gets its own application and database state. External services can be faked, so tests stay fast and deterministic.

A test that touches the database can refresh it to the migrations and seed only what it needs. Tests run in parallel, each with an isolated application, so one test cannot see another's rows.

The framework ships fakes for the services that leave the process, such as mail, notifications, queues, and time. A fake records what would have happened; the test asserts the record instead of contacting a provider.

tests/orders.rs
#[dust::test]
async fn a_shipped_order_emails_the_customer(app: Application) {
    app.post("/orders/42/ship").await.assert_redirect();

    // assert the mail fake received OrderShipped
}

Use the clock instead of sleeping. A test that waits three days for a workflow is not a test; move the clock and run the next step.

Deterministic beats realistic

A fake that always answers the same way is a better test than a provider that is usually up.

Build, ship, and systemd

In plain words

Build a release binary, put it in bin/, and let systemd start it. The same binary serves requests and runs the console.

dust build --release compiles the application and copies it, with dust-cron, into bin/. Deploy bin/, public/, resources/, and the config; the rest of the source is not needed to run.

console
$ dust build --release
$ dust install --force
$ systemctl restart storefront

A small systemd unit keeps the server alive. WorkingDirectory lets the application find public/, resources/, and storage/; TimeoutStopSec must outlast the server's shutdown timeout so in-flight requests and background work can drain.

/etc/systemd/system/storefront.service
[Service]
Type=simple
User=www-data
WorkingDirectory=/srv/storefront
EnvironmentFile=/srv/storefront/.env
ExecStart=/srv/storefront/bin/storefront
Restart=always
RestartSec=1
TimeoutStopSec=25

Migrations run in dust install, before the server starts. The cron daemon and the supervisor are separate programs; dust status shows whether each is running.

One binary, one deploy

Replace the binary and restart the service. There is no build artifact to copy and no frontend bundle to publish.

Chapter 17

Cron & workflows

Some work needs a clock, some needs a memory: cron starts commands on time, and workflows remember where a long process stopped.

Not every piece of work starts with an HTTP request. A weekly digest goes out on Friday evening, stale records are pruned at midnight, a new customer receives tips three days after signing up, and a payment provider calls back an hour later to say the charge settled. None of those needs a visitor. All of them need either a clock or a memory.

dust gives you three tools for that work. The cron daemon runs commands whose schedule is stored in the database. The scheduler expresses recurring tasks in Rust, so the schedule ships with the code. A workflow keeps a multi-step process alive across sleeps, webhooks, and deploys, because every finished step is written down.

Cron and the daemon

In plain words

dust-cron reads your cron entries from the database and starts each one when its time comes. There is no crontab on the server.

Classic cron gives you a line in a system file, one-minute resolution, and almost no record of what happened. dust keeps the entries in the crons table and runs a dedicated daemon, dust-cron, which checks the clock and starts each due command in its own process. Expressions carry seconds, so a health check can run every second without a trick, and every execution leaves a row in cron_runs.

A new application ships the daemon binary at src/bin/dust-cron.rs, the crons, cron_runs, and cron_runners migrations, and the log and PID paths. Build it with the application, then start it:

console
$ cargo build --bin dust-cron
$ dust cron:start
$ dust cron:status
$ dust cron:restart

dust build builds both binaries into bin/, and cron:start looks there first, then for a dust-cron next to the application binary. It launches the daemon with nohup and waits for the PID file. On an older application, add the feature, the binary, and the migration, then run dust migrate before starting either side.

While it runs, the daemon loads the active crons and computes their next run, checks every CRON_TICK_MS, starts commands through /bin/sh -c, captures output, samples CPU and memory from /proc, and updates cron_runs plus the cron's last status. On startup it marks runs left running by a previous daemon as interrupted, and it keeps a heartbeat in cron_runners. The supervisor is separate: it keeps the queue worker alive, while the daemon has its own PID file. dust status reports both, and dust restart restarts the daemon, supervisor, and relay.

If it will not start

cron:start waits five seconds for the PID file. When it times out, the reason is almost always in storage/logs/cron.log.

Writing a cron entry

In plain words

A cron entry is a name, a schedule, and a shell command. You add it once, and the daemon runs it forever after.

The command is everything after --, so its own flags are not mistaken for options to cron:add:

console
$ dust cron:add backup "0 3 * * * *" -- ./app backup
$ dust cron:add health "* * * * * *" -- curl -fsS http://127.0.0.1:8000/health

The first runs daily at 03:00; the second runs every second. Options shape the run: --timeout <seconds> kills a command that hangs, --overlap skip|allow|queue handles a slow previous run, --timezone <tz> follows a local clock, --working-dir <path> changes the folder, and --suspended adds it without scheduling. A five-field expression starts at second zero, so 0 3 * * * and 0 0 3 * * * mean daily at 03:00. Change, pause, restore, and remove entries with cron:update, cron:suspend, cron:resume, and cron:delete.

When a cron is due but its previous run has not finished, the default skip leaves the due run for later. allow starts another copy alongside the first, for commands that are safe to run twice at once; queue currently behaves like skip. A run that exceeds its timeout is killed and recorded as timeout. A run that exits non-zero is recorded as failed, with its exit code and the tail of stderr. Crons do not retry automatically: put the loop inside the command, or read the failure from cron_runs and act on it with a job or an alert.

A cron is a deployed shell script

The command runs through /bin/sh -c. Never build one from untrusted input, and restrict who may run cron:add and cron:update in production.

Run history and debugging

In plain words

Every execution leaves a row with its result, its output, and what it cost. You debug from the row, not from a guess.

Each row in cron_runs stores the daemon's runner_id and the child's pid, the start and finish times, the status, the exit code, the last 64 KiB of stdout and stderr, cpu_ms, and memory_kb. It also records whether the run was scheduled or manual. The full output stays under storage/logs/cron/, so truncation in the table never loses the whole story.

Five statuses cover every outcome. running means the process is alive; success means exit code zero; failed means a non-zero exit; timeout means the daemon killed it at the limit; interrupted means a daemon exited before the run finished, and the next daemon marks those rows so the history has no permanent ghosts.

console
$ dust cron:list
$ dust cron:runs backup
$ dust cron:runs backup --limit 50
$ dust cron:run backup
$ dust cron:logs --lines 100

cron:list prints each entry with its schedule, state, last run, next run, and last status. cron:runs prints run IDs with start time, status, exit code, CPU, memory, and the first output line; it defaults to the newest twenty. cron:logs tails the daemon log, where start-up errors live. cron:run backup reproduces a failure without waiting, but it is a real execution: side effects happen and the row counts. Runs older than CRON_RETENTION_DAYS (seven by default) are pruned hourly, and cron:prune --days <n> does it on demand.

Read the row before the log

The status and exit code tell you which kind of failure it was. Only then is the captured stderr worth reading in full.

The scheduler

In plain words

The scheduler is your schedule written in Rust. One cron entry calls it every minute, and it decides which tasks are due.

Most recurring application work belongs in source control, not in a row someone added over SSH. It lives in src/console/mod.rs, where #[schedule::tasks] marks a function that dust discovers automatically:

src/console/mod.rs
use dust::db;
use dust::schedule::{self, Schedule};

#[schedule::tasks]
fn schedule(schedule: &mut Schedule) {
    schedule.call(prune_recent_users).daily();
}

pub async fn prune_recent_users() -> dust::Result<()> {
    db::table("recent_users").delete().await?;

    Ok(())
}

There are five kinds of task. call runs an async function in the scheduler's process. command runs a console command in a fresh process, split with shell-style quoting but without a shell. exec runs an external program and takes args without escaping. shell runs a line through the system shell for pipes and redirects. job dispatches a queued job, the right choice for work that takes more than a few seconds.

src/console/mod.rs
schedule.command("emails:send Taylor --force").daily_at("08:00");
schedule.exec("node").args(["scripts/report.js"]).hourly();
schedule.shell("node scripts/report.js | gzip > storage/report.gz").daily();

Frequencies read like English: every_minute, every_five_minutes, hourly_at(17), daily_at("13:00"), weekly_on(Weekday::Monday, "08:00"), monthly_on(4, "15:00"), or a five-field cron("*/5 8-17 * * MON-FRI"). Constraints narrow a task: weekdays, between("08:00", "17:00"), environments(["staging", "production"]), and async predicates with when and skip. All times are UTC and missed minutes are not backfilled. without_overlapping skips a run while the previous one holds a cache lock; on_one_runner lets one server run a task each minute. Both need a shared cache store, so call schedule.use_cache("database") and name callbacks that use either lock.

schedule:run runs everything due in the current minute, waits for the tasks, reports failures, and exits. schedule:work calls it at the start of every minute for local development. schedule:setup adds the cron entry 0 * * * * *, which runs your binary with schedule:run from the application folder; dust install does it too. schedule:list prints every task with its expression and next run, with -v and --json. After a deploy, ./your-app schedule:interrupt stops a sub-minute run still repeating the old build; schedule:clear-cache is only for a lock left by a crash.

The scheduler is not a crontab

schedule:run is the only entry your server needs. Everything else is Rust, reviewed and deployed with the rest of the application.

Durable workflows

In plain words

A workflow is an async function whose progress is saved after every step. It can sleep for days, wait for a webhook, and pick up where it stopped after a deploy.

Onboarding a customer might mean a welcome email, a three-day wait, and tips if no project exists yet. With queues alone you chain delayed jobs and add status columns. A workflow expresses the same thing as one function, with a struct deriving Queueable and a #[workflow] impl:

src/workflows/onboard_user.rs
use dust::queue::Queueable;
use dust::time::ToSpan;
use dust::workflow::{Run, workflow};

#[derive(Queueable)]
pub struct OnboardUser {
    pub user_id: i64,
}

#[workflow]
impl OnboardUser {
    async fn handle(self, run: &Run) -> dust::Result<()> {
        run.step("send welcome email", self.send_welcome_email()).await?;

        run.sleep(3.days()).await?;

        if run.step("count projects", self.count_projects()).await? == 0 {
            run.step("send tips", self.send_tips()).await?;
        }

        Ok(())
    }
}

Runs execute on your existing queue workers. Each advance calls handle from the top, replays the steps whose results are stored, and runs the next unrecorded step. At a sleep, a wait, or a retry backoff the run suspends and schedules a delayed job, so no process sits idle for two weeks. If a worker crashes, its lease expires and workflow:recover requeues the run from the last recorded step.

run.step("name", work) executes the work once and persists its result; later advances return the stored value. Names must be unique within a run, so a loop includes its key. A step retries three times by default, with backoffs of 10 seconds and 1 minute; set tries, backoff, and timeout, return workflow::retry_after(when, error) when an API says when to return, or wrap an error in workflow::fatal to stop at once. run.sleep, run.sleep_until, and run.wait_for::<T>(token) suspend durably; workflow::resume(token, value) delivers a value, and workflow::webhook_url(token) gives an external service a signed callback URL. A token is an identifier, not a secret, so protect the route; if a reply can arrive early, claim it at start.

Runs live in the database store by default, across workflow_runs, workflow_steps, workflow_waits, workflow_resumes, and workflow_attributes. New applications do not include them; add a migration containing only dust::workflow::tables!(); before the first run. Choose another store with WORKFLOW_STORE; the memory store is for tests only. Because runs resume by matching step names, adding or removing a step is safe, renaming one runs it again, and a stable #[workflow(name = "users.onboard")] keeps in-flight runs attached.

Handle replays from the top

Do all I/O inside steps and branch only on inputs and recorded results. If handle awaits anything other than an operation on &Run, the run fails and names the last step it passed.

Workflow patterns and testing

In plain words

Start once, make every step safe to repeat, and inspect the run when it stops. Test it by moving the clock, not by waiting three days.

A signup form can be submitted twice, and a webhook can arrive twice. Start the onboarding run with a uniqueness key so the second request joins the first:

src/http/controllers/auth.rs
use dust::prelude::*;
use dust::workflow::Started;

pub async fn store(user: User) -> dust::Result<Redirect> {
    let started = OnboardUser { user_id: user.id }
        .start()
        .unique(format!("users.{}.onboarding", user.id))
        .attribute("tenant", "acme")
        .await?;

    if let Started::Existing(run_id) = started {
        tracing::info!(%run_id, "onboarding is already running");
    }

    Ok(Redirect::to("/dashboard"))
}

Idempotency is the second half of that promise. A crash between finishing external work and recording the result makes the step run again, so pass a stable key to the provider: workflow::current_step().key() combines the run ID and step name and survives retries. Use it as an Idempotency-Key header. Prefer storing IDs over models, which reload on every advance and can change while the run sleeps. A run releases its unique key when it ends, so a rejected expense can be resubmitted. Retries should match the failure: a timeout or a 429 is transient, so let the step retry or return workflow::retry_after with the provider's delay; a declined card is permanent, so wrap it in workflow::fatal and alert from the failed method. Compensations are ordinary steps: if the hotel booking fails, run a "cancel flight" step and return the original error.

Operators need a view. workflow:list filters with --status=failed, --name=users.onboard, and --attribute tenant=acme; workflow:show {id} prints the input, status, attributes, output or error, and every step's attempts and timing. workflow:retry {id} resumes a failed run at the failing step, workflow:cancel {id} stops an active one, and workflow:recover requeues runs whose wake-up job went missing. Schedule recover every few minutes and prune daily. When you are deciding what to build, choose the lightest tool: one task that runs once is a job, a fixed sequence is a chain, a fan-out with a callback is a batch, and logic that branches, sleeps, or waits for a webhook is a workflow. Work that repeats on a clock belongs to the scheduler.

Tests use the memory store and the sync queue. app.workflow(..) advances a run until it suspends or finishes, and app.travel moves the clock:

tests/onboarding.rs
#[dust::test]
async fn onboarding_sends_tips_when_user_has_no_projects(
    app: Application,
) -> dust::Result<()> {
    let mail = mail::fake();
    let user = User::factory().create().await?;

    let run = app.workflow(OnboardUser { user_id: user.id }).await;

    mail.assert_sent::<Welcome>();
    run.assert_sleeping();

    app.travel(3.days());
    run.advance().await;

    mail.assert_sent::<GettingStartedTips>();
    run.assert_completed();

    Ok(())
}
Move the clock, not the deadline

A test that waits three days is not a test. Travel to the wake-up time, advance the run, and assert the message or the step that should have happened.

Chapter 18

Pipeline & events

A pipeline composes one value through async stages; an event lets one fact reach many independent listeners.

A checkout has stages: validate the order, charge the card, save the result. A pipeline lets you write each stage once, test it alone, and compose them without turning the handler into a long sequence of calls. Events solve the other half of the problem: one fact, many independent reactions.

This chapter covers both. You will build a pipeline from small async steps, stop it early, carry errors, and test a stage without the rest. Then you will define an event, attach listeners, dispatch it, queue the slow work, and let the same event reach a browser.

Why a pipeline

In plain words

A pipeline is one value moving through a list of async steps. Each step can change the value, pass it on, or stop the rest.

The alternative is a handler that does everything in one body. It validates, charges, writes, and returns, and every new requirement makes the function longer. The stages are tangled together, so you cannot test the card charge without also constructing a valid order and a database row. A pipeline separates the stages without hiding them: each one is a named value you can read, replace, and test. Each pipe sees only the value it is given and the continuation it is handed, so it does not need to know which pipes came before it or which follow. That independence is what lets you move a stage, remove it, or test it without rewriting the rest.

The value type stays the same through every pipe, which is what makes the stages interchangeable. In the checkout below, both pipes receive an Order and return an Order. The final then is the one place that changes the shape of the result, turning the finished order into the boolean the caller asked for.

src/checkout.rs
use dust::pipeline::Pipeline;

pub async fn checkout(order: Order) -> dust::Result<bool> {
    Pipeline::send(order)
        .pipe(ValidateOrder)
        .pipe(ChargeCard)
        .then(|order| async move { Ok(order.charged) })
        .await
}

Use a pipeline when the stages are independent and run in order inside one request, command, or job. Reach for something else when the work is parallel, when the steps are really HTTP middleware, or when the work must survive a crash. The last case is a queued job or a workflow, not a pipeline. If there is only one step, call the function directly; a pipeline around a single call adds vocabulary without adding structure.

Same type, one direction

A pipe cannot change Order into a receipt. Keep the working value the same and let then produce the final result.

Writing pipes

In plain words

A pipe is a step with a simple shape: it receives the value and a continuation, then decides whether to continue.

The shortest pipe is a closure wrapped with pipe. The closure receives the current value and next; calling next(value).await runs the remaining pipes and returns their result. Work before the call happens on the way in, and work after it happens on the way out. Because the closure returns dust::Result<T>, you can use ? inside it like anywhere else.

src/checkout.rs
use dust::pipeline::{Pipeline, pipe};

pub async fn total() -> dust::Result<i32> {
    Pipeline::send(10)
        .pipe(pipe(|value, next| async move {
            println!("before: {value}");
            let value = next(value + 5).await?;
            println!("after: {value}");
            Ok(value)
        }))
        .then_return()
        .await
}

When a stage has dependencies, deserves a name, or is reused in more than one pipeline, implement Pipe for a struct. The trait's handle method receives the value and a Next<T> continuation, and returns a boxed future. Returning a box lets the trait work as a trait object, which is how the pipeline stores pipes of different concrete types in one list. Put the client, the clock, or the configuration on the struct; the value stays the only thing flowing through the pipeline.

src/checkout.rs
use dust::pipeline::{Next, Pipe};
use dust::Result;
use futures_util::future::BoxFuture;

pub struct Order {
    pub total: i32,
    pub charged: bool,
}

pub struct ChargeCard;

impl Pipe<Order> for ChargeCard {
    fn handle<'a>(&'a self, mut order: Order, next: Next<Order>) -> BoxFuture<'a, Result<Order>> {
        Box::pin(async move {
            order.charged = true;
            next(order).await
        })
    }
}

Prefer a closure for a small, local transformation and a struct for anything you want to name at the call site. Both are ordinary async code. A struct pipe can hold a client or a repository and still look the same at the call site; the difference is where the dependencies live, not how the pipeline runs. The closure must be Send + Sync + 'static, and the value must be Send + 'static, because the pipeline may be awaited on any worker thread.

next runs once

Next<T> is a boxed FnOnce. Call it at most once; a pipe that returns without calling it stops the remaining pipes.

Building and stopping

In plain words

send starts with a value, pipe adds a step, and then turns the finished value into the answer.

Pipeline::send creates the builder around the first value. Add one pipe with pipe, or add many with through and its alias pipes. Finish with then, which receives the value that came out of the last pipe, or then_return, which is the short form when the pipeline's value is already the result you want to return.

src/checkout.rs
use dust::pipeline::Pipeline;

pub async fn checkout(order: Order) -> dust::Result<bool> {
    Pipeline::send(order)
        .pipe(ValidateOrder)
        .pipe(ChargeCard)
        .then(|order| async move { Ok(order.charged) })
        .await
}

pub async fn saved(order: Order) -> dust::Result<Order> {
    Pipeline::send(order).pipe(ValidateOrder).then_return().await
}

A pipe that returns without calling next stops the remaining pipes, but its value still reaches then. That is how a pipeline skips work that is not needed. In the example below, an unverified user never reaches the order lookup; the final destination still runs and returns the user's existing orders. This is a return, not an error: no failure is reported, and the caller sees an ordinary result.

src/checkout.rs
use dust::pipeline::{Pipeline, pipe};

pub async fn checkout(user: User) -> dust::Result<Vec<Order>> {
    Pipeline::send(user)
        .pipe(pipe(|user, next| async move {
            if user.email_verified {
                next(user).await
            } else {
                Ok(user)
            }
        }))
        .pipe(pipe(|user, next| async move { next(load_orders(user).await?).await }))
        .then(|user| async move { Ok(user.orders) })
        .await
}

When the list of pipes is built at runtime, or when the pipes have different concrete types, collect them as Box<dyn Pipe<T>> and pass them to through. A boxed Pipe is still a Pipe, so the builder accepts it. For a one-off pipe, prefer pipe: it keeps the concrete type and avoids an allocation and a trait object you did not need. The concrete type is also easier to read in a compiler error, so keep it unless the collection is genuinely dynamic.

src/checkout.rs
use dust::pipeline::{Pipe, Pipeline};

pub async fn checkout(order: Order) -> dust::Result<Order> {
    let pipes: Vec<Box<dyn Pipe<Order>>> = vec![Box::new(ValidateOrder), Box::new(ChargeCard)];

    Pipeline::send(order).through(pipes).then_return().await
}
Nothing runs until you await

The builder only collects pipes. The work starts when then or then_return is awaited, so an unawaited pipeline does nothing at all.

Errors and testing

In plain words

Every pipe returns a result. The first error stops the rest and travels back unchanged, so a failure has one clear path.

Pipes return dust::Result<T>, so ? works as usual. When a pipe returns an error, the remaining pipes are skipped, the destination does not run, and the caller receives that error. Add context where the error crosses a boundary, exactly as you would in a handler. The context says what the code was doing, not what the database called the constraint. Because the pipeline returns the framework's ordinary result type, the caller handles a failed pipeline exactly like a failed handler: report it, turn it into a response, or add context at the edge.

src/checkout.rs
use dust::ErrorContext as _;
use dust::pipeline::{Pipeline, pipe};

pub async fn checkout(order: Order) -> dust::Result<Order> {
    Pipeline::send(order)
        .pipe(pipe(|order, next| async move {
            let order = validate(order).with_context(|| "while validating the order")?;
            next(order).await
        }))
        .then_return()
        .await
}

Pipelines are ordinary async functions, so test them with #[tokio::test] or inside a #[dust::test] application test. Assert the order the pipes ran in, the value each pipe received, and the short-circuit case. The test below drives the whole composition and checks the value that came out of the last stage.

tests/checkout.rs
#[tokio::test]
async fn the_order_is_validated_before_it_is_charged() {
    let result = Pipeline::send(order)
        .pipe(ValidateOrder)
        .pipe(ChargeCard)
        .then_return()
        .await
        .unwrap();

    assert!(result.charged);
}

To test one stage in isolation, call its handle method with a Next continuation you control. The continuation can record the value it received, return a fixed error, or set a flag; the stage under test never needs the pipes that usually follow it. That is the point of keeping each pipe a separate value: a test can exercise the charge without a database, or the validation without a card.

tests/checkout.rs
use dust::pipeline::{Next, Pipe};

let next: Next<Order> = Box::new(|order| Box::pin(async move { Ok(order) }));
let order = ChargeCard.handle(order, next).await?;

assert!(order.charged);
Test the stop, too

Make the next continuation set a flag, return early from a pipe, and assert the flag never changed. A short-circuit is behaviour, so it deserves a test.

Events and listeners

In plain words

An event is a fact that already happened. A listener is a reaction to it. Dispatch is how the application announces the fact.

An event is a plain struct that derives Event. Name it after the fact, in the past tense: OrderPlaced, InvoicePaid, UserVerified. An event should describe what happened, not what should happen next; the listeners decide the next step. Store owned values such as String, because the event may outlive the request that created it, and give every field a listener might need. New applications keep events in src/events/. The example also derives Queueable, because one of its listeners will run on the queue; an event with only inline listeners needs Event alone.

src/events/order_placed.rs
use dust::event::Event;
use dust::queue::Queueable;

#[derive(Event, Queueable)]
pub struct OrderPlaced {
    pub order_id: i64,
    pub email: String,
    pub total: i64,
}

A listener is an async function marked with #[listener]. Its first parameter is Event<T>, which dereferences to your event, so event.email reads a field directly. It returns () or dust::Result<()>, and it may take Inject<T> services and Section<T> config sections after the event. dust discovers tagged listeners in the application's library crate at boot; a package opts in with events.discover(env!("CARGO_CRATE_NAME")), and a manual listener is registered with events.listen inside with_events.

src/listeners/send_receipt.rs
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(())
}

Call dispatch on an event instance to notify its listeners. The call runs the inline listeners sequentially, in registration order, and resolves once they all finish; the first error stops the remaining listeners and is returned to the caller. When the request does not need to wait, dispatch_background starts the listeners in a background task and returns immediately. Background events live only in memory, so they are not retried and can be lost on a restart. Slow listeners belong on the queue instead: the event also derives Queueable, and marking the listener #[listener(queued)] makes dispatch push a Queued<L> job that holds the event, while a worker runs the listener later. Queue options such as queue, tries, backoff, connection, and delay are available on the attribute. Inline and queued listeners can coexist: the inline ones still run during dispatch, while the queued ones succeed or fail independently.

src/http/orders.rs
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)
}
src/listeners/send_receipt.rs
use dust::event::{Event, listener};
use dust::mail;

use crate::events::OrderPlaced;
use crate::mail::OrderReceipt;

#[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(())
}

Broadcasting is the same event reaching a browser. Add a channel to the event with #[event(broadcast(private = "orders.{order_id}"))]. Dispatching then publishes the event on private-orders.42 and still runs every listener. The payload is built from the event's pub fields; private and pub(crate) fields are omitted, and every public field in the payload must implement Serialize. Delivery goes through the queue by default, waits for a database transaction to commit, and is discarded on rollback. The Real-time chapter covers the Relay connection, channels, and the browser side.

src/events/order_shipped.rs
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,
}
One event, several reactions

Do not grow the order handler with every new side effect. Dispatch the fact once and let each listener own its reaction; queued listeners keep the slow ones off the request path.

Chapter 19

Cache, Redis & search

Keep expensive answers close, share them across servers, and let readers find the rows that matter.

Some work does not need to happen twice. A user count, a rendered report, a call to a rate-limited API: the answer is the same for a while, so the application can store it and read it back. That is a cache. Redis is the shared home many applications give that data, and search is the same idea turned around: instead of storing an answer for later, you build an index that makes finding it fast.

You will start with the cache API and its stores, use it for expensive queries and locks, then meet Redis as a connection you can also use for sessions and queues. The last pages make a model searchable, choose an engine, and keep the index honest as rows change.

Cache stores and the API

In plain words

A cache is a named shelf for values you can rebuild. The store decides where the shelf lives; the API stays the same.

CACHE_STORE selects the default store. memory lives inside each process and disappears on restart. database keeps values and locks in the cache and cache_locks tables, so every server shares them. redis uses a Redis connection and lets Redis expire keys. failover tries database, then memory, while discard stores nothing and makes every read miss. New applications default to database:

.env
CACHE_STORE=database

CACHE_PREFIX is prepended to every key so applications sharing a store do not collide. It defaults to a name derived from the application, such as my_app_cache_. The calls are typed and small: get returns Option<T>, has checks a key, put stores a value for a duration, and remember reads or computes and stores in one step. Values are JSON, so any Serialize type can be written and any Deserialize type read back. This counts users at most once every ten minutes:

src/http/dashboard.rs
use dust::cache;
use dust::prelude::*;

use crate::models::User;

pub async fn show() -> dust::Result<String> {
    let users: u64 = cache::remember("users:count", 10.minutes(), async || {
        User::query().count().await
    })
    .await?;

    Ok(format!("{users} users"))
}
Gotcha

get errors when stored JSON no longer matches the requested type, while remember and flexible treat that as a miss and recompute. An entry is never a guarantee: it can expire, be evicted, or vanish on restart. Every read must be correct when the value is missing.

Cache patterns and locks

In plain words

Cache the result, not the request. When the result is expensive, make sure only one process recomputes it.

remember takes a key, a lifetime, and a closure returning dust::Result, so you can use ? inside. If the value is present the closure never runs; if it fails the error returns and nothing is cached. Use it for a report, a settings blob, or a count whose answer changes slowly, and keep the lifetime as short as the product allows. Version the key when the cached value's shape changes.

The weakness is the stampede: when a hot key expires, every concurrent miss runs the closure. cache::flexible serves the stale value immediately and refreshes it in the background between its fresh and stale deadlines. An atomic lock is stricter: only the owner runs the work. Locks on database or redis are shared across servers; a memory lock coordinates only within one process.

src/http/reports.rs
use dust::cache;
use dust::prelude::*;

let lock = cache::lock("reports", 10.seconds())?;

if lock.acquire().await? {
    // Generate the report...

    lock.release().await?;
}

Prefer lock.get with a closure: it acquires, runs, and releases even when the callback errors or the request is cancelled, and returns None if someone else holds the lock. block(5.seconds()) waits instead and fails with LockTimeout — a 423 Locked response — when time runs out. A lock taken with acquire must be released explicitly; dropping it or panicking does not release it. forget removes one key and flush empties the store. From the console, dust cache:clear flushes a store, while dust cache:prune removes expired database rows on demand. Flushing ignores the prefix, and cache:clear cannot reach a running process's memory store.

Gotcha

Never release a lock you did not take, and never let one outlive its usefulness. lock.get protects you from cancellation; a bare acquire does not. If the work can exceed the lock's duration, refresh the lock or split the work.

Redis

In plain words

Redis is a shared, in-memory key-value server. The framework gives it names, connections, and typed commands, then uses it wherever processes need the same fast state.

Redis support is a Cargo feature, off by default. Enable redis and the dust::redis module is compiled; the same feature lets the cache, sessions, and queues keep their data in Redis. Use it for shared caches, counters, leaderboards, rate windows, locks, sessions, and job queues. Keep records you cannot afford to lose in your database.

Cargo.toml
[dependencies]
dust-framework = { version = "0.1", features = ["redis"] }

Two connections exist by default: default, which most code uses, and cache, which the cache store uses. Both read REDIS_URL and default to redis://127.0.0.1:6379. The default connection uses database REDIS_DB (0); the cache connection uses REDIS_CACHE_DB (1), so clearing the cache does not erase application data. Add another named connection in src/config/redis.rs when needed, and look it up cheaply with redis::connection("reports")?.

Everyday commands have typed helpers: strings and keys, hashes, lists, sets, and sorted sets. A missing key returns None or an empty collection. For anything not wrapped, import Commands and call it on redis::default_connection()?. This increments a post's view counter:

src/http/posts.rs
use dust::prelude::*;
use dust::redis;

pub async fn view(Params(id): Params<i64>) -> dust::Result<Json<isize>> {
    let views = redis::incr(format!("post:{id}:views"), 1).await?;

    Ok(Json(views))
}

Pub/Sub broadcasts to every listener on a channel: publish accepts any Serialize value, and subscribe returns a stream of messages. Subscriptions belong in a long-running console command and do not buffer; messages published during a reconnect are lost, so use a queue when delivery must be guaranteed. Set CACHE_STORE=redis for caching and select Redis in the session and queue configuration. Redis adds no application prefix, so give production and staging separate databases.

Gotcha

A Redis Cluster supports only database 0, has no Pub/Sub, and requires keys used together to share a hash slot. Group them with a hash tag such as {user:42}:name. Blocking commands need dedicated(), or they stall every request on the shared connection.

Search engines and indexes

In plain words

The model and the query stay the same. The engine decides where the index lives and what kind of matching it can do.

The default is database: no extra service, always current, filters on real columns, but no typo tolerance and only substring scans. Meilisearch and Typesense are dedicated servers with typo tolerance, highlighting, and embedders. Turbopuffer is hosted on object storage for very large namespaces. discard stores nothing, finds nothing, and is safe for staging servers that share production data. Switching engines changes the environment, not your model marks or handlers.

Enable the search Cargo feature alongside your database feature, then set SEARCH_ENGINE and the service credentials. Meilisearch needs a host and, unless the server runs without a master key, a key. Typesense needs a host, port, protocol, and API key. SEARCH_PREFIX prepends text such as staging_ to every index name and sync lock so environments sharing a service do not collide.

.env
SEARCH_ENGINE=meilisearch
MEILISEARCH_HOST=http://127.0.0.1:7700
MEILISEARCH_KEY=masterKey
.env (Typesense)
SEARCH_ENGINE=typesense
TYPESENSE_HOST=localhost
TYPESENSE_PORT=8108
TYPESENSE_PROTOCOL=http
TYPESENSE_API_KEY=xyz

Indexes are managed from the console:

console
$ dust search:index
$ dust search:import Post
$ dust search:flush Post

search:index creates missing indexes and pushes the settings derived from your marks; pass Post to do one model. search:import Post upserts every row returned by indexed in chunks of 500, and --fresh clears first. search:flush removes every document without re-importing, while search:delete-index Post deletes the index and succeeds even when it is already gone. Meilisearch requires search:index before filtering or sorting; Typesense creates a collection on first write; Turbopuffer applies its schema on every write; database reports that there is no separate index.

Gotcha

Typesense and Turbopuffer cannot change the type of an existing field. After changing a marked field's Rust type, run search:delete-index, search:index, then search:import. Running search:index again when nothing changed is safe, so a deploy script can include it unconditionally.

Keeping search in sync

In plain words

The write is the source of truth. Sync the index after it commits, and repair the index from the table when something was missed.

When a searchable model is written with create!, update!, delete, or destroy, the framework syncs the row after the transaction commits; a rollback syncs nothing. An update syncs only when it changes a marked field or the primary key, unless the model defines indexed or embedding_input, which makes it sync on every update. Override needs_reindex to decide yourself. If the search service is down, the database write still succeeds: the sync error is reported, not returned.

Bulk operations skip model events, and therefore skip syncing. A query-based update, insert, or upsert must be followed by search::sync with the same query. It re-reads rows through indexed, upserts those that still match, and removes keys that no longer exist or no longer match. For a bulk delete, load the rows first, delete them, then pass the loaded models so their keys are removed. To pause syncing while writing many rows, wrap the writes in search::without_syncing and import afterward.

src/console/archive.rs
use dust::search;

Post::query()
    .filter(Post::author_id.eq(author.id))
    .update()
    .published(false)
    .await?;

search::sync(Post::query().filter(Post::author_id.eq(author.id))).await?;

In production, set SEARCH_QUEUE=true so syncs run as queued jobs. The framework debounces repeated edits to a row for five seconds, retries a failing sync up to ten times, and locks each row in the default cache so an older sync cannot overwrite a newer one. That is why production needs a shared cache store such as database or redis. A deploy that adds the feature or changes marks runs dust search:index, then dust search:import Post, optionally with --fresh; the same import repairs rows missed during an outage. Move from database to a dedicated engine when readers expect typo tolerance, when row counts grow into the millions, or when substring scans dominate request time. Choose discard for staging when the extra service costs more than the product needs, and keep tests that assert on ranking against the engine you run in production, because each engine ranks differently even for the same query.

Gotcha

Queued syncs need a shared cache for debouncing and row locks, and Meilisearch applies writes asynchronously. A post saved a second ago may not appear immediately. Do not hide that with a retry loop in the handler; run search:import when the index needs rebuilding.

Chapter 20

Feature flags, client & console

Three kinds of work that sit beside the request: a flag that remembers a decision, a client that calls another server, and a command that runs without a browser.

Not everything begins with an HTTP request. A rollout has to decide who sees a new screen, an order has to reach a payment provider, and a nightly import has to run from a terminal or a scheduler. None of those is a route, yet all of them need the application's configuration, models, and services.

This chapter covers the three tools for that work. Feature flags make a decision once per user, team, or application and remember it. The HTTP client sends requests to other services with timeouts, retries, and testable failures. Console commands run the same application from a command line, with typed arguments and a real exit code.

Feature flags

In plain words

A feature flag is a named decision: should this user, this team, or everyone see the new thing? The decision is made once and stored, so the answer does not change on the next request.

Without flags you enable a feature by deploying it, and every user gets it at the same moment. A flag separates the deploy from the rollout. You can give a new API to staff first, then one customer in a hundred, and finally everyone, without another release at each step. The same mechanism runs A/B experiments, because a flag can return a value richer than yes or no.

Define a flag by annotating a function with #[flag]. The function receives the scope it decides for and returns the first value. Here the new API is on for staff and for one percent of everyone else:

src/features.rs
use dust::feature::flag;
use dust::lottery::Lottery;

use crate::models::User;

#[flag]
pub fn new_api(user: &User) -> bool {
    user.is_staff || Lottery::odds(1, 100).draw()
}

The function runs on a user's first check and the result is stored, so each user gets one lottery draw and keeps that outcome. The attribute also creates a unit struct with the same name; a misspelled name fails at compile time. Import the module and write features::new_api, because a local let new_api binding would collide with that struct.

Call .features() on the scope, then active or value. User models support it automatically. In a handler, extract Authenticated<User> and branch on the answer:

src/http/servers.rs
use dust::prelude::*;

use crate::features;
use crate::models::User;

pub async fn index(user: Authenticated<User>) -> dust::Result<Response> {
    if user.features().active(features::new_api).await? {
        return servers::v2::index().await;
    }

    servers::v1::index().await
}

Teams work the same way once Team implements HasFeatures, whose feature_key returns a permanent scope kind and the team's id, as in ScopeKey::new("Team", self.id); then team.features().active(features::billing_v2).await? answers for the whole team. A flag written for &Team cannot be checked on a User: the scope is part of the type. A flag with no parameter is application-wide, and one that accepts Option<&User> also evaluates for guests.

A rollout guard, not a permission

Hiding a button does not protect the route behind it. Check the flag in the handler or attach RequireFeature, and enforce who may do the action with a policy. A user who cannot see the button can still call the URL.

Rollouts and storage

In plain words

Flags need a place to keep their answers. By default that place is a features table in your database, so every server agrees and a deploy does not reset the rollout.

Choose the store with FEATURE_STORE: database is the default, and memory keeps values in each process and forgets them on restart. Use DB_FEATURE_CONNECTION to point at another connection and DB_FEATURE_TABLE to rename the table. The memory store is what tests use and what an application without a database falls back to; across several servers, each process would hold a different answer. The table is not created for you: add a migration that calls the macro, which is the whole file:

database/migrations/2026_01_01_000000_create_features_table.rs
dust::feature::table!();

It creates id, name, scope, value, and timestamps, with a unique index on name and scope. Keep that index if you write the migration by hand: two simultaneous first checks for the same user must converge on one row, not insert two. The store keeps resolved values, so a percentage rule runs once for each new scope and is never re-rolled. Not every flag is a boolean. Return Option<T> when an experiment has variants: Some(value) is active with that variant, None is off, and the value must implement Serialize, Deserialize, and Clone. Read it with value; a rich flag stores JSON, such as "seafoam-green", and a value that no longer deserializes makes the function run again.

You can move a single scope without waiting for a new draw. activate turns a boolean flag on, activate_with stores a rich value, deactivate turns it off, and forget deletes the row so the next check runs the function again. Call them on the scope: user.features().activate(features::new_api).await?. When a rollout is finished, feature::everyone() updates every stored row for that flag at once. It only touches scopes already checked, so someone who arrives tomorrow still gets whatever the function returns; change the function too when you finalize. To clean up, purge by stored name:

console
$ dust feature:purge new_api purchase-button
$ dust feature:purge --except-defined

With no names, feature:purge removes every stored feature, so defined flags are computed again on their next check. --except keeps names you list, and --except-defined removes only flags no longer in the code, which makes it a good deployment step after a deletion.

Purge is per flag, not per user

feature:purge new_api deletes every stored value of that flag, not one user's row. Use forget to reset one scope. When you rename a flag function, set #[flag(name = "new_api")] so the old rows are not orphaned.

The HTTP client

In plain words

To call someone else's API, start with a verb, chain what the request needs, and await it. The response is already in memory when you get it back.

All client functions live in dust::http::client. Start with get, post, put, patch, delete, or head; awaiting sends the request and reads the whole body. A 404 or 500 still arrives as Ok(response), and ? fails only when the request could not be sent at all.

src/services/github.rs
use dust::http::client;
use serde_json::json;

let response = client::get("https://example.com/users").await?;

client::post("https://example.com/users")
    .headers([("x-tenant", "acme"), ("x-locale", "en")])
    .header("idempotency-key", "user-1234")
    .json(json!({ "name": "Taylor" }))
    .await?;

json serializes any Serialize value into the body. query appends parameters from pairs, a json! object, or a struct, skipping None fields, and accept_json sets Accept:

src/services/github.rs
client::get("https://example.com/users")
    .query([("name", "Taylor"), ("page", "2")])
    .accept_json()
    .await?;

On the response, status compares with integers, while successful, failed, client_error, and server_error name the class. text returns the body as a string and json::<T>() deserializes it; both are synchronous because the body is buffered. Timeouts are on by default: 30 seconds for the full response and 10 seconds to connect. Override one request with .timeout(3.seconds()). Retries are opt-in: pass the maximum attempts and a fixed or exponential delay, and cap the whole sequence when the handler has a latency budget. Only retry idempotent work, or a request protected by an idempotency key: a retry sends the same request again. When a 429 or 503 carries Retry-After, the client waits at least that long if it fits the budget, and stops immediately if it does not.

src/services/github.rs
use dust::http::client::{self, Backoff};
use dust::prelude::*;

client::get("https://api.github.com/users/taylorotwell")
    .timeout(2.seconds())
    .retry(5, Backoff::exponential(200.milliseconds()))
    .total_timeout(5.seconds())
    .await?;

Failures are one enum. Error::Connection means no response arrived: unreachable host, TLS problem, or timeout. Error::Status means a non-2xx response after ensure_successful or a retry, and error.response() lets you inspect it. Error::Decode means json() did not match the type, and Error::Invalid means the request could not be built. Match when you can recover, and convert the rest with ?.

404 is not an error until you say so

By default a 404 is a successful round trip with a 404 status. Add .ensure_successful() when any non-2xx should become Error::Status; from a handler, that becomes a reported 500 naming the URL and the start of the body.

The client in practice

In plain words

When several places call the same API, build the request once. Keep the token in configuration, parse the answer into a type, and fake the network in tests.

Repeating the base URL, token, and error policy at every call site invites drift. Build a PendingRequest template with client::base_url, then call get and post with relative paths. The template carries the shared headers, the bearer token, and ensure_successful:

src/services/github.rs
use dust::config::Section;
use dust::http::client::{self, PendingRequest};
use dust::prelude::*;
use serde_json::json;

use crate::config::services::GitHub;

fn github(config: &GitHub) -> PendingRequest {
    client::base_url("https://api.github.com")
        .token(&config.token)
        .accept_json()
        .ensure_successful()
}

pub async fn show(config: Section<GitHub>) -> dust::Result<Json<serde_json::Value>> {
    let github = github(&config);

    let user: serde_json::Value = github.get("/user").await?.json()?;

    let repositories: serde_json::Value = github
        .get("/user/repos")
        .query([("per_page", 100)])
        .await?
        .json()?;

    Ok(Json(json!({ "user": user, "repositories": repositories })))
}

The token comes from a Section, not a literal in the source. Declare a field such as #[env("GITHUB_TOKEN", required)] and inject the section into the handler; the value stays in the environment while the code stays readable. Parsing into a struct is the difference between a demo and production code:

src/services/github.rs
use serde::Deserialize;

#[derive(Deserialize)]
pub struct GitHubUser {
    pub login: String,
    pub name: String,
}

let user: GitHubUser = github.get("/user").await?.json()?;

println!("{} ({})", user.name, user.login);

Handlers are not special. A queued job, a console command, and a listener may send requests the same way, because the client belongs to the application rather than to the request. Put the call in one async function and call it from each place. If the work does not need the response, task::background can run it after the handler returns; the framework waits for it before the process exits.

Tests never need the network. client::fake() intercepts outgoing requests and returns an empty 200 by default. Add matches with .with(..), using patterns that match anywhere in the URL and support *:

tests/profile.rs
use dust::http::client;
use dust::testing::prelude::*;
use serde_json::json;

#[dust::test]
async fn shows_a_github_profile(app: Application) {
    let http = client::fake().with(
        "api.github.com/users/*",
        json!({ "login": "taylorotwell", "name": "Taylor Otwell" }),
    );

    app.get("/profile").await.assert_ok();

    http.assert_sent_count(1);
}
The fake sees your client, not everyone's

Keep the handle alive while the test runs; dropping it restores live requests. For a failure path, client::failed_connection() returns Error::Connection, and client::sequence() returns different answers across attempts, which is how a retry is tested. prevent_stray_requests turns an unexpected URL into a failure instead of a silent empty 200. A third-party SDK that builds its own HTTP client bypasses the fake entirely; wrap it in a service you can replace in tests.

Console commands

In plain words

A console command is an async function with a name, typed arguments, and a console to write to. It runs in the same application as a request, without the request.

New applications put each command in its own file under src/console/. Annotate an async function with #[command("name")]; its parameters become the command line, parsed by clap. A trailing &mut Console gives it output and prompts, and is not parsed as an argument:

src/console/posts.rs
use dust::console::{Console, command};
use dust::model::update;

use crate::models::Post;

/// Publish a draft post.
#[command("posts:publish")]
pub async fn publish_post(
    /// The ID of the post to publish.
    id: i64,
    /// Publish the post again if it's already published.
    #[arg(long)]
    force: bool,
    console: &mut Console,
) -> dust::Result<()> {
    let mut post = Post::find_or_fail(id).await?;

    if post.published_at.is_some() && !force {
        console.info(format!("Post `{id}` is already published."));

        return Ok(());
    }

    update!(post { published_at: dust::now() }).await?;

    console.success(format!("Post `{id}` published."));

    Ok(())
}

The doc comment becomes the description in dust list and --help. A plain parameter is positional; #[arg(long)] makes a named option, #[arg(short, long)] adds a one-letter form, and default_value_t supplies a default. Vec<T> accepts repeated values, Option<T> makes one optional, and snake-case names become kebab-case flags. This version accepts several IDs and a minimum vote count:

src/console/posts.rs
/// Publish draft posts.
#[command("posts:publish")]
pub async fn publish_posts(
    /// The IDs of the posts to publish.
    #[arg(required = true)]
    ids: Vec<i64>,
    /// Publish posts that are already published again.
    #[arg(short, long)]
    force: bool,
    /// Publish only the posts with at least this many votes.
    #[arg(long, value_name = "VOTES", default_value_t = 0)]
    min_votes: i64,
    console: &mut Console,
) -> dust::Result<()> {
    // ...

    Ok(())
}

Run it as dust posts:publish 3 7 12 -f --min-votes=10. The function may also accept Inject<T> services, Section<T> config, and &Application; injected parameters are excluded from parsing. Import clap through dust::console rather than adding a second clap dependency. Output has two streams: status messages go to stderr as info, warn, error, step, or success, while primary output goes to stdout as line, new_line, or table.

Every command accepts --quiet and repeated -v; use verbose, very_verbose, and debug for detail that should not print by default. An exit code is part of the interface. Returning () or Ok(()) exits 0; return u8 or dust::Result<u8> to choose a code. An Err or panic prints to stderr, reports through the error handler, and exits 1; a cancelled prompt exits 130.

A bool is a switch, not a value

bool with #[arg(long)] takes no value. When an option needs one, use Option<T> or a concrete type. A bool switch never consumes the next word, so --force true treats true as another argument.

Testing and scheduling commands

In plain words

Run the command line in a test and assert what it printed and what it returned. Put the command in the schedule when it should run without a person.

app.command takes the part after dust and runs it in the test's process. The result captures stdout and stderr separately, so you can assert on the sentence a person would see and on the exit code:

tests/console.rs
use dust::model::create;
use dust::testing::prelude::*;

use app::models::{Post, User};

#[dust::test]
async fn it_publishes_a_post(app: Application) -> dust::Result<()> {
    let user = create!(User {
        name: "Taylor",
        email: "taylor@example.com",
        password: "password",
    })
    .await?;

    let post = create!(Post {
        title: "My first post",
        user: &user,
    })
    .await?;

    app.command(&format!("posts:publish {}", post.id))
        .await
        .assert_successful()
        .assert_error_output_contains("published.");

    Ok(())
}

assert_output_contains checks stdout, where line and table write; assert_error_output_contains checks stderr, where status messages, notes, and progress write. assert_no_output and assert_exit_code cover the other direction. Use app.command_args(["posts:publish", "42", "--force"]) when an argument must be passed exactly, and script prompts in order with expects_question, expects_password, and expects_confirmation.

To make a command recurring, register it in the schedule rather than a server crontab. The schedule lives in src/console/mod.rs and ships with the application. command takes a full command line and splits it with shell-like quoting, without invoking a shell:

src/console/mod.rs
use dust::schedule::{self, Schedule};

#[schedule::tasks]
fn schedule(schedule: &mut Schedule) {
    schedule.command("emails:send Taylor --force").daily_at("08:00");
    schedule.exec("node").args(["scripts/report.js"]).hourly();
}

When an argument is computed at runtime, append it with args so spaces, quotes, and $ need no escaping. Use exec for an external program, and shell for pipes or redirects; only pass shell trusted strings, never user input. Command functions are discovered from the app crate when their module is declared with mod; a command struct needs commands.add::<PublishPost>() in with_commands. Scheduled commands are tested with the same app.command(..) call, since the scheduler only decides when to run them.

Tests run the real command

There is no fake process. A command that writes a file or changes a row does so in the test. That is usually what you want to assert, but it means serve cannot run in a test, and a destructive command should be pointed at test data.

Chapter 21

Supervisor & Relay

The supervisor keeps the programs that outlive a request running, and Relay carries your broadcasts to the browser while you build them.

A web request ends. A queue worker does not. Some of an application's work has to stay alive for hours, keep its place in a queue, and come back after a crash. The supervisor is the small daemon that owns those processes so the application does not have to.

Relay is the other long-running piece: a WebSocket server for local development that speaks the Pusher protocol. It lets you watch an event leave a handler and arrive in a browser without signing up for an external service.

What the supervisor does

In plain words

The supervisor is a process whose only job is to run other processes and start them again when they stop.

A program is a console command that must keep running, such as queue:work. The supervisor runs workers copies of that command, each in its own process. Every half second it checks whether a child exited, logs the exit status, and starts it again after a short delay.

The configuration is a TOML file with one top-level section and one [[program]] block per kind of worker. Every application starts with the queue worker:

config/supervisor.toml
binary = "dust-demo"

[[program]]
name = "queue"
command = "queue:work"
args = ["--queue=default"]
workers = 1
restart = true

dust install starts the supervisor after the migrations, so a deploy does not need a systemd unit for each worker. The supervisor runs the application binary once per worker, and supervisor:status reports each worker's PID, CPU, memory, and restart count.

It is not the web server

The supervisor does not answer HTTP requests. It keeps workers alive next to the server; the server itself still runs under systemd or your process manager.

Configuring programs

In plain words

Describe each worker once: what to run, how many copies, and whether to restart it. The command is the same one you would type by hand.

The supervisor reads config/supervisor.toml at startup. The top level sets the binary and the shared timing; each [[program]] describes one kind of worker. binary is required, and the supervisor looks for it in bin/; an unbuilt binary stops the daemon with an error.

config/supervisor.toml
binary = "dust-demo"
log = "storage/logs/supervisor.log"
grace_seconds = 25
restart_seconds = 1

[[program]]
name = "queue"
command = "queue:work"
args = ["--queue=default"]
workers = 1
restart = true

[[program]]
name = "mail"
command = "queue:work"
args = ["--queue=mail", "--concurrency=4"]
workers = 2
env = { QUEUE_CONNECTION = "redis" }

name is what supervisor:status shows and supervisor:restart accepts. args are passed after the command exactly as written, so the worker keeps its own options: --queue, --concurrency, --sleep, and --timeout. workers is how many copies run at once; restart = false lets a program exit without being brought back, which suits a one-shot job.

env adds environment variables for that program only, as a table of names and values. grace_seconds is how long a stopping process has before it is killed, and restart_seconds is the wait before a crashed program is started again. Two programs with the same name, or a program without a command, stop the supervisor with a named error.

The file is read at startup

After you edit a program's definition, stop and start the supervisor so the daemon loads the new file. A running daemon keeps the settings it read when it started.

Running and inspecting

In plain words

Start it once, ask for its status when something looks slow, and restart only the program you changed.

Five commands cover the whole life of the daemon. dust install already starts it; you run these when you need to look or intervene.

console
$ dust supervisor:start
$ dust supervisor:status
running, pid 214176
queue: 1 worker(s)
  worker 0: pid 214211, cpu 0.4%, 62.7 MB, 0 restart(s), started 2026-12-03T06:01:44Z
$ dust supervisor:programs
$ dust supervisor:stop

The daemon samples each worker's CPU time and resident memory from /proc every two seconds and writes them to storage/framework/supervisor.json. supervisor:status reads that file; dust status shows the supervisor's total CPU and memory next to the database, queue, cache, cron, and relay.

supervisor:programs lists every configured program, running or not, with its command, its worker count, how many are running, and its totals. supervisor:restart without a name restarts every program; with a name it restarts only that one, and the others keep working.

console
$ dust supervisor:restart mail
$ dust supervisor:restart
$ dust supervisor:programs
CPU is a rate, not a total

The percentage is measured between two samples, so a worker started moments ago reads 0.0% until the next sample. Memory is the process's resident set from /proc.

Graceful shutdown

In plain words

Stopping is a process: stop taking new work, finish what is already running, then exit before the process manager loses patience.

When your process manager stops the server with SIGTERM, or you press Ctrl+C, the server stops accepting new connections and gives in-flight requests time to finish. SERVER_SHUTDOWN_TIMEOUT controls how long it waits and defaults to 20 seconds. A request still running when the timeout expires receives a 503 response.

.env
SERVER_SHUTDOWN_TIMEOUT=15

During shutdown, event streams close immediately so browsers reconnect to the new instance. Ticks stop scheduling new runs, and any tick marked run_on_shutdown executes one final time after active requests and managed background work finish. The goal is to finish work already accepted, not to accept more.

The timeout only helps if the process manager waits longer than it. In the systemd unit, TimeoutStopSec must be larger than SERVER_SHUTDOWN_TIMEOUT; systemd sends SIGKILL when its own timer expires. The supervisor has a matching setting for workers: grace_seconds defaults to 25, and a queue:work process stops taking jobs immediately and finishes the one it is running.

/etc/systemd/system/example-app.service
[Unit]
Description=example-app
After=network.target

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/srv/example-app
EnvironmentFile=/srv/example-app/.env
ExecStart=/srv/example-app/bin/example-app
Restart=always
RestartSec=1
KillSignal=SIGTERM
TimeoutStopSec=25

[Install]
WantedBy=multi-user.target
Longer, not equal

If TimeoutStopSec matches or beats the shutdown timeout, systemd kills the server while it is still draining. Leave a few seconds of margin.

Relay

In plain words

Relay is a WebSocket server on your machine. Your application publishes events to it, and Echo in the browser listens on channels.

Relay is for local development. It implements the Pusher protocol, so Echo, pusher-js, and other Pusher-compatible clients connect without custom adapters. Enabling it is a Cargo feature, off by default so applications that do not broadcast do not compile its dependencies:

Cargo.toml
[dependencies]
dust-framework = { version = "0.1", features = ["database-postgres", "redis", "sqs", "relay"] }

Relay and your application must share three credentials. Put them in .env, switch the broadcast connection to relay, and tell the application where Relay listens:

.env
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=http

Start the server with dust relay:start. It listens on 0.0.0.0:8080 by default, prints the WebSocket URL, and closes open connections on Ctrl+C. --host, --port, and --path override the address for one run, and --debug prints connections, subscriptions, whispers, published events, and protocol errors.

console
$ dust relay:start
$ dust relay:start --host=127.0.0.1 --port=9000
$ dust relay:start --debug

In the browser, install Echo's React bindings and configure it once. Only the application key belongs in the browser; RELAY_APP_SECRET stays on the server. Then subscribe with useEcho using the channel and event names your Rust code broadcasts.

console
$ npm install @dust/echo-react dust-echo pusher-js
frontend entry
import { configureEcho } from '@dust/echo-react';

configureEcho({
    broadcaster: 'relay',
    namespace: false,
});
A missing worker looks like a missing event

Broadcasts are queued by default. If an event never arrives, check that a queue worker is running before you suspect Relay; start one with dust queue:work.

Relay in production

In plain words

In production you stop running the local server and point the same credentials at managed Relay. Your channels, events, and browser code stay as they are.

relay:start is a development server. It runs in a single process, keeps every connection and channel in memory, and does not scale across multiple servers. In production, use managed Relay on DUST Cloud, which handles TLS and scaling for you.

What changes is configuration and process management. Point RELAY_APP_ID, RELAY_APP_KEY, RELAY_APP_SECRET, RELAY_HOST, RELAY_PORT, and RELAY_SCHEME at your Cloud Relay cluster, and stop running relay:start; there is no local dust-relay unit to keep alive. The application publishes to the cluster without the relay Cargo feature.

What does not change is the application. Events keep their #[event(broadcast(...))] attributes, channel authorization stays in src/routes/channels.rs at POST /broadcasting/auth, one-off broadcasts keep their names, and Echo keeps its useEcho, useEchoPublic, and useEchoPresence calls. Public, private, and presence channels behave the same because the protocol is the same.

If you must run your own server for a small self-hosted deployment, run relay:start as a foreground process under systemd rather than in a terminal. Name the unit dust-relay, which dust restart uses by default, and point ExecStart at your application binary. It is still one process with in-memory channel state, so it remains a single point of failure.

/etc/systemd/system/dust-relay.service
[Unit]
Description=dust relay server
After=network.target

[Service]
WorkingDirectory=/srv/app
ExecStart=/srv/app/bin/your-app relay:start
Restart=always
RestartSec=2
KillSignal=SIGTERM

[Install]
WantedBy=multi-user.target
Keep the secret on the server

The browser needs RELAY_APP_KEY, never RELAY_APP_SECRET. A private channel is only as private as the callback that authorizes it.

Chapter 22

Pulse

Watch the application from inside: what it served, what it queued, how the host is doing, and when something crosses a line.

Pulse is the framework's first-party monitoring module. It is not a hosted service and it does not ask you to install an agent: the application records its own requests, mail, and job attempts into tables beside the rest of your data, reads the host it runs on, and serves a dashboard at /pulse. One stream keeps the open tabs current without a reload.

The chapter starts with what the module records and how to install it, then follows the data through the collectors and the pages. The last two pages cover the live stream and the operational side: alert rules, incidents, retention, and module upgrades.

What Pulse is

In plain words

A monitoring dashboard that lives in your application and reads the data the application already produces.

Pulse has two jobs: record and show. A middleware appends one row per request to an in-memory buffer, and listeners on the framework's mail and queue events write what was sent and what ran. Ticks flush the buffer, build a snapshot of the current numbers, and prune old rows. Nothing in that path changes a response: a failed write is reported to the error handler, not returned to the visitor, and the request that is being observed never waits for the database.

The pages cover the application and the machine. /pulse is the overview; /pulse/requests, /pulse/mail, /pulse/sessions, /pulse/cache, /pulse/jobs, and /pulse/cron cover runtime work; /pulse/system and /pulse/storage cover the host; /pulse/alerts covers the rules and incidents. A Server-Sent Events stream at /pulse/stream keeps every open tab current.

Requests, mail, and job attempts live in Pulse's own pulse_requests, pulse_mail, and pulse_jobs tables. Sessions, cache, and the queue's pending jobs are read from the framework's configured stores, but only when the driver actually uses a database table. CPU, memory, disk, and directory sizes come from the host: /proc, df, and a bounded walk of the application's own folders. On a platform without /proc, the host page says the readings are unavailable.

modules/pulse/mod.rs
impl Module for Pulse {
    fn name() -> &'static str {
        "pulse"
    }

    fn routes(route: &mut Router) {
        routes::routes(route);
    }

    fn register(app: &mut Registrar) {
        app.middleware().append(middleware::RecordRequests);
        app.events()
            .listen(listeners::record_mail_sending)
            .listen(listeners::record_mail_sent)
            .listen(listeners::record_job)
            .listen(listeners::record_job_failed);
    }
}
Gotcha

A section that needs a database store shows — and names the driver when that driver is not in use. It is not reporting zero sessions or zero jobs; it is telling you that the store it would read does not exist in this configuration.

Installing and configuring

In plain words

Download the module, create its tables, compile it in, then decide who may open the dashboard.

Pulse is distributed through the module registry named by modules_url in config/modules.toml. Three commands install it. module:download unpacks it into modules/pulse, verifies the archive, and adds it to modules/mod.rs; migrate creates the module's tables; build compiles the module into the application. Restart the server afterward.

shell
$ dust module:download pulse
$ dust migrate
$ dust build

The dashboard is private by default. Every page and the stream require a signed-in user, and a guest gets a 401. Pulse ships no login form, so send people to your application's own login page first, or place the dashboard behind a gateway. If something else already protects the URL — a private network or an authenticated proxy — set PULSE_ACCESS=public to let the module skip its own check. The check is also bypassed when APP_ENV=testing, so tests can read the pages without a session.

Access is a single group in modules/pulse/routes.rs, and every route sits inside it. That matters when you add a narrower rule: attach it to the group, never to one page, or the next page you add will miss it. The same group carries NoStore, which sets Cache-Control: no-store, private, Pragma: no-cache, and Vary: Cookie, so a shared proxy never keeps a private page. Pulse has no roles or abilities of its own; authenticated or not is the only question it asks.

modules/pulse/routes.rs
route
    .middleware(NoStore)
    .middleware(Access)
    .middleware(YourOperatorCheck)
    .group(|route| {
        route.get("/pulse", handlers::overview);
        route.get("/pulse/stream", stream::stream);
    });
Gotcha

The 401 is deliberate. A redirect to a login page would be parsed as the start of an event stream by EventSource, and the browser would retry forever. Keep the answer a 401, and put authentication in front of the dashboard rather than inside the stream.

Collectors and samples

In plain words

The request path writes to memory; background ticks do the database work and keep the history short.

RecordRequests captures the method, path, status, duration, framework request ID, and time after the response is ready. It skips Pulse's own pages, /vendor, /assets, /storage, /up, /health, /favicon.ico, and /robots.txt. The buffer holds at most 4,096 samples, and each flush inserts at most 200 rows. A one-second tick writes the batch and runs once at shutdown. If the database is down, the batch is dropped and the error reports how many samples were lost; the buffer never grows without bound.

The collector runs every second, immediately at boot. It reads the last 60 seconds of pulse_requests for the rate, error count, slow count, average, p50, p95, and p99, examines at most 5,000 rows for the status classes and the eight busiest routes, and keeps the newest 20 requests. The 24-hour counters are cached for 60 seconds. The result, plus the host and storage readings, is written as one JSON document into pulse_snapshots.

History is written every ten seconds. pulse_system_samples stores CPU, memory, swap, load, processes, and uptime; pulse_disk_samples stores one row per mount with capacity and inodes; pulse_request_samples stores the rolling minute's count, errors, slow requests, and percentiles. Each has an index on sampled_at, and the disk table also indexes mount with sampled_at. The request table indexes created_at, status with created_at, and duration_ms, so the filters the pages use stay cheap.

modules/pulse/mod.rs
app.ticks()
    .every(1.seconds(), middleware::flush)
    .name("pulse-flush-requests")
    .when(|host| host.is_server())
    .run_on_shutdown();

app.ticks()
    .every(1.seconds(), collector::run)
    .name("pulse-collect")
    .when(|host| host.is_server())
    .immediately();
Gotcha

The first CPU reading is zero, because a percentage needs two samples. Disk readings are cached for ten seconds, directory walks for a minute, and a walk skips symbolic links and stops after 200,000 entries. A chart that is empty right after boot is usually just waiting for its first sample.

The dashboard

In plain words

Each page answers one question, and every table keeps the same shape: 25 rows, working filters, and links that preserve them.

The overview is the one-screen answer. It shows CPU with its five-minute history, memory and swap, every mounted disk with capacity, the rolling-minute request chart, the busiest routes, the newest requests, runtime counters, and the newest open incidents. The header also reports the supervisor, cron daemon, and relay.

/pulse/requests adds the full history. The summary covers the last 24 hours; the live card covers the last minute; the table below is paginated at 25 rows. Its From and To date pickers submit from and to as YYYY-MM-DD, default to the last 24 hours, and treat the To date as the end of that day. If you enter the dates backwards, the report swaps them. Press Apply to run the range. Each row links to /pulse/requests/{id}, which shows the method, path, status, duration, and the framework request ID that also appears in the log and the X-Request-Id header.

/pulse/system shows total and per-core CPU, the eight busiest cores, load averages, memory, swap, uptime, process count, and the last 60 samples of CPU history. /pulse/storage shows each mount with capacity and inodes, then the measured sizes of storage/, storage/logs, storage/app, public/, the SQLite files, and the media library. The filesystem reading comes from df -kP and df -iP.

/pulse/runtime gathers pending and dead jobs, failed and completed attempts, mail, sessions, cache, cron, the newest failures, and the configured drivers. /pulse/mail filters by status and subject, 25 per page; View opens the stored email, whose HTML preview is sandboxed by a strict Content Security Policy. Sessions, cache, jobs, and cron runs each paginate at 25, and a cron run's detail page shows its output and error. Page links keep the active filters.

Gotcha

Mail is caught twice through the framework events: MessageSending stores the email as sending, and MessageSent marks the same row sent. A retry updates that row and increments attempt, so one email is one row. A send that never finishes is marked failed after fifteen minutes rather than looking in flight forever.

Live updates

In plain words

One stream, one snapshot, every open tab. The browser reconnects on its own and asks only for what it missed.

/pulse/stream is a Server-Sent Events endpoint on the application's own origin, inside the same access group as the pages. The session cookie therefore authorizes it. The stream reads the browser's Last-Event-ID, asks the snapshot table for a version newer than that, and sends an event named snapshot whose ID is the version. It checks once a second. A keep-alive goes out every fifteen seconds.

A snapshot is one JSON object with five top-level keys. at is the collection time. requests carries the rate, counts, classes, percentiles, top routes, and recent rows. system carries CPU, per-core CPU, load, memory, swap, uptime, and processes. storage carries disks, directory sizes, media, totals, and the used percentage. runtime carries pending and dead jobs, failures, mail, sessions, cache, cron, and open incidents. The collector replaces the single row under the pulse topic.

The pages mark values with data-live and bars with data-live-width. The layout opens the stream with the io/ui sse helper, applies each snapshot in place, and shows Live, Paused, or Offline in the topbar. With JavaScript off, the pages still render on the server, and a <noscript> refresh reloads them every thirty seconds.

modules/pulse/stream.rs
let after = request
    .header("last-event-id")
    .and_then(|value| value.parse::<i64>().ok())
    .unwrap_or(0);

EventStream::channel(move |sender| async move {
    let mut after = after;

    loop {
        if let Some((version, value)) = snapshot::latest(after).await? {
            sender
                .send(Event::new("snapshot", Json(value)).id(version.to_string()))
                .await?;
            after = version;
        }

        dust::task::sleep(1.seconds()).await;
    }
})
.keep_alive(15.seconds())
Gotcha

An edge that buffers responses will hold SSE events and make the dashboard look frozen even when the application is healthy. Exclude /pulse/stream from proxy or CDN buffering, or bypass the edge for it. Also remember that every server process writes the snapshot: on a fleet, the host pages show whichever server wrote last, so run Pulse on one host or add a host column before trusting it across machines.

Alerts, incidents, and operations

In plain words

A rule watches one number in the snapshot, opens one incident while it is over the line, and closes it when the number comes back.

The module ships seven rules: CPU above 85%, memory above 90%, disk above 90%, 5xx above five per minute, slow requests above ten per minute, a queue backlog above a thousand, and any dead job. The evaluator runs every ten seconds against the latest snapshot. It skips a snapshot older than 120 seconds. While a value crosses its threshold, the rule keeps exactly one open incident; when the value returns, that incident is marked resolved.

Rules live in pulse_alerts. To tune one, change its threshold; to pause it, set enabled to false. A rule names a snapshot metric, a comparator (gte, gt, lte, or lt), and a threshold. The metrics you can watch are cpu_bp, memory_bp, disk_bp, errors_60s, slow_60s, pending_jobs, dead_jobs, failed_jobs_24h, and cron_failures. A metric ending in _bp is basis points, so 9000 means 90%. The alerts page lists every rule and the twenty newest incidents; open incidents also appear on the overview and in the sidebar badge.

Retention runs on a five-minute tick with a thirty-second jitter. Requests and job rows default to 14 days (PULSE_RETENTION_DAYS), mail to 30 days (PULSE_MAIL_RETENTION_DAYS), and host and request samples to 7 days (PULSE_SAMPLE_RETENTION_DAYS). A non-numeric or zero value keeps the default. The same tick closes sends that have stayed sending for 900 seconds and marks them failed.

The module itself is managed through the registry. dust module:list shows what is installed, dust module:update pulse installs a newer release, and dust module:download pulse --version 1.3.0 pins one. An update replaces the module's files and first moves the old folder to modules/.backup/pulse-<version>, so commit or copy local edits before running it. Your view overrides in resources/views/vendor/pulse/ survive an update. Run dust migrate for new migrations, then dust build and restart. Disabling the module through config/modules.toml stops its routes and ticks but leaves its tables and data in place.

SQL and shell
UPDATE pulse_alerts SET threshold = 9500 WHERE metric = 'cpu_bp';
UPDATE pulse_alerts SET enabled = FALSE WHERE metric = 'dead_jobs';

$ dust module:update pulse
$ dust migrate
$ dust build
Gotcha

An incident is evidence, not a pager. Pulse has no notification transport, so nobody is woken by a rule; wire the incidents table to the channel you actually watch. A resolved incident stays in the history and is never deleted.

Chapter 23

Neura

Neura gives a dust application an AI runtime: providers, models, chats, tools, memory, and background agents behind a JSON API.

What Neura is

In plain words

Neura is the part of your application that talks to an AI model, remembers the conversation, runs the tools the model asks for, and writes down what happened. It is not a chat window and it is not a model of its own.

Neura is a dust module, so it compiles into the same binary as the rest of your code. It owns the loop between a prompt and an answer: resolve a provider and model, open a chat, write the user message, send the transcript, execute any tool calls, and repeat until the model answers or a budget runs out. Around that loop it adds durable chats, an append-only event log, background shell jobs, delegated child agents, agent memory, and a catalogue of markdown skills.

The module is deliberately headless. It serves JSON, SSE, and WebSocket routes under /neura; it ships no chat interface, so your page, mobile app, or console command builds the screen and calls those routes. Use it when you need a real agent loop — a support assistant that searches your data, a coding helper that runs commands, a worker that delegates research — rather than a single completion.

modules/neura/mod.rs
pub struct Neura;

impl Module for Neura {
    fn name() -> &'static str {
        "neura"
    }

    fn routes(route: &mut Router) {
        routes::routes(route);
    }

    fn migrations() -> Migrations {
        dust::db::migrations!("modules/neura/migrations")
    }

    fn register(app: &mut Registrar) {
        commands::register(app.commands());
    }
}

That implementation is the whole integration surface: routes, migrations, and console commands. Its tables are neura_*, and its files live under storage/neura.

Headless, not unguarded

The routes are unauthenticated. Put Neura behind your application's session guard, an API gateway, or a private network before it is reachable from the internet.

Installing and configuring

In plain words

Download the module, run its migrations, rebuild the application, then write config/neura.toml and sync it into the database.

console
$ dust module:download neura
$ dust migrate
$ dust build

A module is source code, so the download changes the project; building and restarting make its routes and commands available. dust migrate applies the migrations in order: settings and API applications, providers and models, agents, the tool catalogue, chats and messages, requests and steps, compactions and memory, interactions, background jobs and agent runs, usage, events, skills, then two later changes for scoped tools and agent depth. On a fresh application this is one command; on an existing one only the pending migrations run.

The first dust neura:sync copies the module's template to config/neura.toml when the application has none. The file declares settings, providers, and the models each provider serves:

config/neura.toml
[settings]
max_tool_calls = 32
max_hops = 12
compaction_threshold = 0.75
compaction_keep = 0.25
compaction_min_recent = 6
interaction_timeout = 1800
shell_confirmation = true

[providers.ollama]
driver = "ollama"
base_url = "http://localhost:11434"
enabled = true

[providers.ollama.models.llama3]
title = "Llama 3"
context_window = 8192
max_output = 2048
capabilities = ["tools"]

Settings are namespaced strings, so a number stays a number when the runtime reads it. max_tool_calls and max_hops bound one turn; the compaction keys decide when old messages are summarized; interaction_timeout is the default wait for a question; and shell_confirmation = true asks a person before a shell job starts. When a setting is missing, the engine falls back to eight tool calls and eight provider hops.

Keys should not be written literally. Use api_key = "env:DEEPSEEK_API_KEY", export the variable, and sync. Neura stores the resolved key as written, with no encryption layer. A sync that cannot resolve env:NAME keeps the key already stored, so a missing variable shows up as a failed request rather than a silent loss.

console
$ export DEEPSEEK_API_KEY="..."
$ dust neura:sync
$ dust neura:status

neura:sync upserts rows by provider slug and model name. It never deletes a provider a chat still references: a row removed from the file is disabled, so it stops serving new turns while its history remains. neura:status prints the version and per-table counts.

Rebuild after install

A downloaded module is compiled into the application. If the routes answer 404 after installation, the binary is still the old one; run dust build and restart the process.

Models and providers

In plain words

A provider is an endpoint and a key. A model is a name that provider understands, with a context window and a price.

Every provider is a row with a driver, a base URL, optional headers and key, and a timeout. ollama calls POST {base_url}/api/chat and needs no key by default. deepseek, openai, and openai-compatible call POST {base_url}/chat/completions; set the base URL to the versioned root, such as https://api.openai.com/v1.

config/neura.toml
[providers.deepseek]
driver = "deepseek"
base_url = "https://api.deepseek.com"
api_key = "env:DEEPSEEK_API_KEY"
enabled = true

[providers.deepseek.models.deepseek-flash]
title = "DeepSeek V4.1 Flash"
context_window = 1000000
max_output = 384000
capabilities = ["tools", "reasoning", "json", "vision"]

[providers.deepseek.models.deepseek-flash.pricing]
cache_hit = 0.003
cache_hit_peak = 0.006
cache_miss = 0.15
cache_miss_peak = 0.3
output = 0.6
output_peak = 1.2

The model key is the name the provider expects. A request may use that name, or provider/model when two providers serve the same name. Resolution checks an exact model name across every provider first, then the provider prefix, then the bare name again; an unprefixed name that matches two providers resolves to the first in slug order. The HTTP send route requires a model; dust neura:ask without --model picks the first enabled model.

context_window and max_output are token counts; max_output becomes the request's max_tokens, and zero disables that limit. capabilities is metadata for the catalogue and clients — the current engine does not refuse a model that lacks one. pricing is USD per one million tokens, with optional _peak keys for DeepSeek's window: Monday to Friday, 01:00–04:00 and 06:00–10:00 UTC. A missing price counts as zero; a missing peak price falls back to off-peak.

Most failures are configuration failures and say so. An unknown driver reports the driver by name; a missing URL reports that the provider has no base_url; a disabled or misspelled model produces no enabled model with the requested name; a non-2xx answer becomes provider answered 401: …. A turn that cannot find a model never opens a request row. Run dust neura:models to see what the registry can resolve, and dust neura:sync after every edit.

Keys are plain text in the database

There is no encryption layer. Prefer env:NAME so the config holds no secret, restrict database access, and rotate a key by changing the variable and running dust neura:sync.

Agents and prompts

In plain words

An agent is a row with instructions. A completion is one turn in a chat, and the chat is what the next turn remembers.

Agent definitions live in neura_agents: a unique slug, name, long instructions, kind, default_model_id, status, and optional configuration. The engine reads the row's instructions when a turn passes its numeric agent_id; empty instructions fall back to the built-in text: “You are neura, an AI assistant running inside a dust application. Use the tools you are given, keep answers concise, and say when you cannot do something.” No HTTP route creates an agent, so seed the row or write it through your own model, then pass the id.

A completion is a POST /neura/chat with a model, a prompt, and optionally a chat id and agent id. Omit chat_id to start a chat; include it to continue. The response returns the chat id, assistant message id, text, tool-call count, finish reason, whether the turn was stopped, the cost, and token usage.

POST /neura/chat
{
  "model": "llama3",
  "prompt": "Hello",
  "chat_id": null,
  "agent_id": null
}

The system prompt is assembled for each turn. It starts with the agent's instructions, adds a short paragraph about explore and search, appends a bounded ## Memory section when an agent is present, and appends the newest ## Conversation summary when the chat has been compacted. The rest is the visible transcript in order, including assistant tool calls and tool results. A hidden background report is still read by the next turn, so the model sees what a child job returned.

Conversation state is the chat row. The first prompt becomes the title, cut to sixty characters. Every later turn adopts the model named in the request, so a chat can move models without losing history. Only one live turn is registered per chat in a process; a second send there gets HTTP 409. POST /neura/chat/{chat_id}/stop stops the chat and its children, and POST /neura/chat/{chat_id}/steer queues a message for the next hop. Read the transcript with GET /neura/chat/{chat_id}/messages; list chats with GET /neura/chats.

console
$ dust neura:ask "Explain this repository" --model llama3
$ dust neura:ask "Continue" --model llama3 --chat <uuid>
$ dust neura:ask "Review the plan" --model llama3 --agent 3
The agent supplies instructions, not the model

Pass agent_id to apply its instructions and memory. The turn's model still comes from the request; the agent's default_model_id is not substituted by this engine.

Tools and context

In plain words

A tool is a named function with a JSON Schema. The model asks for one, Neura runs it, and the result goes back into the conversation.

Neura keeps one global tool registry, not a per-agent list. Packs group tools by purpose, and the model discovers them with explore and search. Every tool declares a name, description, pack, kind, JSON Schema, and an async run. Built-ins cover discovery, memory, skills, background jobs, delegation, interaction, compaction, and tool management. Application tools belong in the compiled registry, not on an agent row.

One provider hop may return several calls. The engine runs them in order, writes a neura_tool_calls row per call, appends a tool message with the call id, and sends results back on the next hop. A turn ends when the model answers without a call or max_hops is reached. A call past max_tool_calls is answered with a refusal instead of failing the turn, so the model can finish with what it has. A result is capped at 20,000 characters before the next prompt.

The context a tool receives is explicit. ToolContext carries the chat uuid, request uuid, agent id, working directory, whether interactions are allowed, the registry, the interaction hub, the stop flag, and the chain depth. The model sees instructions, memory, the latest summary, the visible transcript, and tool schemas and results. There is no automatic injection of application records and no general SQL tool: to let the model read your database, give it a deliberate tool — compiled or HTTP — that calls your endpoint. Memory and skills are the built-in durable stores.

A dynamic tool is a catalogue row with an http, template, or chain runtime. The model creates them with tool_create; an operator can create one over HTTP. A chat-scoped tool is visible only to that chat; a global tool is visible to every chat. Names are 1–64 letters, digits, -, and _, cannot collide with a built-in, and config and schema must be objects. The http runtime refuses private hosts and Host overrides and caps default responses at 20,000 characters; a chain refuses self-calls and interaction tools, cannot escalate kind, and stops at eight levels of nesting.

POST /neura/tools
{
  "name": "weather",
  "description": "Read the weather for a city.",
  "execution": "http",
  "config": {
    "url": "https://api.example.com/weather",
    "query": { "city": "{{city}}" }
  },
  "schema": {
    "type": "object",
    "properties": { "city": { "type": "string" } },
    "required": ["city"]
  },
  "pack": "dynamic",
  "chat_id": null
}
No raw database access

Neura does not expose a “run SQL” tool. Keep database access behind a narrow tool with its own validation, and give the model only the operations the feature needs.

Running in production

In plain words

Run a queue worker for background work, protect the API, watch cost and stale rows, and upgrade the module like any other dependency.

Neura does not stream tokens: provider requests use "stream": false. Watch progress through the event log instead. GET /neura/chat/{chat_id}/events?after=0&follow=true is an SSE stream that replays after an id and follows new events; a reconnecting client sends Last-Event-ID and resumes without gaps. GET /neura/chat/{chat_id}/socket is the WebSocket version and sends one JSON object per event.

Background shell jobs and delegated agents are ordinary dust queue jobs named neura.background and neura.agent. In production the supervisor keeps a queue:work process alive; in tests QUEUE_CONNECTION=sync runs them immediately. A job is queued, claimed, run, and closed as finished, failed, or cancelled; output and error are stored up to 200,000 characters. A cancel signals the process group, then sends SIGKILL after five seconds. A delegated agent gets its own child chat, stops at four levels, and reports into the parent.

neura_chats, neura_messages, neura_requests, neura_steps, and neura_tool_calls are the conversation and audit trail. neura_compactions holds summaries, neura_agent_memory holds what an agent kept, and neura_interactions holds pending questions. Background runs and agent runs track detached work. neura_usage records tokens and cost; neura_requests.cost and neura_chats.cost repeat the figures for reporting. Read requests for status and stop reason, steps for each hop, tool calls for arguments and results, and events for the sequence. dust neura:status gives row counts, and GET /neura/health answers "ok".

A deploy or crashed worker can leave rows running; dust neura:reap --minutes 180 fails stale turns, runs, and jobs, returns chats to idle, and expires pending questions. Long chats compact automatically; POST /neura/chat/{chat_id}/compact or dust neura:compact <chat-uuid> --keep 6 does it on demand. Protect the API: every route is unauthenticated, and although neura_apps can issue keys with dust neura:apps:create "My app", this release does not enforce them. Use your session guard, a gateway, or a private network. To upgrade, run dust module:update neura, then dust migrate, dust build, dust neura:sync, dust neura:tools:sync, and dust neura:skills:sync; restart the web process and queue workers. Commit local changes first, because an update replaces the module's files.

Stop the whole tree

POST /neura/chat/{chat_id}/stop also stops delegated child chats and their queued or running background jobs. Use it when a user cancels, rather than deleting the chat row and leaving work running.

Chapter 24

Observability & utilities

Logs, traces, and a small set of shared helpers that tell you what your application did, when it did it, and how long it took.

Observability is not a separate service you bolt on later. The application writes structured logs, records timed spans, and reads one controllable clock, so the same code that serves a request can explain it afterward. This chapter covers those facilities first, then the helpers around text, exact numbers, random decisions, and files compiled into the binary.

Start with logging to learn what happened, and with tracing to learn where the time went. The OpenTelemetry page shows how to export spans. The rest covers time travel in tests, Str and Decimal, and the remaining small utilities.

Logging

In plain words

A log is a line that says what the application just did, written in a form both you and a log collector can read.

Write log messages with the tracing macros, one for each level: trace!, debug!, info!, warn!, and error!; off disables logging. The default configuration records info and above to standard error. LOG_LEVEL sets the minimum level, and RUST_LOG overrides it when it is present in the process environment. Both accept tracing's filter syntax, which lets you raise one module without raising the rest: LOG_LEVEL=info,app=debug,sqlx=warn.

Channels decide where the lines go. stderr is the default and is what containers and process managers collect; stdout writes to standard output; daily writes a rotating file under storage/logs, named like dust.2026-10-04.log. Give a channel its own level with LOG_DAILY_LEVEL, LOG_STDERR_LEVEL, or LOG_STDOUT_LEVEL. LOG_DAILY_DAYS controls how many daily files are kept, and 0 keeps them all. The format is text by default and json when you set LOG_FORMAT=json; JSON lines carry the time, level, message, target, active request or job, fields, and context.

.env
LOG_CHANNEL=stderr,daily
LOG_LEVEL=info,app=debug,sqlx=warn
LOG_FORMAT=json
LOG_DAILY_LEVEL=warn
LOG_DAILY_DAYS=14

Pass record identifiers as structured fields instead of interpolating them: tracing::info!(post.id = post.id, user.id = user.id, "Post published"). Numbers, strings, and booleans work directly; a type that needs Display or Debug takes a % or ? prefix, as in %user.email. Every line inside a request carries the request span with its id, method, path, and route, and dust::context::add("tenant", tenant) attaches a value to every later line in that request. A channel that needs a different format can be configured in src/config/logging.rs.

Gotcha

daily is off by default; check LOG_CHANNEL before the level. An exported RUST_LOG also beats LOG_LEVEL.

Tracing

In plain words

A trace is a timeline of one operation, made of timed spans for the request and for every query, cache lookup, and outgoing call inside it.

Requests, console commands, queued jobs, scheduled tasks, ticks, workflow runs and steps, database queries, cache operations, Redis commands, mail, and SMS already create spans. A request is named after the method and route, such as GET /users/{user}; a job after the job; a workflow step as step charge card. A failed request, job, task, query, or send marks its span as failed and records an error.type, so a tracing tool can group failures.

Attributes follow OpenTelemetry's semantic conventions. A request records its method, route, path, scheme, and status; a query records its operation, table, and SQL with every literal replaced by ?; an outgoing request records its URL with query values replaced by REDACTED. Bound query parameters, Redis arguments, phone numbers, and email addresses, subjects, and bodies stay out of spans. A framework error exports a short summary such as database error 22P02 or HTTP 404 rather than a message that might quote user data. Logs and error reports still receive the full error.

Wrap your own functions when the built-in spans do not show which part of your code is slow. #[tracing::instrument] puts the function in a span named after it; skip_all keeps arguments out, and fields(...) adds the values you want. For one future, import tracing::Instrument and call .instrument(tracing::info_span!(...)). Your span becomes a child of the active request or command, and its queries become its children. dust::task::spawn inherits the span; tokio::spawn does not, so its work appears in a separate trace. Between services, an incoming traceparent continues the upstream trace, every outgoing HTTP request sends one, and a queued job or scheduled command keeps the trace that dispatched it.

src/actions/popular_posts.rs
use dust::prelude::*;

#[tracing::instrument(skip_all, fields(user.id = user.id))]
pub async fn popular_posts(user: &User) -> dust::Result<Vec<Post>> {
    Post::query()
        .filter(Post::user_id.eq(user.id) & Post::votes.gt(100))
        .order_by(Post::votes.desc())
        .limit(5)
        .get()
        .await
}
Gotcha

Paths, cache keys, and logged messages are exported. Never put a token, email address, or reset secret in them.

OpenTelemetry

In plain words

Enable the feature, point the application at a collector, and the spans it already records leave in batches for your tracing tool.

Add the opentelemetry feature to dust-framework in Cargo.toml. The exporter starts as soon as an endpoint is configured. OTEL_EXPORTER_OTLP_ENDPOINT is the base URL, and the framework appends /v1/traces; OTEL_EXPORTER_OTLP_TRACES_ENDPOINT is the full URL when your provider needs one. Put headers in OTEL_EXPORTER_OTLP_HEADERS or the traces-specific variant, name the service with OTEL_SERVICE_NAME, and add attributes with OTEL_RESOURCE_ATTRIBUTES. OTEL_SDK_DISABLED=true turns exporting off without deleting the configuration.

By default every trace is kept. In production, a sampler usually pays for itself: OTEL_TRACES_SAMPLER=parentbased_traceidratio with OTEL_TRACES_SAMPLER_ARG=0.1 keeps about ten percent of traces that start in your service, while a request continuing an upstream trace follows the upstream decision. Sentry accepts OTLP with its traces endpoint and an x-sentry-auth header. The exporter batches in the background, so a slow collector adds memory and egress rather than request latency; an unreachable collector logs an error without stopping requests. Buffered spans are flushed at shutdown.

.env
OTEL_SERVICE_NAME=storefront
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1

What arrives is the span tree described on the tracing page: a request with its queries, cache calls, outgoing requests, jobs, and workflow steps beneath it. This exporter carries traces only; it does not turn the OTEL_* variables into a metrics pipeline, so keep host and business metrics in the system that already collects them. JSON logs gain trace_id and span_id while tracing is active, so a log line links to its trace. For a different exporter, register a provider with logging.tracer_provider(provider) inside with_logging, using the same OpenTelemetry version and an HTTP exporter when the Tokio runtime is not running yet.

Gotcha

The base URL gets /v1/traces; use OTEL_EXPORTER_OTLP_TRACES_ENDPOINT only when you have the full URL.

Time

In plain words

The application has one clock, and every part of your code reads it through dust::now() so a test can move time without sleeping.

dust::now() returns a ZonedDateTime in UTC, and dust::time::today() returns today's civil::Date. Store instants as Timestamp, the timezone-independent value that maps to timestamp columns, and convert with in_tz("America/Chicago") for a user's local time. Do not call ZonedDateTime::now() or SystemTime::now(): those bypass the application clock, so a test cannot move them.

The Dates trait adds format, plus, minus, is_past, diff_in_days, and for_humans to all three date types. ToSpan builds durations from integers, such as 30.days() or 2.hours().minutes(30). Calendar spans are not fixed durations: adding one day keeps the same wall-clock time across a daylight saving change, and adding one month to January 31 lands at the end of February. For spans from user input, Jiff's checked_add and checked_sub return an error instead of panicking outside the supported years.

src/http/handlers/dashboard.rs
use dust::prelude::*;

let now = dust::now();
let trial_ends_at = now.plus(30.days());

if trial_ends_at.is_past() {
    // Send the user to billing...
}

let label = now.in_tz("America/Chicago")?.format("%B %-d, %Y");
let remaining = now.timestamp().diff_in_days(&trial_ends_at.timestamp());

Tests move the clock instead of waiting. app.travel(25.hours()) advances the application's time and leaves it standing still; travel_back() returns to the present. travel_to(time) jumps to a ZonedDateTime or Timestamp, freeze_time() stops where it is, and freeze_second() stops at the start of the current second so a value matches one the database stored to the second. Each test application owns its clock, so parallel tests never shift each other's time.

Gotcha

Store a Timestamp, not a ZonedDateTime; 24 hours is not always a calendar day.

Strings and numbers

In plain words

The framework ships the text conversions you would otherwise write by hand, and an exact decimal for values a binary float would round.

The Str trait is on every &str and String, and the prelude imports it. Use slug for URLs, headline for labels, snake().plural() for table names, and limit or words for previews. All lengths and positions count characters rather than bytes, so "这是一段中文".take(2) is safe. Slicing methods such as after and take return a borrowed &str; transformations return a new String.

For identifiers, dust::str draws from the operating system's random source. str::random(40) returns letters and digits for an invitation code, str::password(16) includes symbols, and str::uuid7() or str::ulid() returns an identifier that sorts by creation time. Prefer the time-ordered forms for primary keys: they append cleanly to a B-tree index, unlike a random version 4 UUID.

Use the standard library for counters, sizes, and measurements: u64, f64, parse, and format! are the right tools, and a parsed value is a Result you must handle. Use dust::numeric::Decimal for money, rates, and anything where 0.1 + 0.2 must not become 0.30000000000000004. Create a decimal by parsing text rather than converting a float, add and multiply it directly, round with round(2) or rescale with with_scale(2), and convert with to_f64() only at the edge. It serializes as a string, so a client keeps the precision the server calculated.

src/support/pricing.rs
use dust::numeric::Decimal;
use dust::prelude::*;

let slug = "My First Post".slug();
let table = "BlogPost".snake().plural();
let preview = "A long post title".limit(12);
let token = dust::str::random(40);
let id = dust::str::uuid7();

let amount: Decimal = "19.99".parse()?;
let fee: Decimal = "0.01".parse()?;
let total = (amount + fee).round(2);

assert_eq!(total.to_string(), "20.00");
Gotcha

slug keeps accents; call .ascii() first for ASCII. limit adds an ellipsis; take does not.

Small utilities

In plain words

Two helpers cover decisions that do not deserve their own module: a lottery for choosing a fraction of events, and a macro for shipping files inside the binary.

Lottery::odds(wins, out_of) returns a value whose draw() wins when a random number from 0 to out_of - 1 is less than wins. odds(1, 20) wins about five percent of the time, odds(0, 100) never wins, and odds(100, 100) always does. The odds are exact over many draws, not per user or per session, so use a lottery for work that is genuinely per event, such as sampling one request in a hundred for diagnostics. When a decision must stay with a user, store it in a feature flag; a fresh draw on every visit is the wrong shape for a rollout.

dust::embed!("resources/views") compiles a directory into the binary and returns an Embedded. Register it under a namespace with app.views().namespace("billing", ...), or serve its files with app.routing().assets("billing", ...); the framework then resolves billing::invoice or /vendor/billing/... without a source tree on the server. In a debug build, when the original directory exists, files are read from disk so edits appear without a rebuild. Production uses the embedded bytes, hidden files are skipped, and a newly added file needs a rebuild.

The lottery is controllable in tests. always_win() makes every draw win, always_lose() makes every draw lose, fix([true, false]) supplies results in order, and determine_results_normally() returns to random draws. These affect the test application, including draws made by session cleanup and feature flags, so use always_win or always_lose when middleware might draw first. Keep embed! paths relative to the crate's Cargo.toml, and list the directory in the published package.

src/features/survey.rs
use dust::lottery::Lottery;

pub fn should_survey() -> bool {
    Lottery::odds(1, 20).draw()
}

// In a test:
// Lottery::always_win();
src/providers/billing.rs
use dust::container::Registrar;

fn register(app: &mut Registrar) {
    app.views().namespace("billing", dust::embed!("resources/views"));
    app.routing().assets("billing", dust::embed!("public"));
}
Gotcha

fix is order-sensitive across middleware draws; prefer always_win or always_lose when the exact draw matters.

Chapter 25

Packages & agents

Extend the application with packages and registry modules, then give an AI agent the instructions and the exact guides it needs to change it safely.

A dust application grows in two directions. A package is a Rust crate you add to Cargo.toml; a module is a folder of Rust that compiles into your own binary. The first is how you consume someone else's work, the second is how you keep one feature's routes, tables, views, and services together without turning src/ into a pile.

This chapter covers both, from the vendor URL an asset is served under to the registry commands that install a module. It then turns to the files that tell an AI agent how to work in the application: AGENTS.md, the optional CLAUDE.md and skills, and the version-matched guides in storage/docs.

Packages and assets

In plain words

A package is a library crate that plugs into your application through a service provider; the styles and scripts it ships are served under /vendor/<namespace>.

A package is an ordinary Rust library crate that depends on dust-framework. Adding it with cargo add makes its types importable, but nothing runs until you register its service provider in src/app.rs with with_providers. Providers have three optional steps — config, register, and boot — and the application's own callbacks run after every provider, so your settings, routes, and middleware can always override a package default.

Inside register, a provider reaches the same builders as src/app.rs: routing, middleware, views, events, commands, schedule, migrations, errors, logging, and services. It can also ship configuration sections, which the application may edit field by field before the provider's services are resolved. Only authentication guards are reserved to the application.

Assets are the part you see in a template. A package embeds a directory with dust::embed! and registers it under a namespace with app.routing().assets(...). dust-framework serves the files at /vendor/<namespace>/<path>, and vendor_asset returns that URL with a content hash in the query string, such as /vendor/inspire/inspire.css?id=34b6aba934cd2bfe. The hash changes when the file changes, so a browser fetches the new copy instead of a cached one.

resources/views/layouts/app.html
<link rel="stylesheet" href="{{ vendor_asset("inspire", "inspire.css") }}">
<script type="module" src="{{ vendor_asset("inspire", "app.js") }}"></script>

An application can replace any package asset by putting a file at public/vendor/<namespace>/<path>. A package that builds its CSS or JavaScript should publish the built directory, point the bundler's public path at /vendor/<namespace>/, and list the directory in Cargo.toml's include. embed! reads it when the consuming application compiles the crate, so a consumer never runs your bundler.

Gotcha

The include list is what makes assets survive cargo publish. Check it with cargo package --list; a dist/ folder missing from the list builds locally and fails for everyone else.

The module registry

In plain words

A module is a self-contained folder of Rust compiled into your application; the registry is an index of module releases, and the module commands install, update, list, and toggle them.

Modules are not crates. They live in modules/ at the application root and are declared in modules/mod.rs, so adding one does not add a dependency or a second build graph. Each module has a module.toml with its name, version, description, and the dust versions it targets, a mod.rs implementing Module, and folders for routes, handlers, migrations, views, and docs. dust module:make blog writes that starting point and adds the two registry lines.

The registry is named by modules_url in config/modules.toml, or by MODULES_URL when the file leaves it out. dust module:download pulse reads {modules_url}/index.json, which lists each release's name, version, description, target dust versions, checksum, and download path. It picks the newest release — or the exact one passed with --version — downloads the archive, checks its SHA-256, and unpacks it into modules/pulse. It also verifies that module.toml agrees with the registry and that every archive path stays inside the module's folder. An existing folder is left alone unless you pass --force, which first moves the old copy to modules/.backup/<name>-<version>.

A download only writes files and registry lines. The module is Rust, so run dust build and restart the application before its routes exist; if it ships migrations, run dust migrate as well. module:update compares each installed module.toml version with the registry and installs a newer release, keeping the same backup. A module the registry does not list is left alone, and an update replaces local edits, so commit them first.

config/modules.toml
# Modules that stay compiled in but don't register at startup.
disabled = ["shop"]

# The registry that module:download and module:update read.
modules_url = "https://modules.dustapp.dev"

module:list shows each module's path and whether it is enabled, and --enabled or --disabled filters the table. module:disable shop adds the name to disabled; module:enable shop removes it. The change applies at the next start and needs no recompilation, because a disabled module is still compiled — it just does not register its routes, migrations, views, or services. module:delete asks first, then removes the folder and the registry lines, but not the migrations or the tables they created.

Gotcha

Disabling is not a rollback. The module's tables and data stay in the database, and modules/.backup is never compiled in or listed. Removing either takes a deliberate step outside these commands.

Project instructions for agents

In plain words

AGENTS.md is the short brief an agent reads first; storage/docs is the long reference; CLAUDE.md points tools that expect it at the same brief, and .agents/skills adds focused playbooks.

dust new writes AGENTS.md and the framework's guides into storage/docs. On an application created before those files existed, dust docs:install does the same thing in place: it rewrites AGENTS.md and the guides, and refuses to run outside a directory with a Cargo.toml. It does not create CLAUDE.md or .agents/skills; those are additions you make when your tools or team need them.

AGENTS.md is deliberately short. It says where the guides are, what dust is, which folder holds what, the commands used every day, and the rules that keep code idiomatic: return dust::Result and use ?, use the query builder and migrations, register routes and services in src/app.rs or a module's register, document public items, keep files under 250 code lines, and test behaviour. It ends with safety rules: do not edit storage/docs, do not commit .env, and treat migrations as append-only. Keep it current as the application grows.

CLAUDE.md is one line, @AGENTS.md, so a tool that looks for Claude's file reads the same instructions. .agents/skills/ holds Agent Skills that an agent loads on demand, one per area: writing-dust-apps for layout and idioms, database-and-models for models, typed queries, relationships, and migrations, validation-and-input for typed body and query input, authorization attributes, and custom rules, auth-and-authorization for users, policies, and compile-time-checked authorization, queues-and-workflows for tasks, jobs, workflows, and events, and testing-dust-apps for feature tests, factories, and fakes. A skill is a playbook, not a second copy of the guides.

CLAUDE.md
@AGENTS.md

The instructions should carry what only your application knows: its domain vocabulary, the services it adds, where a new feature belongs, the commands CI runs, and the mistakes an agent has already made. Keep the verification commands identical to CI, because an agent that can reproduce a failure locally can usually fix it before you look. Leave the framework's API out of the file and point at the guide instead; a copied signature goes stale, a link does not.

Gotcha

AGENTS.md is not a changelog and not a tutorial. If a rule needs a paragraph of history, it belongs in the guide or in the code, not in the brief every agent reads on every task.

Bundled docs for the installed version

In plain words

The guides ship with the application and with the installed crate, so an agent can read the exact version you compiled against without a network.

storage/docs holds the complete guides as plain Markdown with relative links: documentation.md is the index grouped by area, README.md explains how they are organised, and the rest are the guides themselves, with the images they reference. dust new writes them, and dust docs:install rewrites them in an existing application. Read them in an editor, or point an agent at storage/docs/documentation.md and ask it to open the guide for the feature before writing code.

Version matching has two layers. storage/docs is embedded in the dust CLI when the CLI is built, so it matches the CLI that ran, not necessarily the framework version in your Cargo.lock. The crate itself packages the same Markdown under $CARGO_HOME/registry/src/<registry>/dust-framework-<version>/docs, and that copy matches the version Cargo resolved; with a path dependency, read the checkout's docs/. When the two disagree, the crate's docs for the version in Cargo.lock are the ones that describe the code you are compiling.

shell
$ dust docs:install
$ ls "$CARGO_HOME/registry/src"/*/dust-framework-*/docs

Working with agents

The daily loop is short. Read AGENTS.md, open the guide for the area you are about to touch, make the smallest change in the folder the guide names, then run the checks: cargo fmt, cargo clippy --all-targets -- -D warnings, and cargo test. If the change adds a route, a migration, or a configuration value, update the application's own guide or instructions in the same pass, so the next session starts from the truth.

Do not let an agent guess an API, a command sequence, or a schema. A module install is download, migrate, build, restart — in that order — and an update replaces files. Migrations are append-only. Secrets belong in .env. Assets only reach a consumer if the published crate includes them. When a guide and the source disagree, read the source for the version in Cargo.lock and fix the guide; the agent should be able to point at the file that settled the question.

Gotcha

The guides are the source of truth, not the model's memory. A confident signature that is not in storage/docs or the crate source is a guess, and the compiler will usually find it.

Chapter 26

A shop, end to end

Build a small shop from five tables to a tested checkout, and see how the framework's pieces fit together when the feature is real.

This is the last chapter, so it does not introduce another feature. It builds one small application with the features you have already met: five tables, a storefront, a cart, a checkout, an admin area, and an order confirmation. Each page adds one layer and leaves the application runnable.

The shop is deliberately plain. There is no payment provider, no stock reservation service, and no JavaScript framework. Those are decisions you make for your own business. What the chapter does show is where each decision belongs, and which framework boundary keeps the rest of the application honest.

The plan

In plain words

A shop is a catalog, a cart, and an order. The catalog is public, the cart belongs to one visitor, and the order is the permanent record of what was bought.

The domain has five tables. products holds the catalog: a name, a slug for the URL, a description, a price, a stock count, an optional image path, and an active flag. carts holds one row per visitor's cart, keyed by a random token kept in the session. cart_items joins a cart to a product and stores the quantity. orders stores the customer details, the total, a public token for the confirmation URL, and a checkout token used for idempotency. order_items copies the product name and unit price at the moment of purchase, so editing a product later never rewrites history.

There are four page groups. The storefront lists active products and shows one product by slug. The cart shows the current cart, changes quantities, and removes lines. Checkout collects the customer's details and creates the order. The admin area lists orders and manages products behind a login.

Keep the first version in src/. It shares the application's layout and authentication, and you are still changing its shape. A module is the right home once the shop has its own URLs, its own tables, and a boundary you want to disable or ship separately. Moving it later is mostly a change of paths: the handlers, models, and migrations move together, and the routes keep the same URLs.

the shop's files
src/
├── app.rs
├── models/
│   ├── product.rs
│   ├── cart.rs
│   ├── cart_item.rs
│   ├── order.rs
│   └── order_item.rs
├── http/handlers/
│   ├── storefront.rs
│   ├── cart.rs
│   ├── checkout.rs
│   └── admin/
│       ├── products.rs
│       └── orders.rs
├── policies/shop.rs
├── mail/order_confirmation.rs
└── routes/web.rs

resources/views/
├── layout.html
├── storefront/{index,show}.html
├── cart/show.html
├── checkout/{show,confirmation}.html
├── admin/products/{index,create,edit}.html
├── admin/orders/{index,show}.html
└── mail/order-confirmation.html

database/
├── migrations/
└── seeders/shop.rs

tests/shop.rs

src/app.rs registers the migrations and the one route file:

src/app.rs
use dust::foundation::ApplicationBuilder;
use dust::prelude::*;

pub fn configure() -> ApplicationBuilder {
    Application::configure()
        .with_migrations(dust::db::migrations!("database/migrations"))
        .with_routing(|routing, _| {
            routing.web(crate::routes::web::routes);
        })
}
Gotcha

“Move it to a module” is not a reason to move it on day one. A module adds a registry, a view namespace, and a second place to register migrations. Start in src/ and move when the boundary earns its keep.

Migrations and models

In plain words

Write the tables once, in order, with the foreign keys and indexes the queries need. The models are typed mirrors of those tables.

Create the catalog first. A product needs a unique slug, a price stored as an exact decimal, a non-negative stock count, and an index on active because every storefront query filters on it. The cart tables come next: carts.token is unique, and cart_items has a unique index on (cart_id, product_id) so one product appears once per cart. The order tables come last: orders.number, orders.public_token, and orders.checkout_token are unique, and order_items references both the order and the product.

Use restrict_on_delete on the product foreign keys. A product that appears in an order must not disappear and leave the order pointing at nothing. For cart items, cascade_on_delete is fine: deleting a cart should take its lines with it. Add the is_admin column to users in its own migration, with a default of false, so existing rows stay valid.

database/migrations/2026_12_03_100000_create_shop_tables.rs
use dust::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> dust::Result<()> {
    tx.schema()
        .create("products", |table| {
            table.id();
            table.string("name");
            table.string("slug").unique();
            table.text("description").nullable();
            table.decimal("price", 10, 2);
            table.integer("stock").default(0);
            table.boolean("active").default(true);
            table.string("image_path").nullable();
            table.timestamps();
            table.index("active");
        })
        .await?;

    tx.schema()
        .create("carts", |table| {
            table.id();
            table.string("token").unique();
            table.timestamps();
        })
        .await?;

    tx.schema()
        .create("cart_items", |table| {
            table.id();
            table.foreign_id("cart_id").constrained().cascade_on_delete();
            table.foreign_id("product_id").constrained().restrict_on_delete();
            table.integer("quantity");
            table.timestamps();
            table.unique(["cart_id", "product_id"]);
        })
        .await?;

    tx.schema()
        .create("orders", |table| {
            table.id();
            table.string("number").unique();
            table.string("public_token").unique();
            table.string("checkout_token").unique();
            table.string("customer_name");
            table.string("customer_email");
            table.string("address_line");
            table.string("city");
            table.string("postcode");
            table.decimal("total", 10, 2);
            table.string("status").default("pending");
            table.timestamps();
            table.index(["created_at"]);
        })
        .await?;

    tx.schema()
        .create("order_items", |table| {
            table.id();
            table.foreign_id("order_id").constrained().cascade_on_delete();
            table.foreign_id("product_id").constrained().restrict_on_delete();
            table.string("product_name");
            table.decimal("unit_price", 10, 2);
            table.integer("quantity");
            table.timestamps();
        })
        .await
}

The models follow the tables. Cart has many CartItem rows; CartItem belongs to a cart and a product; Order has many OrderItem rows; OrderItem belongs to an order and a product. Prices and totals are Decimal, never floating point. Mark columns with a database default using #[default], so create! may omit them.

src/models/product.rs and src/models/order.rs
use dust::model::{HasMany, model};
use dust::numeric::Decimal;
use dust::time::Timestamp;

use crate::models::OrderItem;

#[model]
pub struct Product {
    pub id: i64,
    pub name: String,
    pub slug: String,
    pub description: Option<String>,
    pub price: Decimal,
    #[default]
    pub stock: i64,
    #[default]
    pub active: bool,
    pub image_path: Option<String>,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,
}

#[model]
pub struct Order {
    pub id: i64,
    pub number: String,
    pub public_token: String,
    pub checkout_token: String,
    pub customer_name: String,
    pub customer_email: String,
    pub address_line: String,
    pub city: String,
    pub postcode: String,
    pub total: Decimal,
    #[default]
    pub status: String,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,

    #[has_many]
    pub items: HasMany<OrderItem>,
}

The other models are short. Cart owns its CartItem rows, and each line points at a product. OrderItem points at the order and keeps a copy of the product name and price, because the catalog may change after the sale.

src/models/cart.rs, cart_item.rs, and order_item.rs (combined)
use dust::model::{BelongsTo, HasMany, model};
use dust::numeric::Decimal;
use dust::time::Timestamp;

// Order and Product are defined in the model files above.

#[model]
pub struct Cart {
    pub id: i64,
    pub token: String,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,

    #[has_many]
    pub items: HasMany<CartItem>,
}

#[model]
pub struct CartItem {
    pub id: i64,
    pub cart_id: i64,
    pub product_id: i64,
    pub quantity: i64,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,

    #[belongs_to]
    pub cart: BelongsTo<Cart>,
    #[belongs_to]
    pub product: BelongsTo<Product>,
}

#[model]
pub struct OrderItem {
    pub id: i64,
    pub order_id: i64,
    pub product_id: i64,
    pub product_name: String,
    pub unit_price: Decimal,
    pub quantity: i64,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,

    #[belongs_to]
    pub order: BelongsTo<Order>,
    #[belongs_to]
    pub product: BelongsTo<Product>,
}

Seed a handful of products so the storefront has something to show. Use create! and parse prices from strings, which keeps the decimal exact. Call the seeder from your default database seeder, or run dust db:seed shop after dust migrate. The count check makes a second run a no-op instead of a unique-slug error.

database/seeders/shop.rs
use dust::db::seeder;
use dust::model::create;
use dust::str::Str;

use crate::models::Product;

#[seeder(without_events)]
pub async fn shop() -> dust::Result<()> {
    if Product::query().count().await? > 0 {
        return Ok(());
    }

    for (name, price, stock) in [
        ("Canvas tote", "24.00", 20_i64),
        ("Enamel mug", "16.50", 35_i64),
        ("Field notebook", "9.00", 50_i64),
    ] {
        create!(Product {
            name,
            slug: name.slug(),
            description: None,
            price: price.parse::<dust::numeric::Decimal>()?,
            stock,
            active: true,
            image_path: None,
        })
        .await?;
    }

    Ok(())
}
Gotcha

Migrations are forward-only. Once the shop has real orders, never edit the migration that created these tables. Add a new migration, backfill what it needs, and only then tighten a column.

The storefront

In plain words

Two public pages and one form: a product list, a product page, and a button that puts a product in the cart.

The storefront has three routes. The list filters active products and orders them by name. The detail route binds the product by slug, so the URL is readable and stable. The add-to-cart route is a POST, because it changes state. All three live in the web group, so they have a session and CSRF protection.

src/routes/web.rs
use crate::http::handlers::{cart, checkout, storefront};
use dust::prelude::*;

pub fn routes(route: &mut Router) {
    route.get("/", storefront::index);
    route.get("/products/{product:slug}", storefront::show);

    route.get("/cart", cart::show);
    route.post("/cart/items", cart::store);
    route.post("/cart/items/{item}/quantity", cart::update);
    route.post("/cart/items/{item}/remove", cart::destroy);

    route.get("/checkout", checkout::show);
    route.post("/checkout", checkout::store);
    route.get("/orders/{order:public_token}", checkout::confirmation);
}

The handlers stay small. The list loads the products; the detail rejects an inactive product with a 404 instead of showing a page that is no longer for sale. A missing slug is already a 404, because route model binding handles it before the handler runs.

src/http/handlers/storefront.rs
use dust::prelude::*;
use dust::view::View;

use crate::models::Product;

pub async fn index() -> dust::Result<View> {
    let products = Product::query()
        .filter(Product::active.eq(true))
        .order_by(Product::name)
        .get()
        .await?;

    Ok(view("storefront.index", data! { products }))
}

pub async fn show(product: Product) -> dust::Result<View> {
    if !product.active {
        return Err(dust::abort(404));
    }

    Ok(view("storefront.show", data! { product }))
}

Product images are optional. The admin uploads a file to the public disk and stores the returned path on the product. The storefront renders /storage/{{ product.image_path }}, which is where the public disk is served. If you move images to S3 or a CDN, replace that path with the URL returned by the disk; do not scatter storage URLs through your templates.

The add-to-cart form posts the product ID and a quantity. The handler checks that the product is active and that the quantity fits the stock before it touches the cart. The next page covers what happens to that input.

Gotcha

A slug is part of a public URL. Changing it breaks links and search results. When a product is renamed, keep the old slug in a redirect or a separate slug history table; do not silently rewrite the route.

The cart

In plain words

The session remembers which cart is yours; the database remembers what is in it. Totals are always calculated from the current product prices.

Store the cart in the database and put only its random token in the session. A cookie-only cart hits the 4 KB cookie limit quickly, and it disappears when the visitor changes browser. A database cart survives that, and it lets you see abandoned carts, though you should delete old ones on a schedule. A guest who never checks out still gets a row; that is the trade you are making.

Adding a line has two cases. If the cart already holds the product, increment the quantity; otherwise insert a new line. The unique index on (cart_id, product_id) is the real guard against duplicates. Check the stock before writing, and check it again at checkout, because another visitor may have bought the last item in between.

src/http/handlers/cart.rs
use dust::model::{create, update};
use dust::prelude::*;
use dust::view::View;

use crate::models::{Cart, CartItem, Product};

async fn current_cart(session: &Session) -> dust::Result<Option<Cart>> {
    let Some(token) = session.get::<String>("shop.cart") else {
        return Ok(None);
    };

    Cart::first_where(Cart::token.eq(token)).await
}

pub async fn store(session: Session, Valid(form): Valid<AddToCart>) -> dust::Result<Redirect> {
    let product = Product::find_or_fail(form.product_id).await?;

    if !product.active {
        return Ok(Redirect::back().with("error", "That product is no longer available."));
    }

    let cart = match current_cart(&session).await? {
        Some(cart) => cart,
        None => {
            let cart = create!(Cart { token: dust::str::uuid().to_string() }).await?;
            session.put("shop.cart", &cart.token);
            cart
        }
    };

    let existing = CartItem::first_where(
        CartItem::cart_id.eq(cart.id) & CartItem::product_id.eq(product.id),
    )
    .await?;

    let new_quantity = existing
        .as_ref()
        .map_or(form.quantity, |item| item.quantity + form.quantity);

    if new_quantity > product.stock {
        return Ok(Redirect::back().with("error", "That quantity is not available."));
    }

    match existing {
        Some(mut item) => update!(item { quantity += form.quantity }).await?,
        None => create!(CartItem {
            cart: &cart,
            product: &product,
            quantity: form.quantity,
        })
        .await?,
    }

    Ok(Redirect::to("/cart").with("status", "Added to your cart."))
}

The cart page loads the lines, loads each product, and calculates the subtotal in Rust. Do not store the subtotal on the cart: prices change, and a stored subtotal goes stale. The order is different. At checkout you copy the name and unit price into order_items, because that is the historical record the customer agreed to.

The AddToCart input marks product_id and quantity required and bounds the quantity with min_value(1) and max_value(10). The line routes check that the item belongs to the session's cart. A quantity of zero is not an update; it is a removal, and the remove route handles it. When the cart has no lines, render an empty state with a link back to the storefront, not an empty table with headings and no explanation.

Gotcha

Do not trust the product ID in the form alone. Reload the product, check active, and compare the quantity with the current stock. A form rendered an hour ago may describe a product that has changed.

Checkout

In plain words

Checkout turns a cart into an order in one transaction: create the order, copy the lines, lower the stock, and empty the cart. A unique token makes a double submit harmless.

Checkout is the one place where several writes must succeed together. The handler opens db::transaction, creates the order, copies each cart line into order_items, decrements the product stock, updates the order total, and deletes the cart's lines. The decrement is conditional on enough stock, so two checkouts cannot both take the last item. If any step fails, the whole thing rolls back and the cart is still there. The customer never receives an order confirmation for an order that was not saved.

The form carries a checkout_token generated when the checkout page first renders. orders.checkout_token is unique, and the handler checks it before doing any work. A refresh, a double click, or a retried request finds the existing order and redirects to its confirmation instead of creating a second one. If two requests race and one loses the unique insert, the handler looks the order up again and redirects to it; the unique index is the final guard, and the early lookup only makes the common case cheap. The CheckoutForm input marks the customer fields required, checks the email, and passes the token through.

src/http/handlers/checkout.rs
use dust::db;
use dust::mail;
use dust::model::{create, update};
use dust::prelude::*;

use crate::mail::OrderConfirmation;
use crate::models::{Cart, CartItem, Order, OrderItem, Product};

pub async fn store(
    session: Session,
    Valid(form): Valid<CheckoutForm>,
) -> dust::Result<Redirect> {
    if let Some(order) = Order::first_where(
        Order::checkout_token.eq(form.checkout_token.as_str()),
    ).await? {
        return Ok(redirect!(confirmation, &order));
    }

    let Some(cart_token) = session.get::<String>("shop.cart") else {
        return Ok(Redirect::to("/cart"));
    };

    let cart = Cart::first_where(Cart::token.eq(cart_token))
        .await?
        .ok_or_else(|| dust::abort(404))?;

    let items = CartItem::query()
        .filter(CartItem::cart_id.eq(cart.id))
        .get()
        .await?;

    if items.is_empty() {
        return Ok(Redirect::to("/cart"));
    }

    let placed = db::transaction(async |_tx| {
        let mut order = create!(Order {
            number: dust::str::uuid().to_string(),
            public_token: dust::str::uuid().to_string(),
            checkout_token: form.checkout_token.clone(),
            customer_name: form.name.clone(),
            customer_email: form.email.clone(),
            address_line: form.address_line.clone(),
            city: form.city.clone(),
            postcode: form.postcode.clone(),
            total: "0.00".parse::<dust::numeric::Decimal>()?,
            status: "pending".to_owned(),
        })
        .await?;

        let mut total = "0.00".parse::<dust::numeric::Decimal>()?;
        let mut lines = Vec::new();

        for item in &items {
            let product = Product::find_or_fail(item.product_id).await?;

            if !product.active || product.stock < item.quantity {
                return Err(dust::abort(409));
            }

            let line = &product.price * dust::numeric::Decimal::from(item.quantity);
            total = &total + &line;

            lines.push(create!(OrderItem {
                order: &order,
                product: &product,
                product_name: product.name.clone(),
                unit_price: product.price.clone(),
                quantity: item.quantity,
            })
            .await?);

            let changed = update!(Product::query()
                .filter(Product::id.eq(product.id) & Product::stock.ge(item.quantity)) {
                    stock -= item.quantity,
                })
                .await?;

            if changed == 0 {
                return Err(dust::abort(409));
            }
        }

        update!(order {
            number: format!("ORD-{:06}", order.id),
            total,
        }).await?;

        CartItem::query()
            .filter(CartItem::cart_id.eq(cart.id))
            .delete()
            .await?;

        mail::to(order.customer_email.as_str())
            .queue(OrderConfirmation { order: order.clone(), items: lines })
            .await?;

        Ok(order)
    })
    .await;

    let order = match placed {
        Ok(order) => order,
        Err(error) => {
            if let Some(order) = Order::first_where(
                Order::checkout_token.eq(form.checkout_token.as_str()),
            ).await? {
                order
            } else {
                return Err(error);
            }
        }
    };

    session.forget("shop.cart");

    Ok(redirect!(confirmation, &order))
}

Queue the confirmation inside the transaction, after the order and its lines exist. dust-framework waits for the commit before it dispatches the job, so a rollback discards the email and a committed order always has one. The handler then clears the cart token and redirects. A payment provider belongs inside the transaction only if its API supports an idempotency key and you can reconcile a timeout. Most applications charge first, then record the order, and treat the provider's webhook as the source of truth.

The confirmation page is bound by public_token, not by the numeric ID. Customers can share the link, and nobody can walk the order IDs of other customers. The admin pages use the numeric ID, behind authentication.

Gotcha

A database transaction is not a distributed transaction. It cannot roll back a card charge or an email the provider already accepted. Keep card charges and other provider calls after the commit, or give them an idempotency key of their own.

The admin

In plain words

Authentication says who you are; a policy says whether you may manage the catalog. The admin group checks the first, and every handler checks the second.

Add #[default] pub is_admin: bool to the User model and write a policy with one ability, manage. Do not hide the admin link and call it security. The route group uses Authenticate so a guest is sent to the login page, and each admin handler calls user.authorize(ShopPolicy::manage, ()).await?. The policy is the server-side answer; the hidden link is only a convenience.

src/policies/shop.rs
use dust::auth::policy;

use crate::models::User;

pub struct ShopPolicy;

#[policy]
impl ShopPolicy {
    pub fn manage(user: &User) -> bool {
        user.is_admin
    }
}

The admin routes share a prefix and middleware. Resource routes give products the usual CRUD endpoints without repeating each route. Orders are read-only, so only index and show are registered. The /admin index redirects to the product list.

src/routes/web.rs, admin section
use dust::auth::Authenticate;
use dust::routing::resource;

use crate::http::handlers::admin::{orders, products};

route.prefix("/admin").middleware(Authenticate).group(|route| {
    route.redirect("/", "/admin/products");
    resource!(products);
    resource!(orders::{index, show});
});

Creating a product validates the name, price, stock, and image, stores the image on the public disk, and generates the slug. NewProduct is a fill struct, so the form cannot set slug, active, or image_path directly; its image field is marked #[fill(skip)]. Updating a product follows the same path with _method=PUT in the form. The image field is optional; leaving it empty keeps the existing path instead of clearing it.

src/http/handlers/admin/products.rs, store
use dust::str::Str;

pub async fn store(
    user: Authenticated<User>,
    Valid(form): Valid<NewProduct>,
) -> dust::Result<Redirect> {
    user.authorize(ShopPolicy::manage, ()).await?;

    let image_path = match &form.image {
        Some(file) => Some(file.store("products").disk("public").await?),
        None => None,
    };

    let slug = form.name.slug();

    create!(Product {
        slug,
        active: true,
        image_path,
        ..form
    })
    .await?;

    Ok(Redirect::to("/admin/products").with("status", "Product created."))
}

Removing a product is the interesting case. A product referenced by an order_item cannot be deleted because of restrict_on_delete. The handler checks whether any order item references it. If one does, it sets active to false instead, which removes the product from the storefront but keeps the order history intact. Either way, its cart lines are cleared first; if nothing is ordered, the product row goes too. That is a business rule, not a database rule, and it belongs in the handler where you can explain it.

src/http/handlers/admin/products.rs
pub async fn destroy(
    user: Authenticated<User>,
    mut product: Product,
) -> dust::Result<Redirect> {
    user.authorize(ShopPolicy::manage, ()).await?;

    let ordered = OrderItem::query()
        .filter(OrderItem::product_id.eq(product.id))
        .exists()
        .await?;

    CartItem::query()
        .filter(CartItem::product_id.eq(product.id))
        .delete()
        .await?;

    if ordered {
        update!(product { active: false }).await?;
    } else {
        product.delete().await?;
    }

    Ok(Redirect::to("/admin/products").with("status", "Product removed."))
}
Gotcha

A foreign key that restricts deletes is a feature. It turns “I deleted the product and the old order lost its line” into a failed request you can handle. Archive the product; do not weaken the constraint to make the delete succeed.

The frontend

In plain words

One layout, ordinary io/ui classes, and forms that show what went wrong. The browser gets clear HTML; the server keeps the rules.

The layout holds the document, the header, the flash banner, and the footer. Pages extend it and override content. The product grid uses io/ui's row, col-*, card, and btn classes. Use semantic elements first: a link that navigates is an <a>, and a button that submits is a <button>. The class styles it; it does not change what it is.

resources/views/storefront/index.html
{% extends "layout.html" %}

{% block content %}
<div class="container py-5">
  <h1 class="mb-4">Shop</h1>

  {% if products %}
    <div class="row g-3">
      {% for product in products %}
        <div class="col-md-6 col-lg-4">
          <article class="card h-100">
            <div class="card-body">
              {% if product.image_path %}
                <img src="/storage/{{ product.image_path }}" alt="{{ product.name }}"
                     width="640" height="480" loading="lazy">
              {% endif %}
              <h2 class="card-title">{{ product.name }}</h2>
              <p class="text-muted">{{ product.price }}</p>
              <a class="btn btn-primary" href="/products/{{ product.slug }}">View</a>
            </div>
          </article>
        </div>
      {% endfor %}
    </div>
  {% else %}
    <div class="alert alert-info">No products are available yet.</div>
  {% endif %}
</div>
{% endblock %}

Every form that posts to a web route includes {{ csrf_field() }}. Give each form an explicit action and method; a form without an action posts to the current URL, which is rarely what you want after a validation redirect. For PUT and DELETE, add a hidden _method field.

When validation fails, dust-framework redirects back with the errors and the old input. Use old("name", "") to repopulate a field and error("name") to show its first message. Flash a status on the redirect with .with("status", "..."), and render it from session("status"). An error that belongs to the whole action, such as “only three left”, can use the same flash mechanism with a different key.

resources/views/checkout/show.html, form section
<form method="post" action="/checkout">
  {{ csrf_field() }}
  <input type="hidden" name="checkout_token" value="{{ checkout_token }}">

  <div class="form-group mb-3">
    <label class="form-label" for="name">Name</label>
    <input class="input" id="name" name="name"
           value="{{ old("name", "") }}">
    {% if error("name") %}
      <p class="form-text">{{ error("name") }}</p>
    {% endif %}
  </div>

  <button class="btn btn-primary" type="submit">Place order</button>
</form>

Empty states and error states are part of the page, not an afterthought. An empty cart gets a short explanation and a link, not a blank table. A sold-out product keeps its page but disables the button and says why. A flash message is removed after the next request, so it never becomes a permanent banner.

Gotcha

Template output is escaped automatically. Do not reach for a raw-HTML helper to render a product description; if you accept HTML from an admin, sanitize it first. Escaping is the default because most values are text.

Finishing

In plain words

Send the confirmation from the queue, test the whole flow through the real stack, then deploy the binary, run the migrations once, and start a worker.

The confirmation is a mailable. Derive Mailable, let the struct name choose the view, and pass the order and its lines. Queue it so the checkout response does not wait on the mail provider; the queue retries transient failures and survives a restart. The email shows the order number, the lines, and the total as they were saved. Its view is resources/views/mail/order-confirmation.html.

src/mail/order_confirmation.rs
use dust::mail::Mailable;

use crate::models::{Order, OrderItem};

#[derive(Mailable)]
#[mail(subject = "Your order is confirmed")]
pub struct OrderConfirmation {
    pub order: Order,
    pub items: Vec<OrderItem>,
}

Now test the promise, not the pieces. A feature test creates a product and a cart, posts the checkout form with a session that names that cart, and checks the database and the mail fake. Use with_session so each request sees the same cart token, and mail::fake() so the test never reaches a provider. Run it with refresh_database enabled, so each test gets its own migrated database.

tests/shop.rs
use dust::mail;
use dust::model::create;
use dust::testing::prelude::*;

use app::mail::OrderConfirmation;
use app::models::{Cart, Product};

#[dust::test]
async fn a_guest_can_check_out(app: Application) -> dust::Result<()> {
    let product = create!(Product {
        name: "Canvas tote",
        slug: "canvas-tote",
        description: None,
        price: "24.00".parse::<dust::numeric::Decimal>()?,
        stock: 10,
        active: true,
        image_path: None,
    })
    .await?;

    create!(Cart { token: "test-cart" }).await?;

    app.post("/cart/items")
        .with_session(json!({ "shop.cart": "test-cart" }))
        .form([
            ("product_id", product.id.to_string()),
            ("quantity", "2".to_owned()),
        ])
        .await
        .assert_redirect();

    let mail = mail::fake();

    app.post("/checkout")
        .with_session(json!({ "shop.cart": "test-cart" }))
        .form([
            ("name", "Ada Lovelace"),
            ("email", "ada@example.com"),
            ("address_line", "12 Analytical Way"),
            ("city", "London"),
            ("postcode", "N1 1AA"),
            ("checkout_token", "test-checkout"),
        ])
        .await
        .assert_redirect();

    app.assert_database_count("orders", 1).await;
    app.assert_database_has("order_items", json!({
        "product_id": product.id,
        "quantity": 2,
    }))
    .await;
    app.assert_database_empty("cart_items").await;
    mail.assert_queued::<OrderConfirmation>();

    Ok(())
}

Deploy the same binary you tested. Build with dust build --release, set APP_ENV=production and APP_DEBUG=false, run the migrations once from one server, and start both the web process and a queue worker. The worker is what sends the confirmation; without it, the order is saved and the email waits.

shell
$ dust build --release
$ ./bin/storefront migrate --force
$ ./bin/storefront queue:work

That is the shop. It has a catalog, a cart that survives the session, a checkout that is atomic and idempotent, an admin area behind a policy, a frontend with honest empty states, and a test that exercises the whole path. Everything else — tax, shipping, discounts, refunds, a payment provider — is a new decision with a new table or a new service, not a rewrite of this one.

Gotcha

Run the queue worker under a supervisor, and give it the same environment and working directory as the web process. A worker started from the wrong directory cannot find resources/views and every queued email fails to render.

Fin.

You've read the tour. The guides go deeper: every chapter above has a matching guide with the full rules, edge cases, and runnable examples.