stratum-node-config 0.1.0-alpha.4

Versioned stratum.toml schema, comment-preserving editor, semantic validator, change preview and public-config hash for Stratum nodes
Documentation
//! Validation and preview error types.

use std::fmt;

use serde::ser::{Serialize, SerializeSeq, Serializer};

/// The category of a [`ValidationError`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ValidationErrorKind {
    /// The text is not valid TOML. The message gives only the line and
    /// column, never the parser's description, which can quote the input.
    Syntax,
    /// The text is longer than [`MAX_DOCUMENT_BYTES`](crate::MAX_DOCUMENT_BYTES)
    /// and was not parsed.
    TooLarge,
    /// The document has no `schema_version` key.
    MissingSchemaVersion,
    /// `schema_version` names a version this library does not implement.
    UnsupportedSchemaVersion,
    /// A key or table that the schema does not define.
    UnknownKey,
    /// A value of the wrong TOML type, or a section that is not a table.
    WrongType,
    /// An integer outside its field's range.
    OutOfRange,
    /// A value of the right type that breaks its field's rule.
    InvalidValue,
    /// Two individually valid fields that conflict with each other.
    Conflict,
}

/// One problem found while validating a configuration document.
///
/// The message is lowercase, has no trailing punctuation and never contains
/// the value of a secret-reference field.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
#[non_exhaustive]
pub struct ValidationError {
    kind: ValidationErrorKind,
    path: Option<String>,
    message: String,
}

impl ValidationError {
    pub(crate) fn new(
        kind: ValidationErrorKind,
        path: Option<&str>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            kind,
            path: path.map(str::to_owned),
            message: message.into(),
        }
    }

    pub(crate) fn at(kind: ValidationErrorKind, path: &str, message: impl Into<String>) -> Self {
        Self::new(kind, Some(path), message)
    }

    /// Returns the category of the problem.
    pub fn kind(&self) -> ValidationErrorKind {
        self.kind
    }

    /// Returns the dotted path of the offending key, or `None` for a
    /// document-level problem such as a syntax error.
    pub fn path(&self) -> Option<&str> {
        self.path.as_deref()
    }

    /// Returns the lowercase description of the problem, without the path.
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.path {
            Some(path) => write!(f, "{path}: {}", self.message),
            None => f.write_str(&self.message),
        }
    }
}

impl std::error::Error for ValidationError {}

/// A non-empty list of every [`ValidationError`] found in one document.
///
/// Errors appear in a stable order: size or syntax (each reported alone), then `schema_version`, then
/// unknown keys in document order, then field errors in schema order, then
/// cross-field conflicts. Serialises as a JSON array of errors.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct ValidationErrors {
    errors: Vec<ValidationError>,
}

impl ValidationErrors {
    /// A list holding exactly `error`.
    pub(crate) fn one(error: ValidationError) -> Self {
        Self {
            errors: vec![error],
        }
    }

    /// Wraps `errors`, or returns `None` when it is empty, so the list can
    /// never be built empty.
    pub(crate) fn from_vec(errors: Vec<ValidationError>) -> Option<Self> {
        (!errors.is_empty()).then_some(Self { errors })
    }

    /// Returns the errors as a slice.
    pub fn as_slice(&self) -> &[ValidationError] {
        &self.errors
    }

    /// Iterates over the errors in report order.
    pub fn iter(&self) -> std::slice::Iter<'_, ValidationError> {
        self.errors.iter()
    }

    /// Returns the number of errors, which is at least one.
    pub fn len(&self) -> usize {
        self.errors.len()
    }

    /// Returns `false`: a `ValidationErrors` always holds at least one error.
    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    /// Consumes the list and returns the errors.
    pub fn into_vec(self) -> Vec<ValidationError> {
        self.errors
    }
}

impl fmt::Display for ValidationErrors {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let n = self.errors.len();
        let noun = if n == 1 { "error" } else { "errors" };
        write!(f, "invalid configuration ({n} {noun})")?;
        for e in &self.errors {
            write!(f, "; {e}")?;
        }
        Ok(())
    }
}

impl std::error::Error for ValidationErrors {}

impl Serialize for ValidationErrors {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut seq = serializer.serialize_seq(Some(self.errors.len()))?;
        for e in &self.errors {
            seq.serialize_element(e)?;
        }
        seq.end()
    }
}

impl<'a> IntoIterator for &'a ValidationErrors {
    type Item = &'a ValidationError;
    type IntoIter = std::slice::Iter<'a, ValidationError>;

    fn into_iter(self) -> Self::IntoIter {
        self.errors.iter()
    }
}

impl IntoIterator for ValidationErrors {
    type Item = ValidationError;
    type IntoIter = std::vec::IntoIter<ValidationError>;

    fn into_iter(self) -> Self::IntoIter {
        self.errors.into_iter()
    }
}

/// Why [`preview`](crate::preview) could not produce an edited document.
///
/// Problems with the *result* of an edit (wrong types, out-of-range values,
/// conflicts) are not errors here; they are reported in
/// [`Preview::errors`](crate::Preview::errors).
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum PreviewError {
    /// The base text is not valid TOML, so there is nothing to edit. The
    /// error carries only the line and column, never the offending text.
    #[error("base document is not valid toml: {0}")]
    Syntax(ValidationError),
    /// The base text, or the text the changes would produce, is longer than
    /// [`MAX_DOCUMENT_BYTES`](crate::MAX_DOCUMENT_BYTES); nothing was parsed,
    /// diffed or validated.
    #[error("document is larger than the {limit}-byte limit")]
    TooLarge {
        /// The limit that was exceeded, [`MAX_DOCUMENT_BYTES`](crate::MAX_DOCUMENT_BYTES).
        limit: usize,
    },
    /// A change names a path that is not in the schema.
    #[error("unknown configuration path {path:?}")]
    UnknownPath {
        /// The path as given in the change.
        path: String,
    },
    /// Two changes name the same path.
    #[error("more than one change for {path}")]
    DuplicatePath {
        /// The repeated path.
        path: String,
    },
    /// The base document holds something other than a table or value where
    /// the edit must go, for example `node = 5` or a `[node.name]` table.
    #[error("cannot edit {path}: the base document does not hold a table or value there")]
    NotEditable {
        /// The dotted path of the obstructing item.
        path: String,
    },
}