diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/config/file.rs | 233 | ||||
| -rw-r--r-- | src/config/mod.rs | 618 | ||||
| -rw-r--r-- | src/federation/party.rs | 6 | ||||
| -rw-r--r-- | src/units.rs | 270 |
4 files changed, 63 insertions, 1064 deletions
diff --git a/src/config/file.rs b/src/config/file.rs index 5984c10..b534f93 100644 --- a/src/config/file.rs +++ b/src/config/file.rs @@ -1,238 +1,17 @@ -//! 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. +//! Configuration files (`config::file`), read by the node's options: TOML (`.toml`) for +//! people, JSON (`.json`) for generated configuration, with the same keys. use std::path::{Path, PathBuf}; -use anyhow::{Context, Result, anyhow, bail}; -use serde_json::{Map as JsonMap, Value as JsonValue}; -use tracing::debug; +use anyhow::Result; -use super::import; -use super::{Entry, Layer, OptionSpec, Overlay, Provenance, UNSET, overlay, spec_in, unset_entry}; - -const INCLUDE: &str = "include"; -/// Gone: optional includes are entries of `include`, so the order is the list's. -const INCLUDE_OPTIONAL: &str = "include-optional"; +use super::{Layer, SCHEMA}; /// The settings `path` makes, its includes resolved. -#[cfg(test)] -pub(super) fn load(path: &Path) -> Result<Layer> { - load_with(path, super::OPTIONS) -} - -/// The settings `path` makes of `options`, its includes resolved: a key naming none of -/// them is an error. -pub(super) fn load_with(path: &Path, options: &'static [OptionSpec]) -> Result<Layer> { - load_inner(path, options, &mut Vec::new()) -} - -fn load_inner( - path: &Path, - options: &'static [OptionSpec], - 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, options, loading) - .with_context(|| format!("included from {}", canonical.display()))?; - for (name, entry) in included { - overlay(&mut layer, name, entry, Overlay::IncludeOverInclude); - } - } - loading.pop(); - - for name in unsets { - if spec_in(options, &name).is_none() { - if let Some(why) = super::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); - } - - let mut own = Vec::new(); - flatten(&root, "", &dir, &mut own).with_context(|| format!("in {}", canonical.display()))?; - for (name, value) in own { - let spec = spec_in(options, &name).ok_or_else(|| match super::gone(&name) { - Some(why) => anyhow!("option {name:?} in {} is gone: {why}", canonical.display()), - None => anyhow!("unknown option {name:?} in {}", canonical.display()), - })?; - let (value, sources) = super::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); - } - 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(()) +fn load(path: &Path) -> Result<Layer> { + ::config::file::load(path, &SCHEMA) } -#[cfg(test)] mod tests { use super::*; use crate::files::scratch_dir; diff --git a/src/config/mod.rs b/src/config/mod.rs index 2f67547..3e7c5d4 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -9,77 +9,68 @@ //! All options are described once, in [`OPTIONS`]: the command line, the file keys and //! the conversion of text values all derive from it. The merged values are then read //! into [`Settings`] and checked. +//! +//! Files, arguments, layers and importers are the crate `config`'s, which reads them by a +//! program's options (`SCHEMA`, the node's; `PARTY`, a party's client's); here are the +//! options, the settings they make, and what is checked and reported of them. +#[cfg(test)] mod file; use std::collections::BTreeMap; use std::net::SocketAddr; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::time::Duration; use anyhow::{Context, Result, anyhow, bail}; -use clap::parser::ValueSource; -use clap::{Arg, ArgAction, ArgMatches, Command}; +use clap::{Arg, ArgAction, Command}; use serde::{Deserialize, Serialize}; use serde_json::Value as JsonValue; -use tracing::{debug, info, warn}; +use tracing::{info, warn}; + +pub(crate) use ::config::arguments::{merged, with_options}; +#[cfg(feature = "federation")] +pub(crate) use ::config::layer::read; +pub(crate) use ::config::layer::{Entry, Layer, Origin, Provenance}; +pub(crate) use ::config::option::{Kind, OptionSpec, Schema, option}; + +/// What the node's configuration is read by: its options, those that can't be combined, +/// and those that are gone. +pub(crate) const SCHEMA: Schema = Schema { + options: OPTIONS, + conflicts: CONFLICTS, + gone: GONE, +}; -use ::config::import::{self, Imported, Raw}; +/// What the configuration of a party's client is read by. +#[cfg(feature = "federation")] +pub(crate) const PARTY: Schema = Schema::of(PARTY_OPTIONS); -/// How an option's value is written as text (command line, text imports). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) 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, +/// As the crate's, by the node's options: what the tests call. +#[cfg(test)] +use ::config::{ + layer::{Overlay, unset_entry}, + option::from_text, +}; + +#[cfg(test)] +fn overlay(layer: &mut Layer, name: String, entry: Entry, how: Overlay) { + ::config::layer::overlay(layer, name, entry, how, &SCHEMA); } -#[derive(Debug)] -pub(crate) struct OptionSpec { - pub(crate) name: &'static str, - pub(crate) kind: Kind, - pub(crate) value_name: &'static str, - /// For `--help` only; the effective defaults are in [`Settings`]. - pub(crate) default: Option<&'static str>, - pub(crate) help: &'static str, - pub(crate) hidden: bool, - /// Its value is never shown (logs, `--print-config`, `GET /admin/config`), however - /// it was given. - pub(crate) secret: bool, +#[cfg(test)] +fn arguments(matches: &clap::ArgMatches) -> Result<Layer> { + ::config::arguments::arguments(matches, &SCHEMA) } -impl OptionSpec { - const fn secret(self) -> Self { - Self { - secret: true, - ..self - } - } +#[cfg(test)] +fn refuse_gone(arguments: impl IntoIterator<Item = String>) -> Result<()> { + ::config::arguments::refuse_gone(arguments, &SCHEMA) } -pub(crate) 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, - } +#[cfg(test)] +fn gone(name: &str) -> Option<&'static str> { + SCHEMA.gone(name) } /// What `--force` may override at start (`force`). @@ -732,11 +723,6 @@ pub(crate) const OPTIONS: &[OptionSpec] = &[ }, ]; -/// The option of `options` named `name`. -pub(super) fn spec_in(options: &'static [OptionSpec], name: &str) -> Option<&'static OptionSpec> { - options.iter().find(|spec| spec.name == name) -} - /// Options of earlier releases that are gone, each with what to do instead: a node given /// one, in a configuration file or on its command line, says so and stops, where "unknown /// option" would leave its operator guessing. @@ -748,28 +734,6 @@ const GONE: &[(&str, &str)] = &[( Two proposed at once)", )]; -/// Why `name` is no option any more, where it was one (`GONE`). -pub(super) fn gone(name: &str) -> Option<&'static str> { - GONE.iter() - .find(|(gone, _)| *gone == name) - .map(|(_, why)| *why) -} - -/// Stops on an argument naming an option that is gone, saying why, before the command -/// line is read: clap would call it unexpected. -fn refuse_gone(arguments: impl IntoIterator<Item = String>) -> 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) = gone(name) { - bail!("--{name} is gone: {why}"); - } - } - Ok(()) -} - /// The options of a party's client (`continuum-party`), set as the node's are: on the /// command line, or in configuration files of the same format (`with_options`, /// `merged`). @@ -813,16 +777,6 @@ pub(crate) const PARTY_OPTIONS: &[OptionSpec] = &[ "The party it works as where no record names it, for reading: the one it logs in to the node as, by --key, where --node names no user and no --token is given", ), ]; -#[cfg(not(feature = "federation"))] -const PARTY_OPTIONS: &[OptionSpec] = &[]; - -/// Whether `option`, the node's or a party's client's, is never shown. -fn secret(option: &str) -> bool { - OPTIONS - .iter() - .chain(PARTY_OPTIONS) - .any(|spec| spec.name == option && spec.secret) -} /// The effective configuration. #[derive(Debug, Clone, Deserialize, Serialize)] @@ -1571,91 +1525,6 @@ fn check_alias(alias: &str) -> Result<()> { Ok(()) } -// --- values and where they came from ------------------------------------------- - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) enum Provenance { - File(PathBuf), - Argument, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct Origin { - pub(crate) provenance: Provenance, - /// The option was unset here (back to its default): `--unset`, `unset = [...]` in a - /// file, or `null` in a JSON file. - pub(crate) unset: bool, - /// Importers the value (or some list elements) came from, e.g. `env:HOSTNAME`. The - /// value is never shown. - pub(crate) imports: Vec<String>, - /// Text with placeholders the value (or some list elements) came from, e.g. - /// `node-${env:HOSTNAME}`. The value is shown. - pub(crate) templates: Vec<String>, - /// With placeholders: the value as written, placeholders and all. - pub(crate) written: Option<JsonValue>, -} - -impl Origin { - pub(crate) 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(crate) struct Entry { - pub(crate) value: JsonValue, - pub(crate) origin: Origin, -} - -impl Entry { - /// The value of `option` for logs: imported values and secrets are never shown. - pub(crate) fn shown(&self, option: &str) -> String { - if self.origin.unset { - "<default>".to_owned() - } else if secret(option) { - "<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(crate) type Layer = BTreeMap<String, Entry>; - -/// An unset of `name` from `provenance`. -fn unset_entry(provenance: Provenance) -> Entry { - Entry { - value: JsonValue::Null, - origin: Origin { - provenance, - unset: true, - imports: Vec::new(), - templates: Vec::new(), - written: None, - }, - } -} - /// Options that can't be combined. A source that sets one side drops the other side's /// values from earlier sources (lower precedence), so e.g. `--mycelium-rest-url` on the /// command line overrides `mycelium-key-file` from a file. Both set in one source is an @@ -1671,235 +1540,6 @@ const CONFLICTS: &[(&[&str], &[&str])] = &[( ], )]; -/// The options `name` can't be combined with. -fn conflicting(name: &str) -> impl Iterator<Item = &'static str> + '_ { - 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() - }) -} - -/// How a later source relates to the earlier ones it overrides (for logging). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) 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(crate) fn overlay(layer: &mut Layer, name: String, entry: Entry, how: Overlay) { - let log = |message: &str, option: &str, previous: &Entry| match how { - Overlay::IncludeOverInclude => warn!( - option, - value = %entry.shown(&name), - from = %entry.origin, - overrides = %previous.shown(option), - overridden_from = %previous.origin, - "{message}" - ), - Overlay::FileOverFile => debug!( - option, - from = %entry.origin, - overrides = %previous.origin, - "{message}" - ), - Overlay::ArgumentOverFile => info!( - option, - value = %entry.shown(&name), - overrides = %previous.shown(option), - from = %previous.origin, - "{message}" - ), - }; - - if !entry.value.is_null() { - for other in 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); -} - -/// The value of a text, by the option's kind. -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(), - ), - }) -} - -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)] -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). - 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`. - 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)); - } - - 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. -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)) -} - /// The first option whose value alone doesn't fit (serde doesn't name it). fn culprit(merged: &Layer) -> Option<(&String, &Entry)> { merged.iter().find(|(name, entry)| { @@ -1914,10 +1554,7 @@ fn culprit(merged: &Layer) -> Option<(&String, &Entry)> { // --- command line -------------------------------------------------------------- -const CONFIG: &str = "config"; const PRINT_CONFIG: &str = "print-config"; -/// Undoing a value set before: the argument `--unset`, and the key `unset` in a file. -pub(super) const UNSET: &str = "unset"; fn command() -> Command { let command = Command::new("continuum") @@ -1950,112 +1587,6 @@ fn command() -> Command { /// `continuum node-id FILE`: the node ID of the key in `FILE` (`Loaded::node_id`). const NODE_ID: &str = "node-id"; -/// `command` taking `options` as arguments, and configuration files for them -/// (`--config`) and unsets of what those set (`--unset`). -pub(crate) 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 given as arguments (unsets first, so a value given too wins). -#[cfg(test)] -fn arguments(matches: &ArgMatches) -> Result<Layer> { - arguments_with(matches, OPTIONS) -} - -/// The values of `options` given as arguments (unsets first, so a value given too wins). -fn arguments_with(matches: &ArgMatches, options: &'static [OptionSpec]) -> Result<Layer> { - let mut layer = Layer::new(); - for name in matches.get_many::<String>(UNSET).into_iter().flatten() { - if spec_in(options, name).is_none() { - bail!("--unset {name}: no such option"); - } - layer.insert(name.clone(), unset_entry(Provenance::Argument)); - } - for spec in 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 configuration, and where each value set came from (absent: default). #[derive(Debug, Clone)] pub(crate) struct Loaded { @@ -2197,7 +1728,7 @@ impl Loaded { /// Reads the command line and the configuration files it names. Exits on `--help`, /// `--version` and command-line syntax errors, like any command. pub(crate) fn load() -> Result<Loaded> { - refuse_gone(std::env::args().skip(1))?; + ::config::arguments::refuse_gone(std::env::args().skip(1), &SCHEMA)?; let matches = command().get_matches(); let print_only = matches.get_flag(PRINT_CONFIG); let node_id = matches.subcommand_matches(NODE_ID).map(|sub| { @@ -2209,63 +1740,13 @@ pub(crate) fn load() -> Result<Loaded> { // says where each value came from anyway). let _ = crate::logging::set_filter("off"); } - let (merged, files) = merged(&matches, OPTIONS)?; + let (merged, files) = merged(&matches, &SCHEMA, &[])?; let mut loaded = resolve(merged, files)?; loaded.print_only = print_only; loaded.node_id = node_id; Ok(loaded) } -/// The values of `options`: from the configuration files `matches` names (`--config`), in -/// order, then from its arguments; and those files. -pub(crate) fn merged( - matches: &ArgMatches, - options: &'static [OptionSpec], -) -> Result<(Layer, Vec<PathBuf>)> { - merged_with(matches, options, &[]) -} - -/// As `merged`, the files `first` read before those `matches` names, which win over them. -pub(crate) fn merged_with( - matches: &ArgMatches, - options: &'static [OptionSpec], - 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_with(path, options)? { - overlay(&mut merged, name, entry, Overlay::FileOverFile); - } - } - for (name, entry) in arguments_with(matches, options)? { - overlay(&mut merged, name, entry, Overlay::ArgumentOverFile); - } - Ok((merged, files)) -} - -/// `T` read from the values `merged` sets, each option's by its name: those unset take -/// `T`'s defaults. -#[cfg(feature = "federation")] -pub(crate) 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}")) -} - /// HyParView's active view, where `neighbours` isn't set: the paper's, for swarms of up /// to about 10 000 members (its fanout of 4, plus one). const HYPARVIEW_NEIGHBOURS: usize = 5; @@ -2939,7 +2420,10 @@ mod tests { .unwrap(); let mut layer = arguments(&matches).unwrap(); assert!(!layer["alias"].origin.is_imported()); - assert_eq!(layer["alias"].shown("alias"), "\"node-berlin\""); + assert_eq!( + layer["alias"].shown(SCHEMA.secret("alias")), + "\"node-berlin\"" + ); with_built_transport(&mut layer); let loaded = resolve(layer, Vec::new()).unwrap(); @@ -2979,7 +2463,7 @@ mod tests { json!({ "htpasswd": "users", "node-key-file": "node.key", "mycelium-rest-url": "http://u:pw@h:8989" }), ); assert_eq!( - values["mycelium-rest-url"].shown("mycelium-rest-url"), + values["mycelium-rest-url"].shown(SCHEMA.secret("mycelium-rest-url")), "<secret>" ); let loaded = resolve(values, Vec::new()).unwrap(); diff --git a/src/federation/party.rs b/src/federation/party.rs index 4420478..eaf28b5 100644 --- a/src/federation/party.rs +++ b/src/federation/party.rs @@ -651,7 +651,7 @@ pub(crate) async fn main() -> Result<()> { .map(|dir| dir.join("party.toml")) .filter(|file| file.exists()) .collect(); - let (merged, _) = config::merged_with(&matches, config::PARTY_OPTIONS, &first)?; + let (merged, _) = config::merged(&matches, &config::PARTY, &first)?; let mut options: Options = config::read(&merged)?; // In a federation's directory, its record and key, where none other is named. if let Some(dir) = &dir { @@ -3320,7 +3320,7 @@ mod tests { "proposals", ]) .unwrap(); - let (merged, _) = config::merged(&matches, config::PARTY_OPTIONS).unwrap(); + let (merged, _) = config::merged(&matches, &config::PARTY, &[]).unwrap(); let options: super::Options = config::read(&merged).unwrap(); assert_eq!(options.node, "http://tv:secret@localhost:3001"); assert_eq!(options.key.as_deref(), Some("laptop.key")); @@ -3328,6 +3328,6 @@ mod tests { assert_eq!(options.token, None); // A key naming none of the client's options is an error, as in the node's files. std::fs::write(&file, "bind-addr = \"127.0.0.1:3000\"\n").unwrap(); - assert!(config::merged(&matches, config::PARTY_OPTIONS).is_err()); + assert!(config::merged(&matches, &config::PARTY, &[]).is_err()); } } diff --git a/src/units.rs b/src/units.rs index 28adab9..e3df366 100644 --- a/src/units.rs +++ b/src/units.rs @@ -1,268 +1,4 @@ -//! 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. +//! Durations and sizes as operators write them (`config::units`), under the name +//! continuum has them by. -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(crate) 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(crate) 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(crate) 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(crate) 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(crate) mod duration_option { - use std::time::Duration; - - use serde::{Deserialize, Deserializer, Serializer, de::Error as _}; - use serde_json::Value as JsonValue; - - pub(crate) fn serialize<S: Serializer>(value: &Duration, s: S) -> Result<S::Ok, S::Error> { - s.serialize_str(&super::format_duration(*value)) - } - - pub(crate) 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(crate) 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(crate) 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(crate) mod size_option { - use serde::{Deserialize, Deserializer, Serializer, de::Error as _}; - use serde_json::Value as JsonValue; - - pub(crate) fn serialize<S: Serializer>(value: &u64, s: S) -> Result<S::Ok, S::Error> { - s.serialize_str(&super::format_size(*value)) - } - - pub(crate) 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"); - } -} +pub(crate) use ::config::units::*; |
