diff options
Diffstat (limited to 'crates/config/src/layer.rs')
| -rw-r--r-- | crates/config/src/layer.rs | 287 |
1 files changed, 287 insertions, 0 deletions
diff --git a/crates/config/src/layer.rs b/crates/config/src/layer.rs new file mode 100644 index 0000000..783bcb0 --- /dev/null +++ b/crates/config/src/layer.rs @@ -0,0 +1,287 @@ +//! Values and where they came from: each source of a configuration, a file or the +//! command line, makes a layer of them, and later ones are put over earlier ones. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use anyhow::{Result, anyhow, bail}; +use serde_json::Value as JsonValue; +use tracing::{debug, info, warn}; + +use crate::import::{self, Imported}; +use crate::option::{Kind, OptionSpec, Schema, from_text}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Provenance { + File(PathBuf), + Argument, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Origin { + pub provenance: Provenance, + /// The option was unset here (back to its default): `--unset`, `unset = [...]` in a + /// file, or `null` in a JSON file. + pub unset: bool, + /// Importers the value (or some list elements) came from, e.g. `env:HOSTNAME`. The + /// value is never shown. + pub imports: Vec<String>, + /// Text with placeholders the value (or some list elements) came from, e.g. + /// `node-${env:HOSTNAME}`. The value is shown. + pub templates: Vec<String>, + /// With placeholders: the value as written, placeholders and all. + pub written: Option<JsonValue>, +} + +impl Origin { + pub fn is_imported(&self) -> bool { + !self.imports.is_empty() + } +} + +impl std::fmt::Display for Origin { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.provenance { + Provenance::File(path) => write!(f, "{}", path.display())?, + Provenance::Argument => write!(f, "the command line")?, + } + if self.unset { + write!(f, " (unset)")?; + } + // Not the text with placeholders: of a secret, it may hold some of it. + if self.is_imported() { + write!(f, " ({})", self.imports.join(", "))?; + } + Ok(()) + } +} + +#[derive(Debug, Clone)] +pub struct Entry { + pub value: JsonValue, + pub origin: Origin, +} + +impl Entry { + /// The value of `option` for logs: imported values and secrets are never shown. + pub fn shown(&self, secret: bool) -> String { + if self.origin.unset { + "<default>".to_owned() + } else if secret { + "<secret>".to_owned() + } else if self.origin.is_imported() { + "<imported>".to_owned() + } else { + self.value.to_string() + } + } +} + +/// Option name to value. A `null` value unsets the option (back to its default). +pub type Layer = BTreeMap<String, Entry>; + +/// An unset of `name` from `provenance`. +pub fn unset_entry(provenance: Provenance) -> Entry { + Entry { + value: JsonValue::Null, + origin: Origin { + provenance, + unset: true, + imports: Vec::new(), + templates: Vec::new(), + written: None, + }, + } +} + +/// How a later source relates to the earlier ones it overrides (for logging). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Overlay { + /// A later include over an earlier include of the same file: usually a mistake. + IncludeOverInclude, + /// A file's own values over its includes, or a later `--config` over an earlier. + FileOverFile, + /// The command line over files. + ArgumentOverFile, +} + +/// Puts `entry` for `name` into `layer`, which holds earlier sources, logging what it +/// replaces and dropping earlier values it can't be combined with. +pub fn overlay(layer: &mut Layer, name: String, entry: Entry, how: Overlay, schema: &Schema) { + let log = |message: &str, option: &str, previous: &Entry| match how { + Overlay::IncludeOverInclude => warn!( + option, + value = %entry.shown(schema.secret(&name)), + from = %entry.origin, + overrides = %previous.shown(schema.secret(option)), + overridden_from = %previous.origin, + "{message}" + ), + Overlay::FileOverFile => debug!( + option, + from = %entry.origin, + overrides = %previous.origin, + "{message}" + ), + Overlay::ArgumentOverFile => info!( + option, + value = %entry.shown(schema.secret(&name)), + overrides = %previous.shown(schema.secret(option)), + from = %previous.origin, + "{message}" + ), + }; + + if !entry.value.is_null() { + for other in schema.conflicting(&name) { + let earlier = layer + .get(other) + .is_some_and(|previous| previous.origin.provenance != entry.origin.provenance); + if earlier && let Some(previous) = layer.remove(other) { + log( + &format!("{name} can't be combined with {other}; dropped the earlier value"), + other, + &previous, + ); + } + } + } + if let Some(previous) = layer.get(&name) { + let message = match how { + Overlay::IncludeOverInclude => { + "Two included configuration files set the same option; the later one wins" + } + Overlay::FileOverFile => "Configuration file overrides an earlier one", + Overlay::ArgumentOverFile => "Command-line argument overrides the configuration file", + }; + log(message, &name, previous); + } + layer.insert(name, entry); +} + +pub fn from_import(kind: Kind, importer: &import::Importer) -> Result<JsonValue> { + match importer.fetch()? { + Imported::Text(text) => from_text(kind, &text), + Imported::Json(value) => Ok(value), + // As it is: one text, its line breaks kept, read as nothing else. + Imported::Raw(bytes) => String::from_utf8(bytes) + .map(JsonValue::String) + .map_err(|_| anyhow!("{} is not UTF-8: an option is text", importer.describe())), + } +} + +/// A value from a file in `dir`: importer tables are resolved, also as list elements. +/// Collects where the parts of a value came from, for its [`Origin`]. +#[derive(Default)] +pub struct Sources { + imports: Vec<String>, + templates: Vec<String>, + /// The parts as written: literal values, importers, text with placeholders. + written: Vec<JsonValue>, +} + +impl Sources { + /// A literal part (list values count element by element). + pub fn literal(&mut self, value: &JsonValue) { + match value { + JsonValue::Array(items) => self.written.extend(items.iter().cloned()), + other => self.written.push(other.clone()), + } + } + + /// A part from `importer`. + pub fn import(&mut self, importer: &import::Importer) { + let described = importer.describe(); + if importer.is_interpolation() { + self.templates.push(described.clone()); + } else { + self.imports.push(described.clone()); + } + self.written.push(JsonValue::String(described)); + } + + pub fn origin(self, provenance: Provenance, unset: bool, kind: Kind) -> Origin { + let written = (!self.templates.is_empty()).then(|| match kind { + Kind::List => JsonValue::Array(self.written), + _ => self.written.into_iter().last().unwrap_or(JsonValue::Null), + }); + Origin { + provenance, + unset, + imports: self.imports, + templates: self.templates, + written, + } + } +} + +/// A value from a file, and where its parts came from. +pub fn resolve_file_value( + spec: &OptionSpec, + value: JsonValue, + dir: &Path, +) -> Result<(JsonValue, Sources)> { + let mut sources = Sources::default(); + let value = match value { + JsonValue::Object(table) => match import::parse_table(&table, dir)? { + Some(importer) => { + sources.import(&importer); + from_import(spec.kind, &importer)? + } + None => bail!("a table here must be an importer (env, file or command)"), + }, + JsonValue::String(text) => match import::interpolated(&text, Some(dir)) { + Some(importer) => { + sources.import(&importer); + from_import(spec.kind, &importer)? + } + None => JsonValue::String(text), + }, + JsonValue::Array(items) if spec.kind == Kind::List => { + let mut values = Vec::new(); + for item in items { + match item { + JsonValue::Object(table) => { + let importer = import::parse_table(&table, dir)?.ok_or_else(|| { + anyhow!("a table here must be an importer (env, file or command)") + })?; + match from_import(Kind::List, &importer)? { + JsonValue::Array(more) => values.extend(more), + other => values.push(other), + } + sources.import(&importer); + } + JsonValue::String(text) => match import::interpolated(&text, Some(dir)) { + Some(importer) => { + values.push(from_import(Kind::Text, &importer)?); + sources.import(&importer); + } + None => { + let value = JsonValue::String(text); + sources.literal(&value); + values.push(value); + } + }, + other => { + sources.literal(&other); + values.push(other); + } + } + } + JsonValue::Array(values) + } + other => other, + }; + Ok((value, sources)) +} + +/// `T` read from the values `merged` sets, each option's by its name: those unset take +/// `T`'s defaults. +pub fn read<T: serde::de::DeserializeOwned>(merged: &Layer) -> Result<T> { + let object: serde_json::Map<String, JsonValue> = merged + .iter() + .filter(|(_, entry)| !entry.value.is_null()) + .map(|(name, entry)| (name.clone(), entry.value.clone())) + .collect(); + serde_json::from_value(JsonValue::Object(object)).map_err(|error| anyhow!("{error}")) +} |
