Configuration
Layer defaults, files, the environment and explicit values into one typed value, and have wire() report every problem with its source.
ulo-config builds a Config in main from sources the application names. Each source overrides the ones before it. The Config is handed to the modules that read it. wire(), the phase that builds the container (see Application phases), reports every problem in it in one report, with the field's path and the file and line, or the variable, that supplied the value.
[dependencies]
ulo-config = "=0.1.0-alpha.3"Layers
This is examples/33-config. Each source overrides the ones added before it:
use ulo_config::{Config, Defaults, DotEnv, Env, File, Values};
pub fn config(dir: &Path, env: Env, explicit: Values) -> Config {
Config::builder()
.source(Defaults::of::<Fallbacks>())
.source(File::toml(dir.join("app.toml")))
.source(DotEnv::file(dir.join(".env")).optional().prefix("APP_").separator("__"))
.source(env.prefix("APP_").separator("__"))
.source(explicit)
.load()
}load() never fails. A source that cannot be read or does not parse is recorded inside the value and reported by wire().
main decides where the process environment and the explicit values enter. No source finds the environment on its own, and a .env file is read into the layer and never into the process environment:
// The process environment is read here and nowhere else: no source finds it by itself.
let config = ex_33_config::config(&dir, Env::process(), Values::new().set("http.host", "127.0.0.1").set("http.port", port));A test passes Env::from_map([...]) instead.
Reading the configuration
ConfigModule::<T>::new(&config) registers the whole tree as one binding of type T and exports it. The module that imports it holds the Config, because ConfigModule reads its sections while the module registers:
use serde::Deserialize;
use ulo::{Module, ModuleDef, ModuleIdentity, controller};
use ulo_config::{Config, ConfigModule};
#[derive(Clone, Debug, Deserialize)]
pub struct AppConfig {
pub greeting: String,
pub http: Http,
pub database: Database,
}
pub struct AppModule {
config: Config,
}
impl Module for AppModule {
fn identity(&self) -> ModuleIdentity {
ModuleIdentity::of_type::<Self>()
}
fn register(&self, m: &mut ModuleDef<'_>) {
m.import(ConfigModule::<AppConfig>::new(&self.config).deny_unread());
m.controller::<SettingsController>();
}
}A provider then takes Dep<AppConfig>. T must be Deserialize + Clone.
An integration reads its own section by path, without knowing the application's type. SqlxModule::<Postgres>::from_config(&config, "database") deserialises the database section at its own registration and records a failure through the same report. See Databases.
Loading happens in main
Registration is synchronous and does no I/O, so configuration cannot load while the application wires. Loading in main also keeps every blocking file read off a runtime worker.