setty
setty is an opinionated configuration crate.
It can be used by:
- Applications - to load and merge config from multiple sources and formats and generate documentation and JSON Schema
- Libraries - to define their own config DTOs without needing to fully anticipate all format and style preference that different applications may choose for their config.
Motivation
Problem Statement
Popular configuration crates like config and figment deal with reading and merging values from multiple sources. They leave it up to you to handle parsing using serde derives. This is a good separation of concerns, but it leaves a lot of important details to you. Like remembering to put #[serde(deny_unknown_fields)] not to realize that your production config had no effect because of a small typo.
Also, you may need features beyond parsing:
- Documentation generation
- JSONSchema generation (e.g. for Helm chart values validation)
- Auto-completion in CLI
- Deprecation mechanism
- Per-field combine strategies (e.g. keep first value, replace with latest, merge arrays)
Layering more libraries and macros makes your models very verbose:
/// No inline default epressions in `serde` - must use functions
And even if you power through this problem in your application - you'll face a composability problem - how to surface configuration from the sub-modules you depend on in your app config. If a config types defined in a module do not use your ideal set of derive macros - you'll be forced to define a temporary DTO and write lots of mapping logic... yet more boilerplate!
Solution
Use one simple macro:
/// Docstrings will appear in Markdown and JSON Schema outputs
Control what behavior you need via create features:
= { = "*", = [
# These traits will be derived for all types
"derive-clone",
"derive-debug",
"derive-partial-eq",
"derive-eq",
"derive-deserialize",
"derive-serialize",
"derive-jsonschema",
"derive-validate",
# Pick one: A case for struct fields (applies `#[serde(renameAll = "...")]`)
"case-fields-lower",
"case-fields-pascal",
"case-fields-camel",
"case-fields-snake",
"case-fields-kebab",
# Pick one: A case for enum variants (applies `#[serde(renameAll = "...")]`)
"case-enums-lower",
"case-enums-pascal",
"case-enums-camel",
"case-enums-snake",
"case-enums-kebab",
"case-enums-any", # Uses one of other cases on write but accepts any on read
# Pick input format(s)
"fmt-toml",
"fmt-json",
"fmt-yaml",
# Pick generation target formats
"gen-jsonschema",
"gen-markdown",
# Extra types support
"types-bigdecimal",
"types-chrono",
"types-duration-string",
"types-url",
] }
By specifying features only at the top-level application crate - the desired derives will be applied to configs of all crates in your dependency tree allowing you to directly embed their DTOs. In other words library developers don't have to predict and align every aspect of configuration with the app layer - they can focus only on DTO types.
Finally, load the config:
use ;
use ;
let cfg: AppConfig = new
// Specify sources in priority order. Latter sources replace or merge
// with values in earlier ones (see also `combine()` attribute).
.with_sources
// Env source allows to pass overrides like:
//
// APP_CONFIG__database__schema_name=my_schema
// APP_CONFIG__database__connection_timeout=30s
// APP_CONFIG__encryption='{"algo": "Aes256Gcm", "nonce": "..."}'
//
// I switch to YAML for env vars to avoid excessive quotes in most cases
.with_source
// Merges the values and deserializes to config type
.extract?;
Alternatives
- Rolling your own declarative macros (see example in
datafusion)
Usage Examples
See the examples directory.
API
Derive Macros
Config- main workhorseDefault- same asstd::Defaultbut recognizes defaults provided via#[config(default = $expr)]attributes
Proc Macros
derive- a replacement for standard#[derive(...)]macro that will de-duplicate derivations - this is most useful for e.g.#[setty::derive(setty::Config, Clone)]which allows type to implementCloneeven when top-level featurederive-cloneis disable, and not hit duplicate trait impl error when feature is enabled.
Field Attributes
These arguments can be specified in #[config(...)] field attribute:
default- UseDefault::defaultvalue if field is not presentdefault = $expr- Specifies expression used to initialize the value when it's not present in configdefault_str = "$str"- Shorthand fordefault = "$str".parse().unwrap()combine(keep | replace | merge)- Allows overriding how values are combined across different config files- Possible values:
keep- keeps first seen valuereplace- fully replaces with the new valuemerge- merges object keys and concatenates arrays, merge is smart and will not merge values across different enums
- Default behavior:
replacefor all known value typesmergefor unknown types- You will need to implement
setty::combine::Combinefor it to work for custom types Configderive macro automatically implements it for you- If you don't want any merging - simply override to use
combine(replace)
- You will need to implement
- Possible values:
Interaction with other attributes
#[deprecated(since = "..", reason = "..")]attribute (and its other forms):- Will be propagated
- A
"deprecation": {"since": "..", "reason": ".."}will be added to JSON schema - Deprecation callback will be called if value is present in the config during loading
#[serde(...)]attribute will be propagated and can be used to override default behaviour (e.g.#[serde(tag = "type")])#[schemars(...)]attribute will be propagated