diff options
Diffstat (limited to 'crates')
| -rw-r--r-- | crates/config/Cargo.toml | 4 | ||||
| -rw-r--r-- | crates/config/src/arguments.rs | 248 | ||||
| -rw-r--r-- | crates/config/src/file.rs | 226 | ||||
| -rw-r--r-- | crates/config/src/import.rs | 27 | ||||
| -rw-r--r-- | crates/config/src/layer.rs | 287 | ||||
| -rw-r--r-- | crates/config/src/lib.rs | 15 | ||||
| -rw-r--r-- | crates/config/src/option.rs | 156 | ||||
| -rw-r--r-- | crates/config/src/testing.rs | 27 | ||||
| -rw-r--r-- | crates/config/src/units.rs | 268 |
9 files changed, 1235 insertions, 23 deletions
diff --git a/crates/config/Cargo.toml b/crates/config/Cargo.toml index 090ee26..d8e75de 100644 --- a/crates/config/Cargo.toml +++ b/crates/config/Cargo.toml @@ -12,3 +12,7 @@ doctest = false [dependencies] anyhow = "1.0" serde_json = "1.0" +clap = "4.6" +serde = { version = "1.0", features = ["derive"] } +toml = "1.1" +tracing = "0.1" diff --git a/crates/config/src/arguments.rs b/crates/config/src/arguments.rs new file mode 100644 index 0000000..b1b8d00 --- /dev/null +++ b/crates/config/src/arguments.rs @@ -0,0 +1,248 @@ +//! The command line: a program's options as arguments, the configuration files it +//! names (`--config`) and what it unsets of theirs (`--unset`), put together. + +use std::path::PathBuf; + +use anyhow::{Context, Result, bail}; +use clap::parser::ValueSource; +use clap::{Arg, ArgAction, ArgMatches, Command}; +use serde_json::Value as JsonValue; + +use crate::file::{self, UNSET}; +use crate::import::{self, Raw}; +use crate::layer::{Entry, Layer, Overlay, Provenance, Sources, from_import, overlay, unset_entry}; +use crate::option::{Kind, OptionSpec, Schema, from_text}; + +pub const CONFIG: &str = "config"; + +/// Stops on an argument naming an option that is gone, saying why, before the command +/// line is read: clap would call it unexpected. +pub fn refuse_gone(arguments: impl IntoIterator<Item = String>, schema: &Schema) -> Result<()> { + for argument in arguments { + let Some(name) = argument.strip_prefix("--") else { + continue; + }; + let name = name.split('=').next().unwrap_or(name); + if let Some(why) = schema.gone(name) { + bail!("--{name} is gone: {why}"); + } + } + Ok(()) +} + +/// `command` taking `options` as arguments, and configuration files for them +/// (`--config`) and unsets of what those set (`--unset`). +pub fn with_options(command: Command, options: &'static [OptionSpec]) -> Command { + let mut command = command + .after_help( + "Every option can also be set in a configuration file (--config); arguments win.\n\ + A value can be imported instead of written out: env:NAME, file:PATH or cmd:COMMAND \ + (as text), or env+json:, file+json:, cmd+json: (parsed as JSON). \ + literal:VALUE passes a value that starts with one of these prefixes.", + ) + .arg( + Arg::new(CONFIG) + .long(CONFIG) + .value_name("PATH") + .action(ArgAction::Append) + .help("Configuration file (.toml or .json); repeatable, later files win."), + ) + .arg( + Arg::new(UNSET) + .long(UNSET) + .value_name("OPTION") + .action(ArgAction::Append) + .help("Unset an option set by a configuration file (back to its default); repeatable."), + ); + for spec in options { + let help = match spec.default { + Some(default) => format!("{} [default: {default}]", spec.help), + None => spec.help.to_owned(), + }; + let arg = Arg::new(spec.name) + .long(spec.name) + .help(help) + .hide(spec.hidden); + command = command.arg(match spec.kind { + Kind::Flag => arg.action(ArgAction::SetTrue), + Kind::List => arg.value_name(spec.value_name).action(ArgAction::Append), + Kind::Text | Kind::Integer | Kind::Duration | Kind::Size => { + arg.value_name(spec.value_name).action(ArgAction::Set) + } + }); + } + command +} + +/// The values of `options` given as arguments (unsets first, so a value given too wins). +pub fn arguments(matches: &ArgMatches, schema: &Schema) -> Result<Layer> { + let mut layer = Layer::new(); + for name in matches.get_many::<String>(UNSET).into_iter().flatten() { + if schema.spec(name).is_none() { + bail!("--unset {name}: no such option"); + } + layer.insert(name.clone(), unset_entry(Provenance::Argument)); + } + for spec in schema.options { + if matches.value_source(spec.name) != Some(ValueSource::CommandLine) { + continue; + } + let mut sources = Sources::default(); + let value = if spec.kind == Kind::Flag { + JsonValue::Bool(true) + } else { + let mut values = Vec::new(); + for raw in matches.get_many::<String>(spec.name).into_iter().flatten() { + let value = match import::parse_argument(raw) { + Raw::Literal(text) => from_text(spec.kind, text).inspect(|value| { + sources.literal(value); + }), + Raw::Import(importer) => { + sources.import(&importer); + from_import(spec.kind, &importer) + } + } + .with_context(|| format!("--{}", spec.name))?; + values.push(value); + } + if spec.kind == Kind::List { + JsonValue::Array( + values + .into_iter() + .flat_map(|value| match value { + JsonValue::Array(items) => items, + other => vec![other], + }) + .collect(), + ) + } else { + values.pop().unwrap_or(JsonValue::Null) + } + }; + layer.insert( + spec.name.to_owned(), + Entry { + value, + origin: sources.origin(Provenance::Argument, false, spec.kind), + }, + ); + } + Ok(layer) +} + +/// The values of the options of `schema`: from the configuration files `first` and then +/// those `matches` names (`--config`), in order, later ones winning, then from its +/// arguments; and those files. +pub fn merged( + matches: &ArgMatches, + schema: &Schema, + first: &[PathBuf], +) -> Result<(Layer, Vec<PathBuf>)> { + let files: Vec<PathBuf> = first + .iter() + .cloned() + .chain( + matches + .get_many::<String>(CONFIG) + .into_iter() + .flatten() + .map(PathBuf::from), + ) + .collect(); + let mut merged = Layer::new(); + for path in &files { + for (name, entry) in file::load(path, schema)? { + overlay(&mut merged, name, entry, Overlay::FileOverFile, schema); + } + } + for (name, entry) in arguments(matches, schema)? { + overlay(&mut merged, name, entry, Overlay::ArgumentOverFile, schema); + } + Ok((merged, files)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::option::{OptionSpec, option}; + use crate::testing::Scratch; + use serde_json::json; + + const OPTIONS: &[OptionSpec] = &[ + option("name", Kind::Text, "NAME", None, "A name"), + option("peers", Kind::List, "PEER,[...]", None, "Peers"), + option("local", Kind::Text, "PATH", None, "A local one"), + option("remote", Kind::Text, "URL", None, "A remote one"), + option("token", Kind::Text, "TOKEN", None, "A token").secret(), + ]; + + const SCHEMA: Schema = Schema { + options: OPTIONS, + conflicts: &[(&["remote"], &["local"])], + gone: &[("legacy", "use name instead")], + }; + + fn merged_of(arguments: &[&str]) -> Result<Layer> { + let command = with_options(Command::new("program"), OPTIONS); + let matches = command + .try_get_matches_from(std::iter::once("program").chain(arguments.iter().copied()))?; + merged(&matches, &SCHEMA, &[]).map(|(layer, _)| layer) + } + + /// A program's own options, by its schema: files in order, a file over its + /// includes, arguments over files; unsets; a conflict dropping the earlier side; an + /// option that is gone said as such, in a file and as an argument. + #[test] + fn files_and_arguments_of_a_schema_of_ones_own() { + let scratch = Scratch::new("arguments"); + let path = |name: &str| scratch.0.join(name).display().to_string(); + scratch.file( + "base.toml", + "name = \"base\"\npeers = [\"a\", \"b\"]\nlocal = \"here\"\n", + ); + scratch.file( + "main.json", + r#"{"include": ["base.toml"], "name": "main", "token": {"file": "secret"}}"#, + ); + scratch.file("secret", "hush\n"); + let layer = merged_of(&["--config", &path("main.json")]).unwrap(); + assert_eq!(layer["name"].value, json!("main")); + assert_eq!(layer["peers"].value, json!(["a", "b"])); + assert_eq!(layer["token"].value, json!("hush")); + assert_eq!(layer["token"].shown(SCHEMA.secret("token")), "<secret>"); + assert!(layer["name"].origin.to_string().ends_with("main.json")); + // Arguments over files, and an unset back to the default. + let layer = merged_of(&[ + "--config", + &path("main.json"), + "--name", + "given", + "--unset", + "peers", + ]) + .unwrap(); + assert_eq!(layer["name"].value, json!("given")); + assert_eq!(layer["name"].origin.provenance, Provenance::Argument); + assert!(layer["peers"].value.is_null() && layer["peers"].origin.unset); + // What can't be combined: the later source's side stays. + let layer = merged_of(&["--config", &path("main.json"), "--remote", "there"]).unwrap(); + assert!(!layer.contains_key("local")); + assert_eq!(layer["remote"].value, json!("there")); + // Unknown, and gone. + scratch.file("unknown.toml", "nmae = \"x\"\n"); + let said = format!( + "{:#}", + merged_of(&["--config", &path("unknown.toml")]).unwrap_err() + ); + assert!(said.contains("unknown option"), "{said}"); + scratch.file("gone.toml", "legacy = \"x\"\n"); + let said = format!( + "{:#}", + merged_of(&["--config", &path("gone.toml")]).unwrap_err() + ); + assert!(said.contains("use name instead"), "{said}"); + let said = refuse_gone(["--legacy=x".to_owned()], &SCHEMA).unwrap_err(); + assert!(said.to_string().contains("use name instead")); + assert!(refuse_gone(["--name".to_owned()], &SCHEMA).is_ok()); + } +} diff --git a/crates/config/src/file.rs b/crates/config/src/file.rs new file mode 100644 index 0000000..a5ed559 --- /dev/null +++ b/crates/config/src/file.rs @@ -0,0 +1,226 @@ +//! Configuration files: TOML (`.toml`) for people, JSON (`.json`) for generated +//! configuration, with the same keys: the long option names. Nested tables join their +//! keys with `-`, so `[mycelium] key-file = …` is `mycelium-key-file`. +//! +//! `include = [paths]` loads other files first (relative to this one), in the order +//! listed; an entry `{ path = "…", optional = true }` is skipped where missing. This +//! file's own values win over theirs, and later includes over earlier ones. A cycle is +//! an error. +//! +//! `unset = [options]` sets options back to their defaults, overriding includes and +//! earlier files; in JSON, `null` does the same for one option. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, anyhow, bail}; +use serde_json::{Map as JsonMap, Value as JsonValue}; +use tracing::debug; + +use crate::import; +use crate::layer::{Entry, Layer, Overlay, Provenance, overlay, resolve_file_value, unset_entry}; +use crate::option::Schema; + +const INCLUDE: &str = "include"; +/// Undoing a value set before: the key `unset` in a file, and the argument `--unset`. +pub const UNSET: &str = "unset"; +/// Gone: optional includes are entries of `include`, so the order is the list's. +const INCLUDE_OPTIONAL: &str = "include-optional"; + +/// The settings `path` makes of the options of `schema`, its includes resolved: a key +/// naming none of them is an error. +pub fn load(path: &Path, schema: &Schema) -> Result<Layer> { + load_inner(path, schema, &mut Vec::new()) +} + +fn load_inner(path: &Path, schema: &Schema, loading: &mut Vec<PathBuf>) -> Result<Layer> { + let canonical = path + .canonicalize() + .with_context(|| format!("configuration file {}", path.display()))?; + if loading.contains(&canonical) { + bail!("{} includes itself (through {:?})", path.display(), loading); + } + let dir = canonical + .parent() + .map(Path::to_owned) + .unwrap_or_else(|| PathBuf::from("/")); + + let mut root = parse(&canonical)?; + if root.contains_key(INCLUDE_OPTIONAL) { + bail!( + "{}: include-optional is gone; list the file in include as {{ path = \"…\", optional = true }}, where it goes in the order", + canonical.display() + ); + } + let includes = take_includes(&mut root, &canonical)?; + let unsets = take_paths(&mut root, UNSET, &canonical)?; + + loading.push(canonical.clone()); + let mut layer = Layer::new(); + for (include, required) in includes { + let include = dir.join(include); + if !required && !include.exists() { + debug!(file = %include.display(), "Optional configuration file is missing; skipped"); + continue; + } + let included = load_inner(&include, schema, loading) + .with_context(|| format!("included from {}", canonical.display()))?; + for (name, entry) in included { + overlay(&mut layer, name, entry, Overlay::IncludeOverInclude, schema); + } + } + loading.pop(); + + for name in unsets { + if schema.spec(&name).is_none() { + if let Some(why) = schema.gone(&name) { + bail!( + "option {name:?} in unset, in {}, is gone: {why}", + canonical.display() + ); + } + bail!( + "unknown option {name:?} in unset, in {}", + canonical.display() + ); + } + let entry = unset_entry(Provenance::File(canonical.clone())); + overlay(&mut layer, name, entry, Overlay::FileOverFile, schema); + } + + let mut own = Vec::new(); + flatten(&root, "", &dir, &mut own).with_context(|| format!("in {}", canonical.display()))?; + for (name, value) in own { + let spec = schema.spec(&name).ok_or_else(|| match schema.gone(&name) { + Some(why) => anyhow!("option {name:?} in {} is gone: {why}", canonical.display()), + None => anyhow!("unknown option {name:?} in {}", canonical.display()), + })?; + let (value, sources) = resolve_file_value(spec, value, &dir) + .with_context(|| format!("option {name} in {}", canonical.display()))?; + let entry = Entry { + origin: sources.origin( + Provenance::File(canonical.clone()), + value.is_null(), + spec.kind, + ), + value, + }; + overlay(&mut layer, name, entry, Overlay::FileOverFile, schema); + } + Ok(layer) +} + +fn parse(path: &Path) -> Result<JsonMap<String, JsonValue>> { + let text = + std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?; + let value: JsonValue = match path.extension().and_then(|e| e.to_str()) { + Some("toml") => { + let value: toml::Value = + toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?; + serde_json::to_value(value).with_context(|| format!("converting {}", path.display()))? + } + Some("json") => { + serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))? + } + _ => bail!( + "{}: unknown configuration format (use .toml or .json)", + path.display() + ), + }; + match value { + JsonValue::Object(map) => Ok(map), + _ => bail!("{}: the top level must be a table", path.display()), + } +} + +/// The files `include` names, in its order, and whether each is required: a path, or +/// `{ path = "…", optional = true }`. +fn take_includes( + root: &mut JsonMap<String, JsonValue>, + path: &Path, +) -> Result<Vec<(String, bool)>> { + let items = match root.remove(INCLUDE) { + None => return Ok(Vec::new()), + Some(JsonValue::Array(items)) => items, + Some(single) => vec![single], + }; + items + .into_iter() + .map(|item| match item { + JsonValue::String(file) => Ok((file, true)), + JsonValue::Object(mut entry) => { + let file = match entry.remove("path") { + Some(JsonValue::String(file)) => file, + _ => bail!("{}: an include entry needs a path", path.display()), + }; + let optional = match entry.remove("optional") { + None => false, + Some(JsonValue::Bool(optional)) => optional, + Some(other) => bail!( + "{}: include's optional is true or false, not {other}", + path.display() + ), + }; + if let Some(key) = entry.keys().next() { + bail!( + "{}: unknown key {key:?} in an include entry", + path.display() + ); + } + Ok((file, !optional)) + } + other => Err(anyhow!( + "{}: include entries are paths or {{ path, optional }}, not {other}", + path.display() + )), + }) + .collect() +} + +fn take_paths( + root: &mut JsonMap<String, JsonValue>, + key: &str, + path: &Path, +) -> Result<Vec<String>> { + match root.remove(key) { + None => Ok(Vec::new()), + Some(JsonValue::String(single)) => Ok(vec![single]), + Some(JsonValue::Array(items)) => items + .into_iter() + .map(|item| match item { + JsonValue::String(item) => Ok(item), + other => Err(anyhow!( + "{}: {key} entries must be paths, not {other}", + path.display() + )), + }) + .collect(), + Some(other) => bail!( + "{}: {key} must be a list of paths, not {other}", + path.display() + ), + } +} + +/// Option names and values, with nested tables joined by `-`. Importer tables are +/// values, not nesting. +fn flatten( + table: &JsonMap<String, JsonValue>, + prefix: &str, + dir: &Path, + out: &mut Vec<(String, JsonValue)>, +) -> Result<()> { + for (key, value) in table { + let name = if prefix.is_empty() { + key.clone() + } else { + format!("{prefix}-{key}") + }; + match value { + JsonValue::Object(nested) if import::parse_table(nested, dir)?.is_none() => { + flatten(nested, &name, dir, out)? + } + _ => out.push((name, value.clone())), + } + } + Ok(()) +} diff --git a/crates/config/src/import.rs b/crates/config/src/import.rs index a9ad603..04d396f 100644 --- a/crates/config/src/import.rs +++ b/crates/config/src/import.rs @@ -817,24 +817,13 @@ mod tests { assert!(failing.fetch().is_err()); } - /// A directory of a test's files, removed with it. - struct Scratch(PathBuf); + use crate::testing::Scratch; - impl Scratch { - fn new(name: &str) -> Scratch { - let dir = - std::env::temp_dir().join(format!("config-import-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - Scratch(dir) - } - - /// A file holding `content`: its name. - fn file(&self, name: &str, content: &str) -> String { - std::fs::write(self.0.join(name), content).unwrap(); - name.to_owned() - } + trait Fetch { + fn fetch(&self, raw: &str) -> Result<String>; + } + impl Fetch for Scratch { /// What a command-line value gives, read in this directory. fn fetch(&self, raw: &str) -> Result<String> { let Raw::Import(mut importer) = parse_argument(raw) else { @@ -936,12 +925,6 @@ mod tests { assert!(expand("a${cmd+raw:cat key}", Some(&scratch.0)).is_err()); } - impl Drop for Scratch { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } - } - #[test] fn the_parts_of_what_an_importer_names() { let text = |text: &str| Part::Text(text.to_owned()); 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}")) +} diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 654c475..fe2432e 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -1,6 +1,19 @@ //! What a program's configuration is made of, from its files and its arguments: a //! library, which continuum's configuration is made with, and other programs' may be. //! -//! * [`import`]: values taken from elsewhere instead of written out. +//! * [`option`]: the options a program takes, described once (`Schema`); +//! * [`file`]: configuration files, TOML or JSON, including others; +//! * [`arguments`]: the command line, and files and arguments put together; +//! * [`layer`]: values and where they came from, later sources over earlier ones; +//! * [`import`]: values taken from elsewhere instead of written out; +//! * [`units`]: durations and sizes as operators write them. +pub mod arguments; +pub mod file; pub mod import; +pub mod layer; +pub mod option; +pub mod units; + +#[cfg(test)] +mod testing; diff --git a/crates/config/src/option.rs b/crates/config/src/option.rs new file mode 100644 index 0000000..b361d38 --- /dev/null +++ b/crates/config/src/option.rs @@ -0,0 +1,156 @@ +//! The options a program takes, each described once: the command line, the keys of +//! configuration files and the reading of text values all go by them. + +use anyhow::{Result, anyhow, bail}; +use serde_json::Value as JsonValue; + +/// How an option's value is written as text (command line, text imports). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + /// `true`/`false`; on the command line, present or not. + Flag, + Text, + Integer, + /// Seconds, or with units: `500ms`, `30s`, `1h30m` (`units::parse_duration`). + Duration, + /// Bytes, or with a unit: `64KiB` (`units::parse_size`). + Size, + /// Comma- or line-separated; repeatable on the command line. + List, +} + +#[derive(Debug)] +pub struct OptionSpec { + pub name: &'static str, + pub kind: Kind, + pub value_name: &'static str, + /// For `--help` only; the effective defaults are in [`Settings`]. + pub default: Option<&'static str>, + pub help: &'static str, + pub hidden: bool, + /// Its value is never shown (logs, `--print-config`, `GET /admin/config`), however + /// it was given. + pub secret: bool, +} + +impl OptionSpec { + pub const fn secret(self) -> Self { + Self { + secret: true, + ..self + } + } +} + +pub const fn option( + name: &'static str, + kind: Kind, + value_name: &'static str, + default: Option<&'static str>, + help: &'static str, +) -> OptionSpec { + OptionSpec { + name, + kind, + value_name, + default, + help, + hidden: false, + secret: false, + } +} + +/// Options that can't be combined: those of one side with those of the other. +pub type Conflict = (&'static [&'static str], &'static [&'static str]); + +/// What a program's configuration is read by: its options, and what it says of them. +#[derive(Debug, Clone, Copy)] +pub struct Schema { + /// Every option. Names are the long option names and the configuration file keys. + pub options: &'static [OptionSpec], + /// Options that can't be combined. A source that sets one side drops the other + /// side's values from earlier sources (lower precedence), so one on the command line + /// overrides the other from a file. + pub conflicts: &'static [Conflict], + /// Options of earlier releases that are gone, each with what to do instead: a program + /// given one, in a configuration file or on its command line, says so and stops, + /// where "unknown option" would leave its operator guessing. + pub gone: &'static [(&'static str, &'static str)], +} + +impl Schema { + /// A schema of `options` alone: none conflicting, none gone. + pub const fn of(options: &'static [OptionSpec]) -> Schema { + Schema { + options, + conflicts: &[], + gone: &[], + } + } + + /// The option named `name`. + pub fn spec(&self, name: &str) -> Option<&'static OptionSpec> { + self.options.iter().find(|spec| spec.name == name) + } + + /// Why `name` is no option any more, where it was one. + pub fn gone(&self, name: &str) -> Option<&'static str> { + self.gone + .iter() + .find(|(gone, _)| *gone == name) + .map(|(_, why)| *why) + } + + /// Whether the option named `name` is never shown. + pub fn secret(&self, name: &str) -> bool { + self.spec(name).is_some_and(|spec| spec.secret) + } + + /// The options `name` can't be combined with. + pub fn conflicting<'a>(&self, name: &'a str) -> impl Iterator<Item = &'static str> + 'a { + self.conflicts.iter().flat_map(move |(a, b)| { + let other: &'static [&'static str] = if a.contains(&name) { + b + } else if b.contains(&name) { + a + } else { + &[] + }; + other.iter().copied() + }) + } +} + +/// The value of a text, by the option's kind. +pub fn from_text(kind: Kind, text: &str) -> Result<JsonValue> { + Ok(match kind { + Kind::Text => JsonValue::String(text.to_owned()), + Kind::Integer => { + let number: u64 = text + .trim() + .parse() + .map_err(|_| anyhow!("{text:?} is not a non-negative integer"))?; + JsonValue::from(number) + } + Kind::Duration => { + crate::units::parse_duration(text).map_err(|reason| anyhow!(reason))?; + JsonValue::String(text.trim().to_owned()) + } + Kind::Size => { + crate::units::parse_size(text).map_err(|reason| anyhow!(reason))?; + JsonValue::String(text.trim().to_owned()) + } + Kind::Flag => match text.trim() { + "true" | "yes" | "1" => JsonValue::Bool(true), + "false" | "no" | "0" => JsonValue::Bool(false), + _ => bail!("{text:?} is not true or false"), + }, + Kind::List => JsonValue::Array( + text.split([',', '\n']) + .map(str::trim) + .filter(|item| !item.is_empty()) + .map(|item| JsonValue::String(item.to_owned())) + .collect(), + ), + }) +} diff --git a/crates/config/src/testing.rs b/crates/config/src/testing.rs new file mode 100644 index 0000000..8101ee3 --- /dev/null +++ b/crates/config/src/testing.rs @@ -0,0 +1,27 @@ +//! What the crate's tests share. + +use std::path::PathBuf; + +/// A directory of a test's files, removed with it. +pub(crate) struct Scratch(pub(crate) PathBuf); + +impl Scratch { + pub(crate) fn new(name: &str) -> Scratch { + let dir = std::env::temp_dir().join(format!("config-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } + + /// A file holding `content`: its name. + pub(crate) fn file(&self, name: &str, content: &str) -> String { + std::fs::write(self.0.join(name), content).unwrap(); + name.to_owned() + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} diff --git a/crates/config/src/units.rs b/crates/config/src/units.rs new file mode 100644 index 0000000..1e72da3 --- /dev/null +++ b/crates/config/src/units.rs @@ -0,0 +1,268 @@ +//! Durations and sizes as operators write them: in options, configuration files and +//! API requests. +//! +//! * A duration is a bare number of seconds (`30`, `0.5`), or components with units in +//! descending order: `ms`, `s`, `m`, `h`, `d` (`500ms`, `500s`, `1h30m`, `1d2h3s`, +//! `1.5h`; spaces between components are allowed). Resolution is a millisecond: a +//! value with a finer part is an error, not rounded. +//! * A size is a bare number of bytes, or a number with a unit: `B`, `KiB`, `MiB`, `GiB` +//! (`64KiB`, `1.5MiB`). A value that isn't a whole number of bytes is an error. +//! +//! Output (stats, reports) stays numeric, with the unit in the field's name. + +use std::time::Duration; + +const DURATION_UNITS: [(&str, u64); 5] = [ + ("d", 86_400_000), + ("h", 3_600_000), + ("m", 60_000), + ("s", 1_000), + ("ms", 1), +]; + +const SIZE_UNITS: [(&str, u64); 4] = [ + ("GiB", 1 << 30), + ("MiB", 1 << 20), + ("KiB", 1 << 10), + ("B", 1), +]; + +/// `number` (digits, optionally a fraction) times `scale`, if that is a whole number +/// that fits. +fn scaled(number: &str, scale: u64) -> Option<u64> { + let (whole, fraction) = number.split_once('.').unwrap_or((number, "")); + if whole.is_empty() && fraction.is_empty() { + return None; + } + if !whole.bytes().all(|b| b.is_ascii_digit()) || !fraction.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let whole: u64 = if whole.is_empty() { + 0 + } else { + whole.parse().ok()? + }; + let mut value = whole.checked_mul(scale)?; + if !fraction.is_empty() { + let digits = u32::try_from(fraction.len()).ok()?; + let denominator = 10u128.checked_pow(digits)?; + let numerator = fraction.parse::<u128>().ok()? * u128::from(scale); + if numerator % denominator != 0 { + return None; + } + value = value.checked_add(u64::try_from(numerator / denominator).ok()?)?; + } + Some(value) +} + +/// A duration as written by an operator (see the module doc). +pub fn parse_duration(text: &str) -> Result<Duration, String> { + let text = text.trim(); + let invalid = || { + format!( + "{text:?} is not a duration (seconds, or e.g. 500ms, 30s, 1h30m, 1d2h3s; at most millisecond precision)" + ) + }; + if text.is_empty() { + return Err(invalid()); + } + if let Some(millis) = scaled(text, 1_000) { + return Ok(Duration::from_millis(millis)); + } + let mut rest = text; + let mut total: u64 = 0; + // Units must descend: the index of the next one allowed. + let mut next_unit = 0; + while !rest.is_empty() { + let number_len = rest + .find(|c: char| !(c.is_ascii_digit() || c == '.')) + .ok_or_else(invalid)?; + let (number, after) = rest.split_at(number_len); + let unit_len = after + .find(|c: char| !c.is_ascii_alphabetic()) + .unwrap_or(after.len()); + let (unit, after) = after.split_at(unit_len); + let index = DURATION_UNITS + .iter() + .position(|(name, _)| *name == unit) + .filter(|&index| index >= next_unit) + .ok_or_else(invalid)?; + let millis = scaled(number, DURATION_UNITS[index].1).ok_or_else(invalid)?; + total = total.checked_add(millis).ok_or_else(invalid)?; + next_unit = index + 1; + rest = after.trim_start(); + } + Ok(Duration::from_millis(total)) +} + +/// A duration the way [`parse_duration`] reads it: `1d2h3s`, `500ms`, `0s`. +pub fn format_duration(duration: Duration) -> String { + let mut millis = u64::try_from(duration.as_millis()).unwrap_or(u64::MAX); + if millis == 0 { + return "0s".to_owned(); + } + let mut out = String::new(); + for (name, scale) in DURATION_UNITS { + if millis >= scale { + out.push_str(&format!("{}{name}", millis / scale)); + millis %= scale; + } + } + out +} + +/// A size in bytes as written by an operator (see the module doc). +pub fn parse_size(text: &str) -> Result<u64, String> { + let text = text.trim(); + let invalid = || format!("{text:?} is not a size (bytes, or e.g. 512B, 64KiB, 1.5MiB, 1GiB)"); + let number_len = text + .find(|c: char| !(c.is_ascii_digit() || c == '.')) + .unwrap_or(text.len()); + let (number, unit) = text.split_at(number_len); + let scale = match unit.trim() { + "" => 1, + unit => SIZE_UNITS + .iter() + .find(|(name, _)| *name == unit) + .map(|(_, scale)| *scale) + .ok_or_else(invalid)?, + }; + scaled(number, scale).ok_or_else(invalid) +} + +/// A size the way [`parse_size`] reads it: the largest unit that divides it. +pub fn format_size(bytes: u64) -> String { + SIZE_UNITS + .iter() + .find(|(_, scale)| bytes != 0 && bytes.is_multiple_of(*scale)) + .map(|(name, scale)| format!("{}{name}", bytes / scale)) + .unwrap_or_else(|| "0B".to_owned()) +} + +/// Serde for a `Duration` option: a string as [`parse_duration`] reads it, or a number +/// of seconds (configuration files may write either); written as [`format_duration`]. +pub mod duration_option { + use std::time::Duration; + + use serde::{Deserialize, Deserializer, Serializer, de::Error as _}; + use serde_json::Value as JsonValue; + + pub fn serialize<S: Serializer>(value: &Duration, s: S) -> Result<S::Ok, S::Error> { + s.serialize_str(&super::format_duration(*value)) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> { + match JsonValue::deserialize(d)? { + JsonValue::String(text) => super::parse_duration(&text).map_err(D::Error::custom), + JsonValue::Number(number) => { + super::parse_duration(&number.to_string()).map_err(D::Error::custom) + } + other => Err(D::Error::custom(format!("{other} is not a duration"))), + } + } +} + +/// Reads an optional `Duration` in a request (JSON body or query string) as +/// [`duration_option`] reads it; absent is `None`. Use as +/// `#[serde(default, deserialize_with = "crate::units::optional_duration")]`. +pub fn optional_duration<'de, D: serde::Deserializer<'de>>( + d: D, +) -> Result<Option<Duration>, D::Error> { + duration_option::deserialize(d).map(Some) +} + +/// Writes an optional `Duration` as [`duration_option`] does; `None` as null. +pub fn serialize_optional_duration<S: serde::Serializer>( + value: &Option<Duration>, + s: S, +) -> Result<S::Ok, S::Error> { + match value { + Some(value) => duration_option::serialize(value, s), + None => s.serialize_none(), + } +} + +/// Serde for a size option: a string as [`parse_size`] reads it, or a number of bytes; +/// written as [`format_size`]. +pub mod size_option { + use serde::{Deserialize, Deserializer, Serializer, de::Error as _}; + use serde_json::Value as JsonValue; + + pub fn serialize<S: Serializer>(value: &u64, s: S) -> Result<S::Ok, S::Error> { + s.serialize_str(&super::format_size(*value)) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<u64, D::Error> { + match JsonValue::deserialize(d)? { + JsonValue::String(text) => super::parse_size(&text).map_err(D::Error::custom), + JsonValue::Number(number) => { + super::parse_size(&number.to_string()).map_err(D::Error::custom) + } + other => Err(D::Error::custom(format!("{other} is not a size"))), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ms(text: &str) -> u64 { + parse_duration(text).unwrap().as_millis() as u64 + } + + #[test] + fn durations() { + assert_eq!(ms("30"), 30_000); + assert_eq!(ms("0.5"), 500); + assert_eq!(ms(".25"), 250); + assert_eq!(ms("500s"), 500_000); + assert_eq!(ms("500ms"), 500); + assert_eq!(ms("1h30m"), 5_400_000); + assert_eq!(ms("1d2h3s"), 93_603_000); + assert_eq!(ms("1d 2h 3s"), 93_603_000); + assert_eq!(ms("1.5h"), 5_400_000); + assert_eq!(ms("0.001"), 1); + assert_eq!(ms(" 7d "), 7 * 86_400_000); + assert_eq!(ms("0"), 0); + } + + #[test] + fn bad_durations() { + for text in [ + "", "s", "1x", "1h1d", "1s1s", "1ms1s", "-1", "1.0005", "0.0001s", "1..5s", "1h 2", + "1e3", + ] { + assert!(parse_duration(text).is_err(), "{text:?} parsed"); + } + } + + #[test] + fn durations_format_as_they_parse() { + for millis in [0, 1, 500, 1_000, 60_000, 5_400_000, 93_603_000, 86_400_001] { + let duration = Duration::from_millis(millis); + assert_eq!( + parse_duration(&format_duration(duration)).unwrap(), + duration + ); + } + assert_eq!(format_duration(Duration::from_millis(93_603_000)), "1d2h3s"); + } + + #[test] + fn sizes() { + assert_eq!(parse_size("4096"), Ok(4096)); + assert_eq!(parse_size("512B"), Ok(512)); + assert_eq!(parse_size("64KiB"), Ok(65_536)); + assert_eq!(parse_size("64 KiB"), Ok(65_536)); + assert_eq!(parse_size("1.5MiB"), Ok(1_572_864)); + assert_eq!(parse_size("1GiB"), Ok(1 << 30)); + for text in ["", "KiB", "1.5", "1kib", "1KB", "0.3KiB", "-1"] { + assert!(parse_size(text).is_err(), "{text:?} parsed"); + } + for bytes in [1, 1024, 1536, 65_536, 1 << 30] { + assert_eq!(parse_size(&format_size(bytes)), Ok(bytes)); + } + assert_eq!(format_size(65_536), "64KiB"); + } +} |
