footing 0.1.18

Feature-gated foundations for Rust backend services
Documentation
use std::{error::Error, fmt};

use crate::result::{ClassifyError, ErrorKind};

/// Maximum number of settings issues retained by one validation pass.
pub const MAX_SETTINGS_ISSUES: usize = 128;
const DEFAULT_SETTINGS_ISSUE_PATH: &str = "settings";
const DEFAULT_SETTINGS_ISSUE_MESSAGE: &str = "are invalid";

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Describes one invalid settings value.
pub struct SettingsIssue {
    path: String,
    message: String,
}

impl SettingsIssue {
    #[must_use]
    /// Creates a settings issue.
    pub fn new(path: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            path: normalize_issue_field(path, DEFAULT_SETTINGS_ISSUE_PATH),
            message: normalize_issue_field(message, DEFAULT_SETTINGS_ISSUE_MESSAGE),
        }
    }

    #[must_use]
    /// Returns the invalid field path.
    pub fn path(&self) -> &str {
        &self.path
    }

    #[must_use]
    /// Returns the validation message.
    pub fn message(&self) -> &str {
        &self.message
    }
}

fn normalize_issue_field(value: impl Into<String>, fallback: &'static str) -> String {
    let value = value.into().trim().to_owned();
    if value.is_empty() {
        fallback.to_owned()
    } else {
        value
    }
}

/// A bounded collection of settings validation failures.
///
/// The collection keeps insertion order so callers can present errors in the
/// same order as their settings fields. Storage is capped at
/// [`MAX_SETTINGS_ISSUES`] and [`SettingsIssues::is_truncated`] reports whether
/// additional issues were omitted.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct SettingsIssues {
    issues: Vec<SettingsIssue>,
    truncated: bool,
}

impl SettingsIssues {
    #[must_use]
    /// Creates an empty issue collection.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds one validation issue unless the collection is already full.
    pub fn push(&mut self, path: impl Into<String>, message: impl Into<String>) {
        self.push_issue(SettingsIssue::new(path, message));
    }

    /// Adds an issue when `condition` is false.
    pub fn require(
        &mut self,
        condition: bool,
        path: impl Into<String>,
        message: impl Into<String>,
    ) {
        if !condition {
            self.push(path, message);
        }
    }

    /// Requires `value` to contain non-whitespace text.
    pub fn require_non_empty(&mut self, path: impl Into<String>, value: &str) {
        let path = path.into();
        self.require(!value.trim().is_empty(), path, "must not be empty");
    }

    #[must_use]
    /// Returns whether the collection is empty.
    pub fn is_empty(&self) -> bool {
        self.issues.is_empty()
    }

    #[must_use]
    /// Returns the number of collected issues.
    pub fn len(&self) -> usize {
        self.issues.len()
    }

    /// Returns whether one or more issues were omitted because the collection
    /// reached [`MAX_SETTINGS_ISSUES`].
    #[must_use]
    pub const fn is_truncated(&self) -> bool {
        self.truncated
    }

    #[must_use]
    /// Borrows the collected issues in insertion order.
    pub fn as_slice(&self) -> &[SettingsIssue] {
        &self.issues
    }

    /// Merges issues from another validation error.
    pub fn extend(&mut self, error: SettingsValidationError) {
        let nested = error.into_issues();
        for issue in nested.issues {
            self.push_issue(issue);
        }
        self.truncated |= nested.truncated;
    }

    /// Merges the error from a nested validation result, if present.
    pub fn extend_result(&mut self, result: Result<(), SettingsValidationError>) {
        if let Err(error) = result {
            self.extend(error);
        }
    }

    /// Converts a non-empty collection into a validation error.
    pub fn into_result(self) -> Result<(), SettingsValidationError> {
        if self.issues.is_empty() {
            Ok(())
        } else {
            Err(SettingsValidationError { issues: self })
        }
    }

    fn push_issue(&mut self, issue: SettingsIssue) {
        if self.issues.len() < MAX_SETTINGS_ISSUES {
            self.issues.push(issue);
        } else {
            self.truncated = true;
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Reports invalid component settings.
pub struct SettingsValidationError {
    issues: SettingsIssues,
}

impl SettingsValidationError {
    #[must_use]
    /// Creates an error from collected issues.
    ///
    /// An empty collection is normalized to a generic issue so the error can
    /// never claim validation failed without explaining why.
    pub fn new(mut issues: SettingsIssues) -> Self {
        if issues.is_empty() {
            issues.push(DEFAULT_SETTINGS_ISSUE_PATH, DEFAULT_SETTINGS_ISSUE_MESSAGE);
        }
        Self { issues }
    }

    #[must_use]
    /// Creates an error containing one issue.
    pub fn single(path: impl Into<String>, message: impl Into<String>) -> Self {
        let mut issues = SettingsIssues::new();
        issues.push(path, message);
        Self { issues }
    }

    #[must_use]
    /// Borrows the collected issues in insertion order.
    pub fn issues(&self) -> &[SettingsIssue] {
        self.issues.as_slice()
    }

    #[must_use]
    /// Consumes the error and returns its issue collection.
    pub fn into_issues(self) -> SettingsIssues {
        self.issues
    }

    /// Returns whether additional issues were omitted by the bounded collector.
    #[must_use]
    pub const fn is_truncated(&self) -> bool {
        self.issues.is_truncated()
    }
}

impl fmt::Display for SettingsValidationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("settings validation failed")?;
        for issue in self.issues() {
            write!(formatter, "\n- {}: {}", issue.path(), issue.message())?;
        }
        if self.issues.is_truncated() {
            formatter.write_str("\n- additional issues omitted")?;
        }
        Ok(())
    }
}

impl Error for SettingsValidationError {}

impl ClassifyError for SettingsValidationError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal("settings_invalid")
    }
}

impl From<&SettingsValidationError> for crate::result::Diagnostic {
    fn from(value: &SettingsValidationError) -> Self {
        let message = value
            .issues()
            .first()
            .map(|issue| format!("{}: {}", issue.path(), issue.message()))
            .unwrap_or_else(|| "settings validation failed".to_owned());
        Self::configuration("settings", message)
    }
}

impl From<SettingsValidationError> for crate::result::Diagnostic {
    fn from(value: SettingsValidationError) -> Self {
        Self::from(&value)
    }
}