Configuration
- Introduction
- Environment configuration
- Configuration files
- Your own configuration sections
- TOML configuration files
- Debug mode
- The base path
- Configuration in tests
Introduction
Your application needs settings that differ between your machine and your servers, such as your database credentials, your mail server, and the keys for the services you call. dust-framework reads most of these settings from environment variables, so you rarely need to write any configuration code.
When a setting needs more than a variable, such as a second database connection, you update one of the configuration files in src/config/, or add one of your own. Every setting is a typed field, so a misspelled setting is a compile error instead of a silent mistake.
Environment configuration
It's often helpful to have different settings depending on where your application runs. For example, you may use the memory cache on your machine and Redis in production.
dust-framework reads your environment variables from your application's .env file. A fresh application includes a .env.example file with the most common variables, and the installer copies it to .env for you. If you work with a team, keep .env.example up to date with placeholder values, so everyone can see which variables the application needs.
Variables set by your server or process manager take precedence over .env, so in production you may set them there instead.
[!WARNING] Your
.envfile holds secrets such as your encryption key and database password, so don't commit it to source control.
Wrap a value that contains spaces in double quotes. A value may refer to another variable as ${NAME}. If a value contains a $, such as a password, place it in single quotes to keep it as written:
APP_NAME="My Application"
MAIL_FROM_NAME="${APP_NAME} Support"
DATABASE_URL='postgres://app:s3cr$t@127.0.0.1/app'How settings are resolved
A setting can come from more than one place. dust-framework resolves it in this order, from highest priority to lowest:
- The process environment. Variables set by your shell, systemd, or your container platform.
.env. The file in your application's root directory..env.testing. Only in thetestingenvironment, and it replaces.envrather than adding to it.- The field's default. A
default = ..in#[env(..)], or the framework's own fallback.
That order means you can keep a development value in .env, override it for one command, and never edit the file:
APP_DEBUG=false dust serveDATABASE_URL=postgres://localhost/app_test cargo testThe process environment wins even when .env sets the same variable, so a host that manages secrets as environment variables doesn't need a .env file at all on the server. Do not rely on .env to change APP_BASE_PATH: the file is read from the directory the application starts in, so the setting can't move that directory. See The base path.
Configuration is read once, when the application starts. Changing a variable in .env while the server runs has no effect until it restarts; change the process environment for a long-running process manager and restart it.
Determining the current environment
The APP_ENV variable names the environment your application runs in. Set it to local on your machine and production on your servers. When APP_ENV isn't set, your application runs as production.
dust-framework is more careful in production. For example:
- Commands that can destroy data, such as
migrate, ask you to confirm before they run. - dust-framework only answers requests for the host in your
APP_URLand its subdomains.
You may also run scheduled tasks only in certain environments. Your tests always run in the testing environment.
You may check the environment anywhere in your application, such as in a handler:
use dust::config::app::Environment;let environment = &dust::config().app.env;if environment.is_local() { // The environment is local...}if matches!(environment, Environment::Local | Environment::Staging) { // The environment is either local or staging...}Configuration files
Environment variables cover most settings, but some need code, such as an extra cache store or a second database connection. For those, write a configuration file in src/config/. Your application already includes configuration files for the database and CORS, so you may edit those too.
A configuration file is a function marked #[config::section] that receives the environment and returns one of the framework's sections. For example, to add a second database connection for a reporting database in src/config/database.rs, start from Database::from_env(env) and register the extra connection:
// src/config/database.rsuse dust::config::database::{ConnectionConfig, Database};use dust::config::{self, Env};#[config::section]fn database(env: &Env) -> Database { let mut database = Database::from_env(env); database.add_connection( "reporting", ConnectionConfig::new(env.get("REPORTING_DATABASE_URL").unwrap_or_default()), ); database}Database::from_env reads your default connection from DB_CONNECTION, DATABASE_URL, and DB_MAX_CONNECTIONS. The database guide covers connections in detail.
When you create a new configuration file, such as src/config/cache.rs, add a mod line for it to src/config/mod.rs:
// src/config/mod.rsmod cache;Reading environment variables
A configuration file reads variables through its Env argument. The get method converts a variable into the type you ask for, such as a number, a bool, or a Driver. It returns None when the variable isn't set, so you may follow it with a default:
let lifetime: u64 = env.get("SESSION_LIFETIME").unwrap_or(120);let domain: Option<String> = env.get("SESSION_DOMAIN");
Read a variable your application can't run without, such as an API key, with require instead:
let stripe_key: String = env.require("STRIPE_KEY");When a required variable is missing, or a variable has a value that doesn't make sense, such as APP_DEBUG=maybe, your application refuses to start and lists every problem:
the environment is invalid:
- `APP_DEBUG` is set to `maybe`, which is invalid: provided string was not `true` or `false`
- `STRIPE_KEY` is required, but isn't setAccessing configuration values
You may read your configuration anywhere in your application, such as in a handler, middleware, or a console command, by calling dust::config(). Each part of the framework has its own section, such as app, session, or mail, and each setting is a field on it:
use dust::prelude::*;pub async fn show() -> String { let config = dust::config(); format!("Welcome to {}", config.app.name)}Settings you add for your own application, such as your Stripe keys, live in sections of your own. You read those by their type, as Section<Stripe> in a handler or dust::config().section::<Stripe>() elsewhere. The framework's sections work this way too, so Section<App> gives a handler the app section.
These are the sections the framework provides:
| Section | Holds | Read with |
|---|---|---|
app |
The name, environment, URL, debug flag, key, and base path. | config.app |
database |
Connections, the default connection, and pool sizes. | config.database |
cache |
The default store and each store's settings. | config.cache |
session |
The driver, lifetime, cookie, and same-site policy. | config.session |
queue |
The default connection and each connection's settings. | config.queue |
mail |
The default mailer, the from address, and each mailer. | config.mail |
filesystems |
The default disk and each disk's settings. | config.filesystems |
logging |
The level, format, and channels. | config.logging |
server |
The listen address, port, shutdown timeout, and connection limit. | config.server |
relay |
The relay's host, port, scheme, and credentials. | config.relay |
Each section is a plain struct with public fields, so reading a setting is a field access and a typo is a compile error. A section you don't touch keeps the values from .env and the framework's defaults.
Service providers, which packages use to plug into your application, are the exception. They run while your application is starting up, before dust::config() is available, so they read configuration from the app they receive instead. The configuration is complete by then, so a provider may use it to decide what to register, such as a route you only want on your machine:
use dust::container::Registrar;use dust::foundation::ServiceProvider;pub struct MailPreviewServiceProvider;impl ServiceProvider for MailPreviewServiceProvider { fn register(&self, app: &mut Registrar) { if app.config().app.env.is_local() { app.routing().web(|route| { route.get("/mail-preview", mail_preview::show); }); } }}Your own configuration sections
When your application calls a third-party service such as Stripe, it needs the service's key, and perhaps settings of its own, such as how long to wait for a response. Give those settings a section of your own: a struct that derives Section, with each field naming the environment variable it reads.
Your application's src/config/services.rs starts with a section for Sentry, as an example of how to define one. It's a convenient home for the credentials of the services your application calls, but you don't have to use it. To add Stripe, add a section next to Sentry's:
// src/config/services.rsuse dust::config::Section;use dust::time::ExactDuration;#[derive(Clone, Section)]pub struct Stripe { /// Stripe's secret key. #[env("STRIPE_KEY", required)] pub key: String, /// The account to send payouts to, if any. #[env("STRIPE_ACCOUNT")] pub account: Option<String>, /// How long to wait for Stripe before giving up. #[env("STRIPE_TIMEOUT", seconds, default = 10)] pub timeout: ExactDuration,}You don't need to register the section. dust-framework reads it from the environment when your application starts, and since STRIPE_KEY is required, your application won't start without it.
The timeout field shows how a section reads a length of time. Environment variables hold plain text, so seconds says that STRIPE_TIMEOUT=30 means 30 seconds. Without the variable, the timeout is 10 seconds, from default = 10. Either way, the field holds an ExactDuration that you may pass straight to the HTTP client, as the handler below does.
Each field's #[env(..)] takes the variable's name, followed by any of these options:
| Option | Means | Example |
|---|---|---|
required |
The application won't start without the variable | #[env("STRIPE_KEY", required)] |
default = .. |
The value to use when the variable isn't set | #[env("STRIPE_REGION", default = "us")] gives "us" |
seconds, minutes |
The variable is a whole number of seconds or minutes | #[env("STRIPE_TIMEOUT", seconds)] reads STRIPE_TIMEOUT=30 as 30 seconds |
separator = "," |
The variable is a list, split on the separator, for a Vec<String> field |
#[env("ADMIN_ROLES", separator = ",")] reads ADMIN_ROLES=admin,editor as ["admin", "editor"] |
The field's type decides how the text is parsed. Use String, bool, an integer or float type, a Vec<String> with separator, or a type that implements FromStr such as an enum or an ExactDuration. A bool accepts true and false; a value such as 1 or yes is an error, not a guess. An Option<T> field is optional even without default; every other field needs a value, a default, or required.
A variable that is present but empty counts as unset, so STRIPE_KEY= with required stops the application the same way a missing variable does. That is deliberate: an empty secret is almost always a broken deploy, not a valid value. If a setting needs to distinguish "not configured" from "configured to nothing", give it a sentinel value such as none rather than an empty string.
To use your section in a handler, accept it as a Section argument:
use dust::config::Section;use dust::http::client;use dust::prelude::*;use crate::config::services::Stripe;pub async fn store(stripe: Section<Stripe>) -> dust::Result<Redirect> { client::post("https://api.stripe.com/v1/payment_intents") .token(&stripe.key) .timeout(stripe.timeout) .form([("amount", "2000"), ("currency", "usd")]) .await?; Ok(Redirect::back())}Elsewhere, such as in a job or a console command, read it from the configuration with section:
let key = &dust::config().section::<Stripe>().key;TOML configuration files
Some settings are easier to keep in a file than in an environment variable: a list of origins, a retry schedule, or a value the application changes while it runs. dust-framework reads and writes those files from the config/ folder at the root of your application.
A document holds one area, and it may sit one folder deep:
config/
├── mail.toml
└── services/
└── stripe.tomlInside a document, a key walks the tables with dots. So smtp.port in config/mail.toml is the key smtp.port:
[smtp]host = "smtp.example.com"port = 587Read a key with tomconf::read. It returns None when the file or the key doesn't exist, so a missing setting is not an error:
let port: Option<u16> = dust::tomconf::read("mail", "smtp.port")?;let port = port.unwrap_or(587);Replace a value with tomconf::write. It creates the file and the tables on the way:
dust::tomconf::write("mail", "smtp.port", 587)?;Merge a table into what is already there with tomconf::update. Keys the new table doesn't mention are kept, which is how two parts of the application can own different keys of the same table:
let smtp = std::collections::BTreeMap::from([("host", "smtp.example.com")]);dust::tomconf::update("mail", "smtp", smtp)?;To read the whole document as a struct, use tomconf::read_file:
#[derive(serde::Deserialize)]struct Mail { smtp: Smtp,}#[derive(serde::Deserialize)]struct Smtp { host: String, port: u16,}let mail: Option<Mail> = dust::tomconf::read_file("mail")?;A few rules keep the folder predictable:
- A file name takes letters, digits,
_, and-, and at most one folder:mail,services/stripe. You may include the.tomlsuffix or leave it out. - A key takes the same characters, and its segments are separated by dots. There is no way to name a key outside its document.
- A write creates
config/and any subfolder it needs, and replaces the document atomically, so a request reading it at the same time sees the old document or the new one. - A value that no longer matches the type you read is an error, not a silent default. Fix the document or remove the key.
Atomic replacement protects a reader from half a file, not from a lost update. Two processes that read the same table, change it, and write it back can overwrite each other's keys. When several workers change the same document, keep the whole table in one process, or put the value in the database where a transaction can serialize the change. update merges the keys you pass into the table as it is on disk, so it is safer than write for two parts of the application that own different keys, but the read and the write still happen in sequence.
The TOML helpers are synchronous because they read and write a small file. Calling them from an async handler blocks that task for the duration of the read or write; the files are small, but don't put a large document or a network filesystem in this folder.
The free functions use the running application's config/ folder. A console command or a tool that works on another application builds a dust::tomconf::Store with Store::at, and calls the same methods:
let store = dust::tomconf::Store::at("/srv/shop");let retries: Option<u32> = store.read("queue", "retries.limit")?;Your application should be able to write the folder, because write and update change the files in place. If a deployment replaces the folder, keep the values the application changes somewhere else, such as the database.
When you are deciding where a setting belongs, use this rule of thumb:
| The setting | Keep it in |
|---|---|
| A secret, a URL, or anything that differs between machines | .env or the process environment |
| A typed collection the application needs at startup, such as an extra connection | src/config/ |
| A value the application reads and changes at runtime, or a list an operator edits | config/ TOML |
Debug mode
APP_DEBUG controls how much the user sees when something goes wrong. With debug mode on, server errors render a detailed page with the error, its causes, the route, and the request. Debug mode also picks up changes to your views without a restart. Your application's .env.example turns debug mode on for local development.
[!WARNING] Always set
APP_DEBUGtofalsein production. Debug pages can show your users sensitive details about your application.
The base path
Your application keeps its files in the public, storage, and resources directories. To build a path to one of them, use the app section's helpers:
let app = &dust::config().app;let invoice = app.storage_path("app/invoices/1234.pdf");let logo = app.public_path("images/logo.svg");dust-framework looks for these directories in the directory your application starts from. If a process manager starts your application from somewhere else, set APP_BASE_PATH in the process manager's environment:
APP_BASE_PATH=/srv/my-appSetting APP_BASE_PATH in .env doesn't work, because dust-framework reads .env from the directory your application starts from. You may instead start your application from its own directory, such as with systemd's WorkingDirectory= or a container's WORKDIR.
Configuration in tests
Each test gets a configuration of its own, so changing a setting in one test never affects another. Tests read your .env file (or .env.testing when present) and apply the overrides in src/testing.rs. The testing guide lists the overrides new applications start with.
To change a variable for one test, write a function in your test file that builds the application with with_env, then name it in the test's attribute:
use dust::testing::prelude::*;fn short_sessions() -> Application { app::testing::configure().with_env("SESSION_LIFETIME", "5").create()}#[dust::test(app = short_sessions)]async fn sessions_expire_after_five_minutes(app: Application) { assert_eq!(app.config().session.lifetime, 5.minutes());}with_env changes only the variable you name. Every other setting keeps its value from .env and src/testing.rs.