vld_app/env.rs
1//! # `vld_app::env` — validate configuration from environment variables
2//!
3//! Read environment variables (feature `env`, no dependency) or a `.env`
4//! file (feature `dotenv`, [dotenvy](https://docs.rs/dotenvy) 0.15) into a
5//! `vld` type at startup: a typed settings struct, or a [`VldEnvError`]
6//! naming every invalid variable.
7//!
8//! # Quick Start
9//!
10//! ```rust
11//! use vld_app::env::prelude::*;
12//!
13//! vld::schema! {
14//! #[derive(Debug)]
15//! pub struct Db {
16//! pub url: String => vld::string().min(1),
17//! pub pool_size: i64 => vld::number().int().min(1).with_default(10),
18//! }
19//! }
20//!
21//! vld::schema! {
22//! #[derive(Debug)]
23//! pub struct Settings {
24//! pub host: String => vld::string().min(1),
25//! pub port: i64 => vld::number().int().min(1).max(65535),
26//! pub debug: bool => vld::boolean().with_default(false),
27//! pub db: Db => vld::nested(Db::parse_value),
28//! }
29//! }
30//!
31//! // In an application: `from_env_prefixed::<Settings>("APP_")`.
32//! let vars = [
33//! ("APP_HOST", "0.0.0.0"),
34//! ("APP_PORT", "8080"),
35//! ("APP_DB__URL", "postgres://localhost/app"),
36//! ("PATH", "/usr/bin"), // no prefix: ignored
37//! ];
38//! let s: Settings = from_vars_prefixed(vars, "APP_").unwrap();
39//! assert_eq!((s.host.as_str(), s.port, s.debug), ("0.0.0.0", 8080, false));
40//! assert_eq!(s.db.pool_size, 10);
41//!
42//! let r: Result<Settings, _> = from_vars_prefixed([("APP_PORT", "http")], "APP_");
43//! let err = r.unwrap_err();
44//! let vars: Vec<&str> = err.var_issues().map(|(var, _)| var).collect();
45//! assert_eq!(vars, ["APP_HOST", "APP_PORT", "APP_DB"]);
46//! ```
47//!
48//! # Variable names
49//!
50//! - The prefix is matched ASCII case-insensitively and stripped; other
51//! variables are ignored. The rest of the name is lower-cased and split on
52//! `__` into nested objects: `APP_DB__POOL_SIZE` is `{"db": {"pool_size": ..}}`.
53//! Field names must therefore be lower snake case.
54//! - Names with an empty part (`APP_`, `APP__X`, `APP_A__`) and, for the
55//! process environment, names or values that are not UTF-8 are skipped.
56//! - When a name repeats, the later value wins (so in
57//! `read_dotenv(p)?.into_iter().chain(std::env::vars())` the process env
58//! overrides the file).
59//! - A variable that is both a value and a section (`APP_DB` and
60//! `APP_DB__URL`) is a [`VldEnvError::Source`] error.
61//!
62//! # Values
63//!
64//! Each value is coerced with [`vld::schema::coerce_text`] (`8080` → number,
65//! `true` → boolean, `01234` stays text) and the result parsed with
66//! [`vld::schema::parse_coerced`], so a value follows its field's schema:
67//! `APP_HOST=12345` into `vld::string()` is `"12345"`, and a single value
68//! into `vld::array(..)` is a one-element array.
69//!
70//! Guide: <https://s00d.github.io/vld/integrations/config-cli/env>
71
72use std::fmt;
73
74use serde_json::{Map, Value};
75use vld::error::{PathSegment, ValidationIssue, VldError};
76use vld::schema::VldParse;
77
78/// Error type for env validation.
79#[derive(Debug)]
80pub enum VldEnvError {
81 /// Validation failed. `vars[i]` is the environment variable of
82 /// `error.issues[i]` (see [`var_issues`](Self::var_issues)).
83 Validation {
84 /// Every validation issue; paths are JSON paths (`.db.url`).
85 error: VldError,
86 /// The variable each issue belongs to (`APP_DB__URL`).
87 vars: Vec<String>,
88 },
89 /// The `.env` file could not be read.
90 Io(std::io::Error),
91 /// A `.env` syntax error, or a variable that is both a value and a
92 /// section (`APP_DB` and `APP_DB__URL`).
93 Source(String),
94}
95
96impl VldEnvError {
97 /// `(variable, issue)` pairs of a validation error; empty otherwise.
98 pub fn var_issues(&self) -> impl Iterator<Item = (&str, &ValidationIssue)> {
99 let pairs = match self {
100 VldEnvError::Validation { error, vars } => Some(vars.iter().zip(&error.issues)),
101 _ => None,
102 };
103 pairs.into_iter().flatten().map(|(v, i)| (v.as_str(), i))
104 }
105}
106
107impl fmt::Display for VldEnvError {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 match self {
110 VldEnvError::Validation { .. } => {
111 f.write_str("invalid environment:")?;
112 for (var, issue) in self.var_issues() {
113 write!(f, "\n {var}: {}", issue.message)?;
114 }
115 Ok(())
116 }
117 VldEnvError::Io(e) => write!(f, "env file error: {e}"),
118 VldEnvError::Source(msg) => write!(f, "env error: {msg}"),
119 }
120 }
121}
122
123impl std::error::Error for VldEnvError {
124 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
125 match self {
126 VldEnvError::Validation { error, .. } => Some(error),
127 VldEnvError::Io(e) => Some(e),
128 VldEnvError::Source(_) => None,
129 }
130 }
131}
132
133/// Validate the whole process environment (no prefix) into `T`.
134///
135/// Every variable is a candidate key, so prefer [`from_env_prefixed`].
136pub fn from_env<T: VldParse>() -> Result<T, VldEnvError> {
137 from_env_prefixed("")
138}
139
140/// Validate the process variables starting with `prefix` (stripped) into `T`.
141pub fn from_env_prefixed<T: VldParse>(prefix: &str) -> Result<T, VldEnvError> {
142 let vars = std::env::vars_os()
143 .filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?)));
144 from_vars_prefixed(vars, prefix)
145}
146
147/// Validate `(name, value)` pairs into `T`, without a prefix.
148pub fn from_vars<T, I, K, V>(vars: I) -> Result<T, VldEnvError>
149where
150 T: VldParse,
151 I: IntoIterator<Item = (K, V)>,
152 K: AsRef<str>,
153 V: AsRef<str>,
154{
155 from_vars_prefixed(vars, "")
156}
157
158/// Validate the `(name, value)` pairs starting with `prefix` (stripped) into
159/// `T`. What [`from_env_prefixed`] does with the process environment.
160pub fn from_vars_prefixed<T, I, K, V>(vars: I, prefix: &str) -> Result<T, VldEnvError>
161where
162 T: VldParse,
163 I: IntoIterator<Item = (K, V)>,
164 K: AsRef<str>,
165 V: AsRef<str>,
166{
167 let mut root = Map::new();
168 // (lower-cased key parts, original name) of every variable read.
169 let mut names: Vec<(Vec<String>, String)> = Vec::new();
170 for (name, value) in vars {
171 let name = name.as_ref();
172 let Some(rest) = strip_prefix(name, prefix) else {
173 continue;
174 };
175 let parts: Vec<String> = rest
176 .to_lowercase()
177 .split("__")
178 .map(str::to_string)
179 .collect();
180 if parts.iter().any(String::is_empty) {
181 continue;
182 }
183 insert(&mut root, &parts, vld::schema::coerce_text(value.as_ref()))
184 .map_err(|()| VldEnvError::Source(format!("{name} is both a value and a section")))?;
185 match names.iter_mut().find(|(p, _)| *p == parts) {
186 Some(entry) => entry.1 = name.to_string(),
187 None => names.push((parts, name.to_string())),
188 }
189 }
190 vld::schema::parse_coerced::<T>(&Value::Object(root)).map_err(|error| {
191 let vars = error
192 .issues
193 .iter()
194 .map(|i| var_name(&i.path, prefix, &names))
195 .collect();
196 VldEnvError::Validation { error, vars }
197 })
198}
199
200/// Read a `.env` file into `(name, value)` pairs (in file order) without
201/// touching the process environment. `${VAR}` references are expanded as
202/// dotenvy does.
203#[cfg(feature = "dotenv")]
204pub fn read_dotenv(
205 path: impl AsRef<std::path::Path>,
206) -> Result<Vec<(String, String)>, VldEnvError> {
207 let map_err = |e: dotenvy::Error| match e {
208 dotenvy::Error::Io(e) => VldEnvError::Io(e),
209 other => VldEnvError::Source(other.to_string()),
210 };
211 dotenvy::from_path_iter(path)
212 .map_err(map_err)?
213 .map(|r| r.map_err(map_err))
214 .collect()
215}
216
217/// Validate a `.env` file (no prefix) into `T`, without touching the process
218/// environment. To layer it under the process env, pass
219/// `read_dotenv(path)?.into_iter().chain(std::env::vars())` to [`from_vars`].
220#[cfg(feature = "dotenv")]
221pub fn from_dotenv<T: VldParse>(path: impl AsRef<std::path::Path>) -> Result<T, VldEnvError> {
222 from_vars(read_dotenv(path)?)
223}
224
225fn strip_prefix<'a>(name: &'a str, prefix: &str) -> Option<&'a str> {
226 name.get(..prefix.len())
227 .filter(|p| p.eq_ignore_ascii_case(prefix))
228 .map(|_| &name[prefix.len()..])
229}
230
231/// Put `value` at `parts`; `Err` when a part is both a value and a section.
232fn insert(root: &mut Map<String, Value>, parts: &[String], value: Value) -> Result<(), ()> {
233 let (last, sections) = parts.split_last().expect("parts are never empty");
234 let mut map = root;
235 for part in sections {
236 map = match map
237 .entry(part.clone())
238 .or_insert_with(|| Value::Object(Map::new()))
239 {
240 Value::Object(m) => m,
241 _ => return Err(()),
242 };
243 }
244 if matches!(map.get(last), Some(Value::Object(_))) {
245 return Err(());
246 }
247 map.insert(last.clone(), value);
248 Ok(())
249}
250
251/// The variable an issue path belongs to: the name read for its leading
252/// fields (`.tags[0]` → `APP_TAGS`), else `PREFIX` + `FIELD__FIELD`.
253fn var_name(path: &[PathSegment], prefix: &str, names: &[(Vec<String>, String)]) -> String {
254 let fields: Vec<String> = path
255 .iter()
256 .map_while(|s| match s {
257 PathSegment::Field(f) => Some(f.clone()),
258 PathSegment::Index(_) => None,
259 })
260 .collect();
261 names
262 .iter()
263 .find(|(p, _)| *p == fields)
264 .map(|(_, n)| n.clone())
265 .unwrap_or_else(|| format!("{prefix}{}", fields.join("__").to_uppercase()))
266}
267
268/// Prelude — re-exports everything you need.
269pub mod prelude {
270 pub use super::{VldEnvError, from_env, from_env_prefixed, from_vars, from_vars_prefixed};
271 #[cfg(feature = "dotenv")]
272 pub use super::{from_dotenv, read_dotenv};
273 pub use vld::prelude::*;
274}