diff options
| author | tv <tv@krebsco.de> | 2026-11-29 01:37:39 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-11-29 01:37:39 +0000 |
| commit | bcb729ce0cae2cd8bbd8f60f8e98a81674bcd4fb (patch) | |
| tree | 7ed9a9bdfd0b55061cc701585e550957563f5597 | |
| parent | fd0e8b29a86444b772f71d5db767c201b04cad2b (diff) | |
config: the report of a configuration, and --print-config
The report moves to the crate, as it was (report::report, Reports,
Values): each option of a schema with its value, by the settings in
effect given as JSON by option name, and where it came from; imported
values and secrets left out. And the argument a program prints it by
(arguments::with_print_config, prints_config).
continuum gives its settings and what it loaded to it; --print-config
and GET /admin/config say what they said.
| -rw-r--r-- | crates/config/Cargo.toml | 2 | ||||
| -rw-r--r-- | crates/config/src/arguments.rs | 56 | ||||
| -rw-r--r-- | crates/config/src/lib.rs | 2 | ||||
| -rw-r--r-- | crates/config/src/report.rs | 120 | ||||
| -rw-r--r-- | docs/architecture.md | 2 | ||||
| -rw-r--r-- | src/config/mod.rs | 115 |
6 files changed, 202 insertions, 95 deletions
diff --git a/crates/config/Cargo.toml b/crates/config/Cargo.toml index 2308315..a025f3d 100644 --- a/crates/config/Cargo.toml +++ b/crates/config/Cargo.toml @@ -24,7 +24,7 @@ tracing = ["dep:tracing"] [dependencies] anyhow = "1.0" clap = { version = "4.6", optional = true } -serde = { version = "1.0", optional = true } +serde = { version = "1.0", features = ["derive"], optional = true } serde_json = "1.0" toml = { version = "1.1", optional = true } tracing = { version = "0.1", optional = true } diff --git a/crates/config/src/arguments.rs b/crates/config/src/arguments.rs index 5f51b2b..4a251da 100644 --- a/crates/config/src/arguments.rs +++ b/crates/config/src/arguments.rs @@ -14,6 +14,24 @@ use crate::layer::{Entry, Layer, Overlay, Provenance, Sources, from_import, over use crate::option::{Kind, OptionSpec, Schema, from_text}; pub const CONFIG: &str = "config"; +/// Printing the report of the configuration and exiting (`with_print_config`). +pub const PRINT_CONFIG: &str = "print-config"; + +/// `command` taking `--print-config`: a program given it prints its configuration's +/// report (`report::report`) and exits (`prints_config`). +pub fn with_print_config(command: Command) -> Command { + command.arg( + Arg::new(PRINT_CONFIG) + .long(PRINT_CONFIG) + .action(ArgAction::SetTrue) + .help("Print the effective configuration as JSON (with each value's source) and exit."), + ) +} + +/// Whether `--print-config` was given. +pub fn prints_config(matches: &ArgMatches) -> bool { + matches.get_flag(PRINT_CONFIG) +} /// Stops on an argument naming an option that is gone, saying why, before the command /// line is read: clap would call it unexpected. @@ -211,6 +229,44 @@ mod tests { 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")); + // The report: each option's value and where it is from, a secret's left out. + let settings: serde_json::Map<String, JsonValue> = layer + .iter() + .map(|(name, entry)| (name.clone(), entry.value.clone())) + .collect(); + let origins = layer + .iter() + .map(|(name, entry)| (name.clone(), entry.origin.clone())) + .collect(); + let files = [scratch.0.join("main.json")]; + let report = crate::report::report( + &SCHEMA, + &settings, + &origins, + &files, + crate::report::Values::Interpolated, + ); + assert_eq!(report["files"], json!([path("main.json")])); + let options = &report["options"]; + assert_eq!(options["name"]["value"], json!("main")); + assert_eq!(options["name"]["source"], json!("file")); + assert!( + options["name"]["file"] + .as_str() + .is_some_and(|file| file.ends_with("main.json")) + ); + assert_eq!( + options["remote"], + json!({ "source": "default", "value": null }) + ); + assert_eq!(options["token"]["secret"], json!(true)); + assert!(options["token"].get("value").is_none()); + assert!(!report.to_string().contains("hush")); + let command = with_print_config(with_options(Command::new("program"), OPTIONS)); + let matches = command + .try_get_matches_from(["program", "--print-config"]) + .unwrap(); + assert!(prints_config(&matches)); // Arguments over files, and an unset back to the default. let layer = merged_of(&[ "--config", diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index aae8bce..bff1221 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -6,6 +6,7 @@ //! * [`arguments`]: the command line, and files and arguments put together (with the //! feature `clap`); //! * [`layer`]: values and where they came from, later sources over earlier ones; +//! * [`report`]: what each option ended up as and where from, to print or to serve; //! * [`import`]: values taken from elsewhere instead of written out; //! * [`units`]: durations and sizes as operators write them. @@ -15,6 +16,7 @@ pub mod file; pub mod import; pub mod layer; pub mod option; +pub mod report; pub mod units; #[cfg(test)] diff --git a/crates/config/src/report.rs b/crates/config/src/report.rs new file mode 100644 index 0000000..dfbaa23 --- /dev/null +++ b/crates/config/src/report.rs @@ -0,0 +1,120 @@ +//! The report of a configuration: what each option ended up as and where its value came +//! from, for a program to print (`--print-config`) or to serve. + +use std::collections::BTreeMap; +use std::path::PathBuf; + +use serde_json::Value as JsonValue; + +use crate::layer::{Origin, Provenance}; +use crate::option::Schema; + +/// How a report shows text with placeholders. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] +pub enum Values { + /// As it ends up. + #[default] + Interpolated, + /// As written, placeholders and all. + Original, +} + +/// The reports of a configuration, either way of showing text with placeholders: made +/// once, at a program's start, for it to serve. +#[derive(Debug, Clone, Default)] +pub struct Reports { + interpolated: JsonValue, + original: JsonValue, +} + +impl Reports { + /// Both reports (`report`). + pub fn of( + schema: &Schema, + settings: &serde_json::Map<String, JsonValue>, + origins: &BTreeMap<String, Origin>, + files: &[PathBuf], + ) -> Reports { + Reports { + interpolated: report(schema, settings, origins, files, Values::Interpolated), + original: report(schema, settings, origins, files, Values::Original), + } + } + + pub fn get(&self, values: Values) -> &JsonValue { + match values { + Values::Interpolated => &self.interpolated, + Values::Original => &self.original, + } + } +} + +/// The effective configuration with each value's source, as JSON: `files`, those read, +/// and `options`, each of `schema`'s by name, with its `value` (of `settings`, the +/// settings in effect by option name; `null` where they hold none), its `source` +/// (`default`, `file` with the `file`, or `argument`), and where they apply `imported`, +/// `templates`, `unset` and `secret`. Imported values are left out (they may be secret); +/// their importers are listed instead. Secrets are left out however they were given. +/// Text with placeholders is shown as `values` says, the text as written listed. Hidden +/// options are left out unless set. +pub fn report( + schema: &Schema, + settings: &serde_json::Map<String, JsonValue>, + origins: &BTreeMap<String, Origin>, + files: &[PathBuf], + values: Values, +) -> JsonValue { + let options: serde_json::Map<String, JsonValue> = schema + .options + .iter() + .filter(|spec| !spec.hidden || origins.contains_key(spec.name)) + .map(|spec| { + let mut entry = serde_json::Map::new(); + let origin = origins.get(spec.name); + match origin { + None => { + entry.insert("source".into(), "default".into()); + } + Some(origin) => { + match &origin.provenance { + Provenance::File(path) => { + entry.insert("source".into(), "file".into()); + entry.insert("file".into(), path.display().to_string().into()); + } + Provenance::Argument => { + entry.insert("source".into(), "argument".into()); + } + } + if origin.is_imported() { + entry.insert("imported".into(), origin.imports.clone().into()); + } + // Of a secret, the text may hold some of it. + if !origin.templates.is_empty() && !spec.secret { + entry.insert("templates".into(), origin.templates.clone().into()); + } + if origin.unset { + entry.insert("unset".into(), true.into()); + } + } + } + let given = origin.is_some_and(|origin| !origin.unset); + if spec.secret && given { + entry.insert("secret".into(), true.into()); + } else if !origin.is_some_and(Origin::is_imported) { + let written = origin.and_then(|origin| origin.written.clone()); + let value = match (values, written) { + (Values::Original, Some(written)) => written, + _ => settings.get(spec.name).cloned().unwrap_or(JsonValue::Null), + }; + entry.insert("value".into(), value); + } + (spec.name.to_owned(), JsonValue::Object(entry)) + }) + .collect(); + serde_json::json!({ + "files": files.iter().map(|path| path.display().to_string()).collect::<Vec<_>>(), + "options": options, + }) +} diff --git a/docs/architecture.md b/docs/architecture.md index 6827387..5a5d438 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/) | 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. | +| [`config/`](../src/config/), [`crates/config/`](../crates/config/) | 2,600, 2,300 | The options, the settings they make, and their checks; 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, the report, 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/mod.rs b/src/config/mod.rs index a32211e..efc190d 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -32,6 +32,7 @@ pub(crate) use ::config::arguments::{merged, with_options}; pub(crate) use ::config::layer::read; pub(crate) use ::config::layer::{Layer, Origin, Provenance}; pub(crate) use ::config::option::{Kind, OptionSpec, Schema, option}; +pub(crate) use ::config::report::{Reports, Values}; /// What the node's configuration is read by: its options, those that can't be combined, /// and those that are gone. @@ -1541,19 +1542,11 @@ const CONFLICTS: &[(&[&str], &[&str])] = &[( // --- command line -------------------------------------------------------------- -const PRINT_CONFIG: &str = "print-config"; - fn command() -> Command { let command = Command::new("continuum") .version(env!("CARGO_PKG_VERSION")) .long_version(crate::release::described()) .about("continuum: a replicated Automerge document over Mycelium, libp2p or Tor") - .arg( - Arg::new(PRINT_CONFIG) - .long(PRINT_CONFIG) - .action(ArgAction::SetTrue) - .help("Print the effective configuration as JSON (with each value's source) and exit."), - ) .subcommand( Command::new(NODE_ID) .about( @@ -1568,7 +1561,7 @@ fn command() -> Command { .help("Make a new key in the file where there is none, as node-key-create"), ), ); - with_options(command, OPTIONS) + with_options(::config::arguments::with_print_config(command), OPTIONS) } /// `continuum node-id FILE`: the node ID of the key in `FILE` (`Loaded::node_id`). @@ -1615,100 +1608,36 @@ impl Loaded { } } -/// How `GET /admin/config` shows text with placeholders (`?values=`). -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) enum Values { - /// As it ends up. - #[default] - Interpolated, - /// As written, placeholders and all. - Original, -} - -/// The configuration reports, made once at start for `GET /admin/config`. -#[derive(Debug, Clone, Default)] -pub(crate) struct Reports { - interpolated: JsonValue, - original: JsonValue, -} - -impl Reports { - pub(crate) fn get(&self, values: Values) -> &JsonValue { - match values { - Values::Interpolated => &self.interpolated, - Values::Original => &self.original, - } - } -} - impl Loaded { /// The effective configuration with each value's source, for `--print-config` and /// `GET /admin/config`. Imported values are left out (they may be secret); their /// importers are listed instead. Secrets are left out however they were given. /// Text with placeholders is shown as `values` says, the text as written listed. pub(crate) fn report(&self, values: Values) -> JsonValue { - let settings = match serde_json::to_value(&self.settings) { + ::config::report::report( + &SCHEMA, + &self.settings_by_option(), + &self.origins, + &self.files, + values, + ) + } + + /// The settings in effect, by option name. + fn settings_by_option(&self) -> serde_json::Map<String, JsonValue> { + match serde_json::to_value(&self.settings) { Ok(JsonValue::Object(settings)) => settings, _ => serde_json::Map::new(), - }; - let options: serde_json::Map<String, JsonValue> = OPTIONS - .iter() - .filter(|spec| !spec.hidden || self.origins.contains_key(spec.name)) - .map(|spec| { - let mut entry = serde_json::Map::new(); - let origin = self.origins.get(spec.name); - match origin { - None => { - entry.insert("source".into(), "default".into()); - } - Some(origin) => { - match &origin.provenance { - Provenance::File(path) => { - entry.insert("source".into(), "file".into()); - entry.insert("file".into(), path.display().to_string().into()); - } - Provenance::Argument => { - entry.insert("source".into(), "argument".into()); - } - } - if origin.is_imported() { - entry.insert("imported".into(), origin.imports.clone().into()); - } - // Of a secret, the text may hold some of it. - if !origin.templates.is_empty() && !spec.secret { - entry.insert("templates".into(), origin.templates.clone().into()); - } - if origin.unset { - entry.insert("unset".into(), true.into()); - } - } - } - let given = origin.is_some_and(|origin| !origin.unset); - if spec.secret && given { - entry.insert("secret".into(), true.into()); - } else if !origin.is_some_and(Origin::is_imported) { - let written = origin.and_then(|origin| origin.written.clone()); - let value = match (values, written) { - (Values::Original, Some(written)) => written, - _ => settings.get(spec.name).cloned().unwrap_or(JsonValue::Null), - }; - entry.insert("value".into(), value); - } - (spec.name.to_owned(), JsonValue::Object(entry)) - }) - .collect(); - serde_json::json!({ - "files": self.files.iter().map(|path| path.display().to_string()).collect::<Vec<_>>(), - "options": options, - }) + } } pub(crate) fn reports(&self) -> Reports { - Reports { - interpolated: self.report(Values::Interpolated), - original: self.report(Values::Original), - } + Reports::of( + &SCHEMA, + &self.settings_by_option(), + &self.origins, + &self.files, + ) } } @@ -1717,7 +1646,7 @@ impl Loaded { pub(crate) fn load() -> Result<Loaded> { ::config::arguments::refuse_gone(std::env::args().skip(1), &SCHEMA)?; let matches = command().get_matches(); - let print_only = matches.get_flag(PRINT_CONFIG); + let print_only = ::config::arguments::prints_config(&matches); let node_id = matches.subcommand_matches(NODE_ID).map(|sub| { let file = sub.get_one::<String>("file").expect("required"); (PathBuf::from(file), sub.get_flag("create")) |
