Expand description
§lib-conf
Rust proc-macro crate providing library authors with first-class configuration for their end-users
§Overview
Included is a LibConfig derive macro to be used on named structs containing fields used to
publicly configure your library.
This derive macro generates a builder struct, an override struct (for runtime configuration), and helper methods.
§Features
- Provides ready-to-use runtime configuration of your library for dependant binaries
- Automatic builder generation
- Supports runtime revert of manually configured settings to library defined default
- Inline evaluation of library defined defaults
- Default expression gets copied into docs of all associated fn’s, preventing doc drift
- Supports runtime-only initialization of fields, deterring hard-coding of sensitive values
- Supports
serde-optional libraries - Full support for structs utilizing generics
§Attribute reference
Attribute documentation can be found on docs.rs.
§Examples
Please see the examples directory
and accompanying README.md file for real-world usage examples.
§Usage demo
For a brief demonstration of the capabilities provided bylib-conf, consider the following:
§The library
A new logging library, crab-log, wishes to expose some settings to its dependant crates.
This library provides a standard CrabLogConfig struct with various options.
It uses the LibConfig derive provided by lib-conf, and specifies a few attributes - one of
which handles setting default values.
use lib_conf::LibConfig;
/// Settings for `crab-log`
#[derive(Debug, Clone, LibConfig)]
pub struct CrabLogConfig {
/// Enables the Logger library
#[config(copy, default = true)]
pub(crate) enabled: bool,
/// Enables verbose logging
#[config(copy, default = false)]
pub(crate) verbose: bool,
/// Enables file logging at the given path
///
/// If no path is provided, file logging is disabled.
pub(crate) log_file_path: Option<String>,
}The LibConfig derive generates a builder struct, CrabLogConfigBuilder.
It also generates a second struct, CrabLogOverrideConfig, which can be used to handle
configuration at runtime.
§The binary
Later, a Rust developer (who unfortunately hasn’t heard of tracing) wants to use crab-log in
their binary.
They’re currently handling runtime configuration by loading a .env file with the help of
the dotenvy and config crates.
mod conf {
use config::Config;
/// Runtime configuration for my app
#[derive(Debug, Clone, Deserialize)]
pub struct AppRuntimeConfig {
pub db: DbConfig,
}
impl AppRuntimeConfig {
/// loads runtime config from .env file
pub fn try_load() -> Result<Self, Box<dyn std::error::Error>> {
dotenvy::dotenv()?;
let parsed = Config::builder()
.add_source(config::Environment::with_prefix("APP").separator("__"))
.build()?
.try_deserialize()?;
Ok(parsed)
}
}
#[derive(Debug, Clone, serde::Deserialize)]
pub struct DbConfig {
pub url: String,
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let runtime_config = conf::AppRuntimeConfig::try_load()?;
println!("Runtime config: {runtime_config:#?}");
Ok(())
}To setup crab-log in their app, they add a CrabLogOverrideConfig field to
their runtime config struct, AppRuntimeConfig:
/// Runtime configuration for my app
#[derive(Debug, Clone, Deserialize)]
pub struct AppRuntimeConfig {
pub db: DbConfig,
#[serde(default)]
pub crab: CrabLogOverrideConfig,
}To initialize crab-log, they use the provided builder and pass in the override config
from AppRuntimeConfig:
let runtime_config = conf::AppRuntimeConfig::try_load()?;
let crab_config = CrabLogConfig::builder()
.verbose(true)
.with_override(runtime_config.crab)
.build();They are able to configure crab-log with the builder, of course.
More importantly however, they can now set, override, or even revert
the settings from their .env file:
APP__DB__URL=http://localhost:5432/postgres
APP__CRAB__LOG_FILE_PATH=/tmp/out.log
APP__CRAB__VERBOSE_UNSET=trueThe fully working code for this demo can be found under examples/readme.
Additionally, the library in this example has its documentation published to showcase
the structs/docs generated by lib-conf.
For a more detailed version of this demo, see examples/1-typical.
§Installation
If serde is a mandatory dependency of your crate, you will likely want to add lib-conf with
the standard feature enabled:
$ cargo add lib-conf --features standard
Cargo.tomlequivalent:[dependencies] lib-conf = { version = "0.2", features = ["standard"] }
Otherwise, if serde is gated by a feature flag, you can add lib-conf with its default features,
and then include serde support in your own feature flag, e.g.
[features]
serde = [
# ...
"lib-conf/serde",
]
[dependencies]
lib-conf = "0.2"A breakdown of all available feature flags can be found below
§Feature flags
§default
- Only the
derivefeature is enabled by default.
§standard
- Enables what we believe to be the most common set of desired features.
This is provided as a feature group to allow for automatic opt-in of new, common use-case features introduced in future releases.
Currently includes: derive, serde, adapter
§derive
- Exposes the
LibConfigderive macro - the core functionality of this crate.
If you’re unsure whether or not you need this feature - then yes, you do.
§serde
- Enables automatically deriving
Deserializeon theOverridestruct - Decreases
Overridefield visibility frompubtopub(crate)
If serde is a mandatory dependency of your library, you should enable this.
If serde is optional, you can include this feature in your serde feature gate.
§adapter
- Exposes a small set of commonly used conversion handlers for
override_via.- e.g. Deserialize duration as seconds, minutes, etc.
While new adapters will likely be added in the future, this feature will only ever be concerned with core types.
In other words, this feature will never introduce new dependencies.
New adapters targeting 3rd party types will always be gated by a dedicated feature.
§adapter-tracing-level
- Provides an adapter for deserializing
tracing::Levelfields at run-time.
§syn-debug
- Enables the
extra-traitsfeature ofsyn.
This is almost certainly only useful for internal development and likely shouldn’t be enabled.
§Generation
Deriving LibConfig on a ‘MyLibraryConfig’ named struct will generate:
A settings builder struct: MyLibraryConfigBuilder
- Provides consumers with simple baseline configuration at compile time
An override settings struct: MyLibraryOverrideConfig
- Provides consumers with a
serde::Deserializevariant of the settings struct, allowing for out-of-the-box runtime adjustment of settings- designed to fit the configuration pattern already in-use by the binary. E.g. using
configto load settings from various files or env variables, or usingdotenvyto pull from a.envfile
- designed to fit the configuration pattern already in-use by the binary. E.g. using
impl’s on the derive struct: MyLibraryConfig
builder()fn- Getter methods
- Merge method to handle absorbing fields present in a
MyLibraryOverrideConfig Defaultimpl, if all fields are optional (Option<_>type ordefault = ..attr present)Add<MyLibraryOverrideConfig>impl, which calls the merge fn
§Benefits of builder/override pattern
- Provides out-of-the-box runtime configuration, bypassing the common need for binary-authors to manually create settings fields/structs used to initialize your library
- Supports adjusting settings at runtime that were not configured using the builder
- Allows for overriding settings at runtime that were configured using the builder
- Supports reverting settings at runtime that were configured using the builder - back to library defined defaults
- Allows for mapping values from deserialize-supported types, without relying on
serde_as - Retains compatibility in serde-optional libraries via feature flags
- Allows for gating fields to runtime-only initialization, which can greatly deter hard-coding of sensitive values (e.g. API tokens, database credentials, etc.)
§Notes
§Config struct name suffix
To infer the name to be used for the Override struct, lib-conf uses a
static list of struct suffixes to match your config struct against.
The following suffixes are currently supported:
Config(orConf)Options(orOpts)Parameters(orParams)Settings
Support for additional suffixes or custom naming schemes via attributes may be added in the future.
§Aliases for *_unset fields
The unset field has additional serde aliases to allow for reverting a
field to the library default using a few common words.
Currently supported are:
unsetresetrevertcleardefault
For example, to revert a field named foo to its library-defined default via a
.env file, any of the following would work:
FOO_UNSET=true # or
FOO_RESET=true # or
FOO_REVERT=true # or
FOO_CLEAR=true # or
FOO_DEFAULT=true§Progress
§Roadmap
- Add default value getters to Config struct
- Generate .env.example util fn for consumers, using defaults + required
- Add/confirm official support for nested usage
- e.g.
lib1 -> lib2 -> bin, where both libs uselib-confand both are exposed to binary - Support lib2 exposing a subset of lib1 options to bin
- e.g.
Modules§
- adapter
adapter - Exposes a small set of conversion handlers for
override_via
Derive Macros§
- LibConfig
derive - Attribute reference