mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Structured failure: one closed shape for every way the product can fail.
//!
//! A failure is never bare text. It always carries a category, a stable code,
//! a message, a hint and a retry mark, so a caller decides its next step
//! without parsing prose. Absence of any of those fields is a defect.

pub mod category;
pub mod render;

pub use category::{Category, ExitNumber};

use std::fmt;

/// A single machine-readable failure.
///
/// Construct through the category helpers rather than the struct literal, so
/// the retry mark stays consistent with the category.
#[derive(Debug, Clone)]
pub struct Failure {
    category: Category,
    code: &'static str,
    message: String,
    hint: Option<String>,
    /// Overrides the category default when the concrete condition is known.
    retryable_override: Option<bool>,
    /// What the failure carries beyond its four mandatory fields.
    ///
    /// Held behind a pointer, and absent altogether on the ordinary failure
    /// that carries none of it. A failure travels inside every `Result` this
    /// product returns, so every field written here is paid for on every call
    /// that never fails at all.
    extras: Option<Box<Extras>>,
}

/// The parts of a failure that most failures do not have.
#[derive(Debug, Clone, Default)]
struct Extras {
    /// The chain of causes, outermost first.
    causes: Vec<String>,
    /// Conditions the server reported beyond the first one.
    extra_conditions: Vec<String>,
    /// The measured values this failure was built around, each under its name.
    ///
    /// A catalogue words the sentence and substitutes these in, so the source
    /// never has to build a sentence in one language for every reader.
    details: Vec<(&'static str, String)>,
}

impl Failure {
    /// Builds a failure in the given category.
    ///
    /// `code` is a stable identifier callers may branch on; it never changes
    /// meaning between releases. `message` is human prose and is never used as
    /// an identifier.
    #[must_use]
    pub fn new(category: Category, code: &'static str, message: impl Into<String>) -> Self {
        Self {
            category,
            code,
            message: message.into(),
            hint: None,
            retryable_override: None,
            extras: None,
        }
    }

    /// Records one measured value under the name a catalogue substitutes it by.
    ///
    /// This is how a failure keeps its measurements without wording a sentence
    /// around them: the source supplies the value, and the catalogue of the
    /// reader's language supplies the words.
    #[must_use]
    pub fn with_detail(mut self, name: &'static str, value: impl Into<String>) -> Self {
        self.extras
            .get_or_insert_with(Box::default)
            .details
            .push((name, value.into()));
        self
    }

    /// Attaches a concrete next action for the caller.
    #[must_use]
    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
        self.hint = Some(hint.into());
        self
    }

    /// Overrides the category's default retry mark.
    ///
    /// Used for server conditions, where whether repeating helps depends on the
    /// condition rather than on the category.
    #[must_use]
    pub const fn with_retryable(mut self, retryable: bool) -> Self {
        self.retryable_override = Some(retryable);
        self
    }

    /// Appends one link to the cause chain, outermost first.
    #[must_use]
    pub fn with_cause(mut self, cause: impl Into<String>) -> Self {
        self.extras
            .get_or_insert_with(Box::default)
            .causes
            .push(cause.into());
        self
    }

    /// Records a server condition beyond the first one.
    ///
    /// The server may report several conditions for one statement; reporting
    /// only the first hides the rest from the caller.
    #[must_use]
    pub fn with_extra_condition(mut self, condition: impl Into<String>) -> Self {
        self.extras
            .get_or_insert_with(Box::default)
            .extra_conditions
            .push(condition.into());
        self
    }

    /// The failure category.
    #[must_use]
    pub const fn category(&self) -> Category {
        self.category
    }

    /// The stable identifier for this failure.
    #[must_use]
    pub const fn code(&self) -> &'static str {
        self.code
    }

    /// The human-readable message.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }

    /// The suggested next action, when one exists.
    #[must_use]
    pub fn hint(&self) -> Option<&str> {
        self.hint.as_deref()
    }

    /// The cause chain, outermost first.
    #[must_use]
    pub fn causes(&self) -> &[String] {
        self.extras
            .as_deref()
            .map_or(&[], |extras| extras.causes.as_slice())
    }

    /// Server conditions beyond the first.
    #[must_use]
    pub fn extra_conditions(&self) -> &[String] {
        self.extras
            .as_deref()
            .map_or(&[], |extras| extras.extra_conditions.as_slice())
    }

    /// The measured values this failure carries, each under its name.
    #[must_use]
    pub fn details(&self) -> &[(&'static str, String)] {
        self.extras
            .as_deref()
            .map_or(&[], |extras| extras.details.as_slice())
    }

    /// Whether repeating the same call may succeed without changing the input.
    #[must_use]
    pub fn is_retryable(&self) -> bool {
        self.retryable_override
            .unwrap_or_else(|| self.category.is_retryable())
    }

    /// The exit number this failure produces.
    #[must_use]
    pub const fn exit_number(&self) -> ExitNumber {
        self.category.exit_number()
    }
}

impl fmt::Display for Failure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.code, self.message)
    }
}

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

/// The result type used across the whole product.
pub type Result<T> = std::result::Result<T, Failure>;

/// Constructors grouped by category, so the retry mark is never set by hand.
impl Failure {
    /// The caller's input to this tool is wrong.
    #[must_use]
    pub fn usage(code: &'static str, message: impl Into<String>) -> Self {
        Self::new(Category::Usage, code, message)
    }

    /// Analysis refused the statement before it was sent.
    #[must_use]
    pub fn validation(code: &'static str, message: impl Into<String>) -> Self {
        Self::new(Category::Validation, code, message)
    }

    /// A profile or setting is missing or invalid.
    #[must_use]
    pub fn config(code: &'static str, message: impl Into<String>) -> Self {
        Self::new(Category::Config, code, message)
    }

    /// The server could not be reached.
    #[must_use]
    pub fn network(code: &'static str, message: impl Into<String>) -> Self {
        Self::new(Category::Network, code, message)
    }

    /// The credential was refused.
    #[must_use]
    pub fn authentication(code: &'static str, message: impl Into<String>) -> Self {
        Self::new(Category::Authentication, code, message)
    }

    /// The credential may not do what was asked.
    #[must_use]
    pub fn permission(code: &'static str, message: impl Into<String>) -> Self {
        Self::new(Category::Permission, code, message)
    }

    /// The requested object does not exist.
    #[must_use]
    pub fn absence(code: &'static str, message: impl Into<String>) -> Self {
        Self::new(Category::Absence, code, message)
    }

    /// The change hit a lock, a deadlock or a constraint.
    #[must_use]
    pub fn conflict(code: &'static str, message: impl Into<String>) -> Self {
        Self::new(Category::Conflict, code, message)
    }

    /// Some phase exceeded its time budget.
    #[must_use]
    pub fn timeout(code: &'static str, message: impl Into<String>) -> Self {
        Self::new(Category::Timeout, code, message)
    }

    /// The server returned an error of its own.
    #[must_use]
    pub fn server(code: &'static str, message: impl Into<String>) -> Self {
        Self::new(Category::Server, code, message)
    }

    /// A size, row or packet ceiling was reached.
    #[must_use]
    pub fn limit(code: &'static str, message: impl Into<String>) -> Self {
        Self::new(Category::Limit, code, message)
    }

    /// The work was cancelled from outside.
    #[must_use]
    pub fn interrupted(code: &'static str, message: impl Into<String>) -> Self {
        Self::new(Category::Interrupted, code, message)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The retry mark follows the category unless a concrete condition
    /// overrides it.
    #[test]
    fn retry_mark_follows_category_by_default() {
        let transient = Failure::network("net.unreachable", "server not reached");
        assert!(transient.is_retryable());

        let permanent = Failure::usage("usage.bad_flag", "unknown value");
        assert!(!permanent.is_retryable());
    }

    /// A server condition decides its own retry mark, because the category
    /// alone cannot tell a deadlock from a syntax error.
    #[test]
    fn server_condition_overrides_the_retry_mark() {
        let retryable = Failure::server("server.1213", "deadlock found").with_retryable(true);
        assert!(retryable.is_retryable());
        assert_eq!(retryable.exit_number(), ExitNumber::Server);

        let permanent = Failure::server("server.1064", "syntax error");
        assert!(!permanent.is_retryable());
    }

    /// All server conditions are kept, not just the first one.
    #[test]
    fn every_server_condition_is_kept() {
        let failure = Failure::server("server.1364", "field has no default")
            .with_extra_condition("column `b` has no default")
            .with_extra_condition("column `c` has no default");
        assert_eq!(failure.extra_conditions().len(), 2);
    }
}