Package Development
- Introduction
- Creating a package
- Service providers
- Installing a package
- Configuration
- Services
- Routes
- Middleware
- Views
- Assets
- Migrations
- Commands and scheduled tasks
- Errors
- Logging
- Checks at boot
- Compatibility and versioning
- Testing packages
- Troubleshooting a package
Introduction
Packages are the primary way to extend dust-framework with reusable functionality, from a payment provider client to a full admin panel with its own routes, views, and database tables.
General-purpose Rust crates such as reqwest and chrono work in any application by adding them to Cargo.toml. dust-framework packages go further: they are standard Rust library crates that depend on dust-framework and integrate with an application through a service provider, adding configuration, services, routes, views, assets, and migrations.
To illustrate each piece, we'll build example-package, a package that serves inspiring quotes with its own configuration, service, routes, middleware, views, and stylesheet.
Creating a package
Create a library crate with cargo new --lib, then add dust-framework with default features disabled:
cargo add dust-framework --no-default-features# Cargo.toml[dependencies]dust-framework = { version = "0.1", default-features = false, features = ["database"] }Service providers
A service provider is a struct implementing ServiceProvider that serves as the entry point for everything your package registers:
use dust::config::{Config, Env};use dust::container::{Container, Registrar};use dust::foundation::ServiceProvider;pub struct InspireServiceProvider;impl ServiceProvider for InspireServiceProvider { fn config(&self, config: &mut Config, env: &Env) { // Register your package's default configuration... } fn register(&self, app: &mut Registrar) { // Register services, routes, views, commands, and more... } async fn boot(&self, app: &Container) -> dust::Result<()> { // Validate configuration or run startup checks... Ok(()) }}All three methods are optional. dust-framework invokes them in order:
configruns on every provider to register default configuration. Application configuration runs afterward so application settings override package defaults.registerruns on every provider to bind services, routes, views, commands, and other hooks. Configuration is final at this stage, so you can inspectapp.config()to decide what to register.bootruns once during application startup, before serving requests or running commands. Use it to resolve services and perform startup checks.
register cannot resolve services directly because services are constructed lazily on first use. When one service depends on another, resolve the dependency inside the service's factory.
What a provider can add
Inside register, Registrar exposes builders corresponding to the callbacks in an application's src/app.rs:
| Builder | Registers | Counterpart in src/app.rs |
|---|---|---|
routing() |
Routes and embedded assets | with_routing |
middleware() |
Global, web, and api middleware |
with_middleware |
views() |
View namespaces, engines, and shared data | with_views |
events() |
Event listeners | with_events |
commands() |
Console commands | with_commands |
schedule() |
Scheduled tasks | with_schedule |
ticks() |
Ticks that repeat in the server and queue workers | with_ticks |
errors() |
Custom error statuses and renderers | with_errors |
logging() |
Custom tracing layers |
with_logging |
head() |
Default <head> tags |
with_head |
migrations() |
Package migrations | with_migrations |
sessions(), cache(), mail(), queue(), features() |
Custom drivers such as a session store or cache store | with_services |
Packages cannot register authentication guards; only the application registers guards via with_auth.
Installing a package
Installing a dust-framework package into an application takes two explicit steps: adding the crate to your Cargo.toml and registering its service provider in src/app.rs. Registering providers explicitly keeps your application's startup sequence transparent and lets you see every package your application loads in one place.
Adding the crate
From your application's root directory, add the package using cargo add:
cargo add example-packageCargo resolves the latest compatible version and adds the crate under [dependencies] in your Cargo.toml:
[dependencies]example-package = "0.1.0"When developing a package locally alongside an application, you can point Cargo directly at your local checkout instead using cargo add --path ../example-package.
Enabling package features
To keep compile times fast and binaries small, packages often place optional capabilities (such as a pdf feature for exporting quotes as PDFs) behind Cargo features so applications only compile what they actually use. You can enable optional features when adding the package:
cargo add example-package --features pdfOr enable them directly in Cargo.toml:
[dependencies]example-package = { version = "0.1.0", features = ["pdf"] }You do not need to manually enable any dust-framework features that a package depends on; Cargo merges the package's required features with your application's automatically during compilation.
Registering the provider
Adding a crate to Cargo.toml makes its types available to import, but it does not wire anything into your application yet. To activate the package's configuration defaults, services, routes, views, middleware, and migrations, register its service provider in src/app.rs using with_providers:
use dust::Application;Application::configure() .with_providers(|providers| { providers.add(example_package::InspireServiceProvider); })Providers execute in the order they are added, so if two providers bind the same service or setting, the later provider overrides the earlier one. Regardless of where with_providers appears in your Application::configure() chain, your application's own callbacks (with_config, with_services, with_routing, with_middleware, and so on) always run after all providers, ensuring your application can always customize or replace any package default.
Configuration
Most packages need to expose configurable settings such as API keys, feature toggles, or default behaviors. Inside your package, define a public configuration section struct by deriving Section, and annotate its fields with #[env(..)] attributes so applications can configure them through environment variables:
use dust::config::Section;#[derive(Debug, Clone, Section)]pub struct InspireConfig { #[env("INSPIRE_HEADER", default = true)] pub header: bool, #[env("INSPIRE_QUOTES", separator = "|")] pub quotes: Vec<String>,}While dust-framework discovers #[derive(Section)] structs in an application's own app crate automatically, packages opt in from their service provider's config method. Calling config.discover(env!("CARGO_CRATE_NAME"), env) inside your package's ServiceProvider::config method loads every derived section in your package crate from the environment:
use dust::config::{Config, Env};use dust::foundation::ServiceProvider;impl ServiceProvider for InspireServiceProvider { fn config(&self, config: &mut Config, env: &Env) { config.discover(env!("CARGO_CRATE_NAME"), env); }}If you need to construct a configuration section in Rust rather than deriving Section, you may register it directly with config.set(..) inside your package provider's config method instead.
Because every package provider's config method runs before the application's own with_config callback, an application that installs your package can override individual fields in src/app.rs while keeping the rest of your package's defaults intact. Derive Clone on your section struct so consuming applications can mutate it with section_mut:
// src/app.rs (in the consuming application)use example_package::InspireConfig;use dust::Application;Application::configure() .with_config(|config, _| { config.section_mut::<InspireConfig>().header = false; })Services
Register your package's services inside register. For example, this registers a Quotes singleton initialized from InspireConfig:
use dust::container::Registrar;#[derive(Clone)]pub struct Quotes { quotes: Vec<String>,}impl Quotes { pub fn new(quotes: Vec<String>) -> Self { Self { quotes } } pub fn all(&self) -> &[String] { &self.quotes }}fn register(&self, app: &mut Registrar) { app.singleton(async |app| { let config = app.config().section::<InspireConfig>(); Ok(Quotes::new(config.quotes.clone())) });}Because singleton factories run lazily on first resolution, they always see the application's final configuration.
You may also define services using #[singleton] or #[bind] and call app.discover to register all attribute-based services, command functions, listeners, and scheduled tasks in your crate at once:
use dust::config::Section;use dust::container::singleton;#[singleton]async fn quotes(config: Section<InspireConfig>) -> dust::Result<Quotes> { Ok(Quotes::new(config.quotes.clone()))}fn register(&self, app: &mut Registrar) { app.discover(env!("CARGO_CRATE_NAME"));}Applications can inject your service with Inject<Quotes> or replace it in with_services.
Routes
Register routes in the web or api group through app.routing():
use dust::container::{Inject, Registrar};fn register(&self, app: &mut Registrar) { app.routing().web(|route| { route.get("/inspire", inspire); });}/// `GET /inspire`: every quote, one per line.pub async fn inspire(quotes: Inject<Quotes>) -> String { quotes.all().join("\n")}Make your route handlers pub. Because routes are identified by their handlers, applications link to package routes via the handler path, such as route!(example_package::inspire)?.
Middleware
Your package can add global, web, or api middleware through app.middleware() inside its service provider's register method. Because every provider's config method and the application's with_config callback have already run by the time register executes, you can inspect the final InspireConfig and attach AddInspiration only when header is enabled:
use dust::container::Registrar;use dust::foundation::ServiceProvider;impl ServiceProvider for InspireServiceProvider { fn register(&self, app: &mut Registrar) { if app.config().section::<InspireConfig>().header { app.middleware().web(|web| { web.append(AddInspiration); }); } }}Consuming applications run their own with_middleware callback after all providers, so an application can also remove a package's middleware in src/app.rs using web.remove::<AddInspiration>().
Views
Because a deployed dust-framework application is a single binary without your package's source tree, embed package templates using dust::embed! (resolved relative to your package's Cargo.toml) and register them under a namespace:
use dust::container::Registrar;fn register(&self, app: &mut Registrar) { app.views().namespace("inspire", dust::embed!("resources/views"));}Render namespaced views with view("inspire::quote", data! { quote }). Applications can override any package view by placing a file at resources/views/vendor/inspire/quote.html.
Your package does not need to enable the minijinja feature for .html views in production, since the application provides the engine. Enable it in dev-dependencies for your package's own tests:
cargo add --dev dust-framework --no-default-features --features minijinjaIn debug builds, dust-framework reads embedded files directly from your package directory so template edits appear without recompiling (adding a new file still requires a rebuild).
Assets
Embed stylesheets, scripts, and images with dust::embed! and register them via app.routing().assets(..). dust-framework serves them under /vendor/<namespace>/<path>:
use dust::container::Registrar;fn register(&self, app: &mut Registrar) { app.routing().assets("inspire", dust::embed!("public"));}Reference package assets using vendor_asset in Rust or templates:
<link rel="stylesheet" href="{{ vendor_asset("inspire", "inspire.css") }}">dust-framework appends a content hash query string (/vendor/inspire/inspire.css?id=34b6aba9…) for cache busting. Applications can override any asset by placing a replacement file in public/vendor/inspire/.
Assets that need a build
A package's assets don't need a framework-specific build. If you write plain CSS and JavaScript, put them under public/ and embed that directory, as above. If you use a compiler or bundler, let it write its output to a directory such as dist/, then embed that directory instead:
fn register(&self, app: &mut Registrar) { app.routing().assets("dashboard", dust::embed!("dist"));}<link rel="stylesheet" href="{{ vendor_asset("dashboard", "style.css") }}"><script type="module" src="{{ vendor_asset("dashboard", "app.js") }}"></script>Set the bundler's public path, or base URL, to /vendor/<namespace>/ so relative font and image URLs in your CSS resolve under the route the framework serves. Keep the output flat enough that vendor_asset can name each file directly; a hashed filename works, because vendor_asset adds its own hash for cache busting.
embed! reads dist/ when the consuming application compiles your package, so the directory must exist in the published crate. Add it to Cargo.toml explicitly, even when .gitignore ignores it:
[package]include = ["src/**", "resources/views/**", "dist/**", "Cargo.toml", "README.md", "LICENSE"]Commit the built output, or build it as part of your release process before cargo publish. A consumer cannot run your bundler.
Including the build in the published crate
The include list above is what makes the assets survive cargo publish. Cargo includes only the files it lists, plus a few defaults; a dist/ directory that .gitignore ignores is still included when the manifest lists it. Check the crate's contents before publishing:
cargo package --listThe list should show every file dust::embed! reads. If it doesn't, the package builds locally but fails when a consumer compiles it.
Migrations
Packages that store database tables can ship migrations and register them via app.migrations(). Running migrate in an application executes package and application migrations together in filename order:
use dust::container::Registrar;fn register(&self, app: &mut Registrar) { app.migrations().add(dust::db::migrations!("database/migrations"));}Because dust::db::migrations! scans your database/migrations directory at compile time, Cargo will not automatically detect newly added migration files unless you instruct it to watch the directory. Add a build.rs file at the root of your package crate so Cargo recompiles whenever a migration file is added, edited, or renamed:
// build.rsfn main() { println!("cargo::rerun-if-changed=database/migrations");}Commands and scheduled tasks
Packages can register their own console commands so applications gain new CLI commands as soon as the package's service provider is installed. Define a command function in your package with #[command], injecting any services it needs with Inject<T>:
use dust::console::{Console, command};use dust::container::Inject;/// List every inspiring quote.#[command("inspire:list")]pub async fn list_quotes(console: &mut Console, quotes: Inject<Quotes>) { for quote in quotes.all() { console.line(quote); }}To register your package's #[command] functions, call app.discover(env!("CARGO_CRATE_NAME")) inside your service provider's register method (or register command structs explicitly with app.commands().add::<ListQuotes>()). If a consuming application defines a command with the same name, the application's command overrides the package's.
If your package needs to run recurring background work, you can also register scheduled tasks inside your service provider's register method via app.schedule():
use dust::container::Registrar;use dust::foundation::ServiceProvider;impl ServiceProvider for BillingServiceProvider { fn register(&self, app: &mut Registrar) { app.schedule() .command("billing:sync-invoices") .daily_at("08:00"); }}Scheduled package tasks run automatically whenever the consuming application runs its scheduler.
Errors
Attach HTTP status codes to your package's domain errors using #[derive(Status)] so consuming applications do not have to map each error manually:
use dust::errors::Status;#[derive(Debug, thiserror::Error, Status)]#[error("The card was declined.")]#[status(402)]pub struct CardDeclined;For additional error handling, use app.errors() inside your service provider's register method (which exposes the same Errors builder as an application's with_errors). For example, a billing package might suppress logging for expected declines, keep sensitive payment fields out of flashed old input, and render a structured JSON response for API requests:
use dust::container::Registrar;use dust::foundation::ServiceProvider;use dust::prelude::*;use serde_json::json;impl ServiceProvider for BillingServiceProvider { fn register(&self, app: &mut Registrar) { let errors = app.errors(); errors.dont_report::<CardDeclined>(); errors.dont_flash(["card.number", "card.cvc"]); errors.render(|error: &CardDeclined, request, status| { if !request.wants_json() { return None; } let body = json!({ "error": "card_declined", "message": error.to_string(), }); Some((status, Json(body)).into_response()) }); }}Consuming applications run their own with_errors callback after all providers, so application status mappings and renderers always take precedence over a package's defaults for the same error type.
Logging
Packages can attach custom tracing layers (such as an error tracker or telemetry exporter) through app.logging():
use dust::container::Registrar;fn register(&self, app: &mut Registrar) { if app.config().section::<TelemetryConfig>().enabled { app.logging().layer(telemetry_layer()); }}To learn how to build and filter custom tracing layers, check out sending logs elsewhere in the logging guide.
Checks at boot
Returning an error from boot prevents the application from starting, catching misconfigurations at deploy time rather than on the first request:
use dust::container::Container;use dust::http::HeaderValue;async fn boot(&self, app: &Container) -> dust::Result<()> { if !app.config().section::<InspireConfig>().header { return Ok(()); } let quotes = app.resolve::<Quotes>().await?; if let Some(quote) = quotes .all() .iter() .find(|quote| HeaderValue::from_str(quote).is_err()) { return Err(dust::abort_with( 500, format!("The quote `{quote}` can't be sent in a header."), )); } Ok(())}The startup error names your provider so developers can immediately identify the failing package. Reserve boot for startup checks like this; keep registrations in register and service initialization in service factories.
Compatibility and versioning
A package is published on its own schedule, so it must say which framework versions it supports. Depend on the façade with the same semver range you tested against:
[dependencies]dust-framework = { version = "0.1", default-features = false }Before 1.0, a minor framework release may break an internal API. Pin the range you test and release a new package version when you move to a newer framework. Do not depend on a crates/* package such as dust-http directly; those crates are internal, and only the façade follows semver. The repository's rules state this in R9, and a package that reaches past the façade breaks when the internals move.
Keep the framework's optional features opt-in. A package that needs the database enables it in its own dependency, but the consuming application decides which driver, so don't force database-postgres. A feature that only exists for your tests belongs in [dev-dependencies], not in the package's default features.
When you change a package's public API, bump the version that matches the change. A new required configuration variable, a renamed service, or a changed route path is a breaking change for an application, even when the Rust signature still compiles. Record the migration in the package's README and, if the package ships a guide, in docs/.
Testing packages
Place your package's integration tests in the tests/ directory at the root of your package crate (for example, tests/package.rs). Because Cargo compiles files in tests/ as separate crates, your tests exercise your package through its public API as a consuming application will.
If your tests need a dust-framework feature your package does not enable in [dependencies] (such as minijinja for rendering .html views), add it under [dev-dependencies] in Cargo.toml so it is never pulled into applications that install your package:
# Cargo.toml[dev-dependencies]dust-framework = { version = "0.1", default-features = false, features = ["minijinja"] }Unlike an application, a package does not have a src/app.rs or src/testing.rs. Instead, define configure and create helpers in tests/package.rs that build a minimal test application with for_testing(env!("CARGO_MANIFEST_DIR")) and register your service provider, then pass create to #[dust::test(app = create)]:
// tests/package.rsuse example_package::{InspireConfig, InspireServiceProvider};use dust::foundation::ApplicationBuilder;use dust::testing::prelude::*;fn configure() -> ApplicationBuilder { Application::configure() .for_testing(env!("CARGO_MANIFEST_DIR")) .with_providers(|providers| { providers.add(InspireServiceProvider); })}fn create() -> Application { configure().create()}#[dust::test(app = create)]async fn the_package_route_and_assets_work(app: Application) { let response = app.get("/inspire").await; response.assert_ok(); assert!(response.header("x-inspiration").is_some()); app.get("/vendor/inspire/inspire.css") .await .assert_ok() .assert_header("content-type", "text/css");}#[dust::test(app = create)] calls create() for every test so each test boots an isolated application in the testing environment with a fresh encryption key and in-memory fallbacks for unset settings. Extract the helper rather than sharing a single booted Application across tests: giving each test its own application keeps sessions, caches, clocks, fakes, and configuration overrides isolated so tests run safely in parallel.
Returning an ApplicationBuilder from configure() gives you one place to set shared test defaults, such as .with_envs(..) for test environment variables, .refresh_database() for packages that ship migrations, or host application routes via .with_routing(..) to verify package middleware and injected services:
use example_package::{InspireServiceProvider, Quotes};use dust::container::Inject;use dust::foundation::ApplicationBuilder;use dust::testing::prelude::*;fn configure() -> ApplicationBuilder { Application::configure() .for_testing(env!("CARGO_MANIFEST_DIR")) .with_providers(|providers| { providers.add(InspireServiceProvider); }) .with_routing(|routing, _| { routing.web(|route| { route.get("/host", async |quotes: Inject<Quotes>| { quotes.all().join("\n") }); }); })}When your test suite grows across multiple files under tests/, Cargo compiles each file as its own crate. Move configure() and create() into tests/common/mod.rs as pub functions, declare mod common; in each test file, and pass common::create to #[dust::test]:
// tests/middleware.rsmod common;use dust::testing::prelude::*;#[dust::test(app = common::create)]async fn web_responses_include_the_inspiration_header(app: Application) { let response = app.get("/host").await; response.assert_ok(); assert!(response.header("x-inspiration").is_some());}When a single test needs custom environment variables or configuration overrides, omit the Application argument on #[dust::test] and build the customized application from configure() inside the test:
#[dust::test]async fn disabling_the_header_skips_the_middleware() { let response = configure() .with_envs([("INSPIRE_HEADER", "false")]) .create() .get("/inspire") .await; response.assert_ok(); assert_eq!(response.header("x-inspiration"), None);}Similarly, to test a boot check that should reject invalid configuration, call .create().boot().await directly and assert that booting fails:
#[dust::test]async fn invalid_quotes_stop_the_application_from_booting() { let error = configure() .with_config(|config, _| { config.set(InspireConfig { header: true, quotes: vec!["Line one\nLine two".to_owned()], }); }) .create() .boot() .await .expect_err("booting should fail") .to_string(); assert!(error.contains("can't be sent in a header"));}Run your package's test suite with cargo test. To explore additional HTTP assertions, authentication helpers, and subsystem fakes, check out the testing guide.
Troubleshooting a package
| Symptom | What to check |
|---|---|
| The application starts but none of the package's routes exist | The provider is registered in src/app.rs with with_providers. Adding the crate is not enough. |
| A configuration variable is ignored | The package's config method calls config.discover(env!("CARGO_CRATE_NAME"), env), or registers the section with config.set. |
Inject<Quotes> fails |
The service is registered in register, not in config, and the type matches exactly. |
| A package view renders the wrong file | The namespace is registered, the name uses namespace::, and the application's resources/views/vendor/<namespace>/ doesn't hold an override. |
Assets return 404 |
app.routing().assets(...) is called with the same namespace and path the template links, and the embedded directory was included in the crate. |
| A package command is missing | The function is #[command] and app.discover(env!("CARGO_CRATE_NAME")) runs, or the struct is added with app.commands().add. |
| Migrations don't run when added | The package has a build.rs with cargo::rerun-if-changed=database/migrations; Cargo doesn't watch the directory on its own. |
| Booting fails with the provider's name | A boot check rejected the configuration; fix the value it names, or make the check conditional. |
| The package compiles alone but fails in an application | The application is missing a feature the package assumes, or dist/ wasn't included; run cargo package --list. |
The error for a failed provider names it, which is why a boot check should use dust::abort_with or a typed error rather than a bare panic. A panic still fails startup, but the message doesn't say which package caused it.