aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Cargo.lock4
-rw-r--r--crates/config/Cargo.toml4
-rw-r--r--crates/config/src/arguments.rs248
-rw-r--r--crates/config/src/file.rs226
-rw-r--r--crates/config/src/import.rs27
-rw-r--r--crates/config/src/layer.rs287
-rw-r--r--crates/config/src/lib.rs15
-rw-r--r--crates/config/src/option.rs156
-rw-r--r--crates/config/src/testing.rs27
-rw-r--r--crates/config/src/units.rs268
-rw-r--r--docs/architecture.md2
-rw-r--r--src/config/file.rs233
-rw-r--r--src/config/mod.rs618
-rw-r--r--src/federation/party.rs6
-rw-r--r--src/units.rs270
15 files changed, 1303 insertions, 1088 deletions
diff --git a/Cargo.lock b/Cargo.lock
index b567587..3d2c35a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -936,7 +936,11 @@ name = "config"
version = "0.1.0"
dependencies = [
"anyhow",
+ "clap",
+ "serde",
"serde_json",
+ "toml 1.2.1+spec-1.1.0",
+ "tracing",
]
[[package]]
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");
+ }
+}
diff --git a/docs/architecture.md b/docs/architecture.md
index 69b0cc3..6827387 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -305,7 +305,7 @@ Roughly by size and by how many rules interact there:
| [`swarm/peer/`](../src/swarm/peer/) + [`sync.rs`](../src/swarm/sync.rs) + [`source.rs`](../src/swarm/source.rs) | 2,300 | The protocol state machine: handshake, liveness, sync sessions with deadlines, who syncs with whom while catching up. Timing-dependent; tested on the simulated network ([`simtest/`](../src/simtest/)). |
| [`state/`](../src/state/) | 1,600 | `AppState` and its write helpers ([`mod.rs`](../src/state/mod.rs)), `PeerState` ([`peer.rs`](../src/state/peer.rs)), `Timing`, reads ([`read.rs`](../src/state/read.rs)) and the `Host` impl ([`host.rs`](../src/state/host.rs)). A hub, not a layer. |
| [`transport/`](../src/transport/) | 11,500 | libp2p ([`libp2p/`](../src/transport/libp2p/), 4,400: addresses, relays, hole punching, which paths to keep), the paths and identity layers (2,300: measuring, failing over, proving node IDs), Mycelium and its daemon ([`mycelium/`](../src/transport/mycelium/), 1,200), Tor (700), the wire format ([`wire.rs`](../src/transport/wire.rs), derived), the simulator. The transports are self-contained behind the `Transport` trait; libp2p's choice of addresses is the subtle part. |
-| [`config/`](../src/config/), [`crates/config/`](../crates/config/) | 3,300, 500 | Layered sources, conflicts, the report; importers and placeholders, in a crate of their own (`config`), which other programs use too. Self-contained. |
+| [`config/`](../src/config/), [`crates/config/`](../crates/config/) | 2,600, 2,300 | The options, the settings they make, their checks and the report; and, in a crate of their own (`config`), which other programs use too, what reads them: files and their includes, arguments, layers and what each value came from, conflicts, importers and placeholders. Self-contained. |
| [`document/store.rs`](../src/document/store.rs) | 1,200 | Conflict-aware JSON over Automerge. Subtle (merged maps, canonical writes), well covered by the rest relying on it. |
| [`swarm/topology/`](../src/swarm/topology/), [`blob.rs`](../src/swarm/blob.rs) | 1,500 | Pure algorithms with tests; the topology hashes each member once, then scores the N² pairs by cheap mixing. |
| [`api/`](../src/api/) | 3,600 | Handlers; the Prometheus rendering is the longest file. The dashboard's page ([`dashboard.html`](../src/api/dashboard/dashboard.html), 2,000 more) is one file of HTML, CSS and script. |
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::*;