stratum-node-cli 0.1.0-alpha.1

The `stratum` operator client for Stratum pod nodes: operator key files, bootstrap claim, signed config apply, audit checkpoint and backup over the loopback API
Documentation
//! Parsing `--set path=value` arguments against the configuration schema.

use stratum_node_config::{schema, Change, Value, ValueType};

/// Parses `--set path=value` arguments into configuration changes, typed by
/// the schema in `stratum-node-config`.
///
/// Each argument is split at its first `=`. The path must name a schema
/// field, and the value is read according to that field's type:
///
/// - **boolean**: `true` or `false`;
/// - **integer**: a decimal integer, optionally negative (the node checks
///   the range);
/// - **string**, **enum** and **secret reference**: the text as given,
///   which may be empty;
/// - **list of strings**: comma-separated elements (`a,b`), or the same path
///   given in several `--set` arguments, whose elements are concatenated in
///   order. An empty value (`path=`) is the empty list. Elements cannot be
///   empty and cannot contain a comma.
///
/// Changes come out in the order their paths first appear; the node applies
/// them in schema order regardless.
///
/// # Examples
///
/// ```
/// use stratum_node_cli::parse_changes;
/// use stratum_node_config::Value;
///
/// # fn main() -> Result<(), stratum_node_cli::ParseChangeError> {
/// let changes = parse_changes([
///     "node.name=alpha",
///     "limits.max_body_bytes=65536",
///     "federation.egress_enabled=false",
/// ])?;
/// assert_eq!(changes[0].value(), &Value::String("alpha".into()));
/// assert_eq!(changes[1].value(), &Value::Integer(65_536));
/// assert_eq!(changes[2].value(), &Value::Boolean(false));
///
/// assert!(parse_changes(["no.such.field=1"]).is_err());
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns a [`ParseChangeError`] for an argument without `=`, an unknown
/// path, a value that does not read as the field's type, or a non-list path
/// given twice.
pub fn parse_changes<I, S>(args: I) -> Result<Vec<Change>, ParseChangeError>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    let mut parsed: Vec<(String, Value)> = Vec::new();
    for arg in args {
        let arg = arg.as_ref();
        let (path, raw) = arg
            .split_once('=')
            .ok_or_else(|| ParseChangeError::MissingEquals {
                argument: arg.to_owned(),
            })?;
        let field = schema()
            .field(path)
            .ok_or_else(|| ParseChangeError::UnknownPath {
                path: path.to_owned(),
            })?;
        let value = parse_value(path, field.value_type(), raw)?;
        match parsed.iter_mut().find(|(seen, _)| seen == path) {
            None => parsed.push((path.to_owned(), value)),
            Some((_, Value::StringList(existing))) => match value {
                Value::StringList(more) => existing.extend(more),
                _ => {
                    return Err(ParseChangeError::Repeated {
                        path: path.to_owned(),
                    })
                }
            },
            Some(_) => {
                return Err(ParseChangeError::Repeated {
                    path: path.to_owned(),
                })
            }
        }
    }
    Ok(parsed
        .into_iter()
        .map(|(path, value)| Change::new(path, value))
        .collect())
}

/// Reads `raw` as a value of type `value_type`.
fn parse_value(path: &str, value_type: ValueType, raw: &str) -> Result<Value, ParseChangeError> {
    let invalid = |expected: &'static str| ParseChangeError::InvalidValue {
        path: path.to_owned(),
        expected,
    };
    match value_type {
        ValueType::Boolean => match raw {
            "true" => Ok(Value::Boolean(true)),
            "false" => Ok(Value::Boolean(false)),
            _ => Err(invalid("true or false")),
        },
        ValueType::Integer { .. } => raw
            .parse::<i64>()
            .map(Value::Integer)
            .map_err(|_| invalid("a decimal integer")),
        ValueType::String | ValueType::Enum { .. } | ValueType::SecretRef => {
            Ok(Value::String(raw.to_owned()))
        }
        ValueType::StringList => {
            if raw.is_empty() {
                return Ok(Value::StringList(Vec::new()));
            }
            let elements: Vec<String> = raw.split(',').map(str::to_owned).collect();
            if elements.iter().any(String::is_empty) {
                return Err(invalid("comma-separated non-empty strings"));
            }
            Ok(Value::StringList(elements))
        }
        _ => Err(ParseChangeError::UnsupportedType {
            path: path.to_owned(),
        }),
    }
}

/// Why a `--set` argument could not be parsed.
///
/// Values are never quoted back, since a value may be a secret reference.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseChangeError {
    /// The argument has no `=`.
    #[error("--set {argument:?} is not of the form path=value")]
    MissingEquals {
        /// The argument as given.
        argument: String,
    },
    /// The path is not a field of the configuration schema.
    #[error("--set: unknown configuration path {path:?} (see `stratum config schema`)")]
    UnknownPath {
        /// The path as given.
        path: String,
    },
    /// The value does not read as the field's type.
    #[error("--set {path}: expected {expected}")]
    InvalidValue {
        /// The field's path.
        path: String,
        /// What the field accepts.
        expected: &'static str,
    },
    /// A field that is not a list was given more than once.
    #[error("--set {path} given more than once")]
    Repeated {
        /// The field's path.
        path: String,
    },
    /// The field has a type this version of the client cannot write.
    #[error("--set {path}: this client cannot write values of this field's type")]
    UnsupportedType {
        /// The field's path.
        path: String,
    },
}