Skip to main content

vld_app/
config.rs

1//! # `vld_app::config` — validate configuration with `vld`
2//!
3//! Load configuration with [config-rs](https://docs.rs/config) (feature
4//! `config-rs`; config `>=0.14, <0.16`) or
5//! [figment](https://docs.rs/figment) (feature `figment`, 0.10) and parse it
6//! into a `vld` type at startup: a typed settings struct, or a
7//! [`VldConfigError`] listing every invalid key. The backend crates are not
8//! re-exported; depend on them yourself.
9//!
10//! # Quick Start (config-rs)
11//!
12//! ```rust,no_run
13//! # #[cfg(feature = "config-rs")] {
14//! use vld::prelude::*;
15//! use vld_app::config::from_config;
16//!
17//! vld::schema! {
18//!     #[derive(Debug)]
19//!     pub struct AppSettings {
20//!         pub host: String => vld::string().min(1),
21//!         pub port: i64    => vld::number().int().min(1).max(65535),
22//!     }
23//! }
24//!
25//! let config = config::Config::builder()
26//!     .add_source(config::File::with_name("config"))
27//!     // Env values are strings; `try_parsing(true)` turns APP_PORT=8080 into a
28//!     // number so it passes `number().int()`.
29//!     .add_source(config::Environment::with_prefix("APP").try_parsing(true))
30//!     .build()
31//!     .unwrap();
32//!
33//! let settings: AppSettings = from_config(&config).unwrap();
34//! println!("Listening on {}:{}", settings.host, settings.port);
35//! # }
36//! ```
37//!
38//! # Quick Start (figment)
39//!
40//! ```rust,no_run
41//! # #[cfg(feature = "figment")] {
42//! use vld::prelude::*;
43//! use vld_app::config::from_figment;
44//!
45//! vld::schema! {
46//!     #[derive(Debug)]
47//!     pub struct AppSettings {
48//!         pub host: String => vld::string().min(1),
49//!         pub port: i64    => vld::number().int().min(1).max(65535),
50//!     }
51//! }
52//!
53//! let figment = figment::Figment::new()
54//!     .merge(figment::providers::Serialized::defaults(
55//!         serde_json::json!({"host": "0.0.0.0", "port": 3000}),
56//!     ))
57//!     .merge(figment::providers::Env::prefixed("APP_"));
58//!
59//! let settings: AppSettings = from_figment(&figment).unwrap();
60//! # }
61//! ```
62//!
63//! # Typed env values
64//!
65//! `from_config`, `from_builder` and `from_figment` validate with
66//! [`vld::schema::parse_coerced`]: env values that the backend parsed into
67//! numbers / booleans are turned back into text where the schema expects a
68//! string (`APP_HOST=12345` into `vld::string()` is `"12345"`), and a single
69//! value is wrapped into an array where the schema expects one. The text is
70//! the backend's parsed value, so a lossy parse (`"01234"` → `1234`) yields
71//! `"1234"`. [`from_value`] validates the JSON value **as is** (strict);
72//! [`from_value_coerced`] applies the same coercion as the backends.
73//!
74//! Guide: <https://s00d.github.io/vld/integrations/config-cli/config>
75
76use std::fmt;
77use vld::schema::VldParse;
78
79/// Error type for config validation.
80#[derive(Debug)]
81pub enum VldConfigError {
82    /// Failed to extract/deserialize config into JSON.
83    Source(String),
84    /// Validation failed — contains all vld validation issues.
85    Validation(vld::error::VldError),
86}
87
88impl fmt::Display for VldConfigError {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match self {
91            VldConfigError::Source(msg) => write!(f, "config error: {msg}"),
92            VldConfigError::Validation(err) => write!(f, "validation error: {err}"),
93        }
94    }
95}
96
97impl std::error::Error for VldConfigError {
98    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
99        match self {
100            VldConfigError::Validation(err) => Some(err),
101            VldConfigError::Source(_) => None,
102        }
103    }
104}
105
106impl From<vld::error::VldError> for VldConfigError {
107    fn from(err: vld::error::VldError) -> Self {
108        VldConfigError::Validation(err)
109    }
110}
111
112// ---------------------------------------------------------------------------
113// config-rs backend
114// ---------------------------------------------------------------------------
115
116/// Load and validate configuration from a [`config::Config`] instance.
117///
118/// The config is first deserialized into a `serde_json::Value`, then
119/// validated and parsed using the `vld` schema via [`VldParse`].
120///
121/// # Errors
122///
123/// Returns [`VldConfigError::Source`] if the config cannot be deserialized
124/// into JSON, or [`VldConfigError::Validation`] if validation fails.
125///
126/// # Example
127///
128/// ```rust,no_run
129/// use vld::prelude::*;
130///
131/// vld::schema! {
132///     #[derive(Debug)]
133///     pub struct Settings {
134///         pub host: String => vld::string().min(1),
135///         pub port: i64    => vld::number().int().min(1).max(65535),
136///     }
137/// }
138///
139/// let config = config::Config::builder()
140///     .add_source(config::File::with_name("config"))
141///     .build()
142///     .unwrap();
143///
144/// let settings: Settings = vld_app::config::from_config(&config).unwrap();
145/// ```
146#[cfg(feature = "config-rs")]
147pub fn from_config<T: VldParse>(config: &config::Config) -> Result<T, VldConfigError> {
148    let value: serde_json::Value = config
149        .clone()
150        .try_deserialize()
151        .map_err(|e| VldConfigError::Source(e.to_string()))?;
152    vld::schema::parse_coerced::<T>(&value).map_err(VldConfigError::Validation)
153}
154
155/// Load and validate configuration from a [`config::ConfigBuilder`].
156///
157/// Convenience wrapper that builds the config and validates in one step.
158///
159/// # Example
160///
161/// ```rust,no_run
162/// use vld::prelude::*;
163///
164/// vld::schema! {
165///     #[derive(Debug)]
166///     pub struct Settings {
167///         pub host: String => vld::string().min(1),
168///         pub port: i64    => vld::number().int().min(1).max(65535),
169///     }
170/// }
171///
172/// let settings: Settings = vld_app::config::from_builder(
173///     config::Config::builder()
174///         .add_source(config::File::with_name("config"))
175/// ).unwrap();
176/// ```
177#[cfg(feature = "config-rs")]
178pub fn from_builder<T: VldParse>(
179    builder: config::ConfigBuilder<config::builder::DefaultState>,
180) -> Result<T, VldConfigError> {
181    let config = builder
182        .build()
183        .map_err(|e| VldConfigError::Source(e.to_string()))?;
184    from_config(&config)
185}
186
187/// Validate a raw `serde_json::Value` **strictly** (no coercion): a number
188/// where the schema expects a string is an error.
189///
190/// Useful when you've already loaded the config data into a JSON value
191/// (e.g. from a custom source) and just want `vld` validation. For values that
192/// come from a typed source like env vars, use [`from_value_coerced`], which
193/// behaves like `from_config` / `from_figment`.
194pub fn from_value<T: VldParse>(value: &serde_json::Value) -> Result<T, VldConfigError> {
195    T::vld_parse_value(value).map_err(VldConfigError::Validation)
196}
197
198/// Validate a raw `serde_json::Value` with the coercion `from_config` /
199/// `from_figment` apply ([`vld::schema::parse_coerced`]): numbers / booleans
200/// become text where the schema expects a string, and a single value is
201/// wrapped where it expects an array.
202///
203/// ```
204/// vld::schema! {
205///     #[derive(Debug)]
206///     pub struct S { pub host: String => vld::string() }
207/// }
208/// let v = serde_json::json!({"host": 12345});
209/// assert!(vld_app::config::from_value::<S>(&v).is_err());
210/// assert_eq!(vld_app::config::from_value_coerced::<S>(&v).unwrap().host, "12345");
211/// ```
212pub fn from_value_coerced<T: VldParse>(value: &serde_json::Value) -> Result<T, VldConfigError> {
213    vld::schema::parse_coerced::<T>(value).map_err(VldConfigError::Validation)
214}
215
216// ---------------------------------------------------------------------------
217// figment backend
218// ---------------------------------------------------------------------------
219
220/// Load and validate configuration from a [`figment::Figment`] instance.
221///
222/// The figment data is extracted into a `serde_json::Value`, then
223/// validated and parsed using the `vld` schema.
224///
225/// # Errors
226///
227/// Returns [`VldConfigError::Source`] if figment extraction fails, or
228/// [`VldConfigError::Validation`] if validation fails.
229///
230/// # Example
231///
232/// ```rust,no_run
233/// use vld::prelude::*;
234///
235/// vld::schema! {
236///     #[derive(Debug)]
237///     pub struct Settings {
238///         pub host: String => vld::string().min(1),
239///         pub port: i64    => vld::number().int().min(1).max(65535),
240///     }
241/// }
242///
243/// let figment = figment::Figment::new()
244///     .merge(figment::providers::Serialized::defaults(
245///         serde_json::json!({"host": "localhost", "port": 8080}),
246///     ));
247///
248/// let settings: Settings = vld_app::config::from_figment(&figment).unwrap();
249/// ```
250#[cfg(feature = "figment")]
251pub fn from_figment<T: VldParse>(figment: &figment::Figment) -> Result<T, VldConfigError> {
252    let value: serde_json::Value = figment
253        .extract()
254        .map_err(|e| VldConfigError::Source(e.to_string()))?;
255    vld::schema::parse_coerced::<T>(&value).map_err(VldConfigError::Validation)
256}
257
258/// Prelude — re-exports everything you need.
259pub mod prelude {
260    pub use super::VldConfigError;
261    #[cfg(feature = "figment")]
262    pub use super::from_figment;
263    #[cfg(feature = "config-rs")]
264    pub use super::{from_builder, from_config};
265    pub use super::{from_value, from_value_coerced};
266    pub use vld::prelude::*;
267}