mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Failure categories and the exit numbers they map to.
//!
//! The product publishes a closed list of thirteen failure categories and a
//! closed table of fourteen exit numbers. Both lists are normative: a category
//! outside [`Category`] does not exist, and an exit number outside
//! [`ExitNumber`] must never be observed.
//!
//! The two lists differ by exactly one, and that is deliberate: thirteen of the
//! numbers are the categories, and [`ExitNumber::Success`] is not a failure, so
//! it has no category. Every number a failure can end with has a category of
//! its own.
//!
//! [`Category::ChannelClosed`] is the thirteenth and was the last to arrive. A
//! closed channel used to be reported as `Limit`, distinguished only by the
//! stable code `output.broken_pipe`, so a caller branching on the category
//! could not tell "the reader went away" from "a ceiling was reached" — two
//! conditions with nothing in common but a number. Branching on the category is
//! now enough.

use serde::{Deserialize, Serialize};

/// The closed set of failure categories the product can report.
///
/// Every failure carries exactly one category. The category is stable across
/// releases and is the field callers branch on, never the message text.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Category {
    /// The caller's input to this tool is wrong.
    Usage,
    /// The statement was refused by analysis before it was sent.
    Validation,
    /// A profile or a setting is missing or invalid.
    Config,
    /// The server could not be reached.
    Network,
    /// The credential was refused.
    Authentication,
    /// The credential may not do what was asked.
    Permission,
    /// The requested object does not exist.
    Absence,
    /// The change hit a lock, a deadlock or a constraint.
    Conflict,
    /// Some phase exceeded its time budget.
    Timeout,
    /// The server returned an error of its own.
    Server,
    /// A size, row or packet ceiling was reached.
    Limit,
    /// The work was cancelled from outside.
    Interrupted,
    /// The reader closed the channel the answer was being written to.
    ///
    /// Not a failure of the work: a caller that read as much as it wanted and
    /// walked away is behaving correctly, which is why this is the one category
    /// whose number is a signal number rather than one of the product's own.
    ChannelClosed,
}

impl Category {
    /// Every category this product carries, in the order the annex tabulates.
    ///
    /// Public because the annex is transcribed by hand in an acceptance proof,
    /// and a transcription needs something that notices when it stops being the
    /// whole of what it transcribes. That proof carried twelve of these thirteen
    /// for as long as it existed, so the pair `ChannelClosed` to 141 was
    /// asserted nowhere and could have been swapped for any other number.
    pub const ALL: [Self; 13] = [
        Self::Usage,
        Self::Validation,
        Self::Config,
        Self::Network,
        Self::Authentication,
        Self::Permission,
        Self::Absence,
        Self::Conflict,
        Self::Timeout,
        Self::Server,
        Self::Limit,
        Self::Interrupted,
        Self::ChannelClosed,
    ];

    /// The exit number this category maps to.
    ///
    /// The mapping is total and fixed: every category has exactly one number,
    /// and the number always comes from the published table.
    #[must_use]
    pub const fn exit_number(self) -> ExitNumber {
        match self {
            Self::Usage => ExitNumber::Usage,
            Self::Validation => ExitNumber::Validation,
            Self::Config => ExitNumber::Config,
            Self::Network => ExitNumber::Network,
            Self::Authentication => ExitNumber::Authentication,
            Self::Permission => ExitNumber::Permission,
            Self::Absence => ExitNumber::Absence,
            Self::Conflict => ExitNumber::Conflict,
            Self::Limit => ExitNumber::Limit,
            Self::Server => ExitNumber::Server,
            Self::Timeout => ExitNumber::Timeout,
            Self::Interrupted => ExitNumber::Interrupted,
            Self::ChannelClosed => ExitNumber::BrokenPipe,
        }
    }

    /// Whether repeating the same call may succeed without changing the input.
    ///
    /// `Server` is deliberately absent from the retryable set here: whether a
    /// server condition is worth repeating depends on the condition itself, so
    /// that decision is made where the condition code is known.
    #[must_use]
    pub const fn is_retryable(self) -> bool {
        matches!(self, Self::Network | Self::Conflict | Self::Timeout)
    }

    /// The stable snake_case identifier emitted on the wire.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Usage => "usage",
            Self::Validation => "validation",
            Self::Config => "config",
            Self::Network => "network",
            Self::Authentication => "authentication",
            Self::Permission => "permission",
            Self::Absence => "absence",
            Self::Conflict => "conflict",
            Self::Timeout => "timeout",
            Self::Server => "server",
            Self::Limit => "limit",
            Self::Interrupted => "interrupted",
            Self::ChannelClosed => "channel_closed",
        }
    }
}

/// The closed table of process exit numbers.
///
/// A number outside this list does not exist in the product. Adding one is a
/// change to the published contract, never an implementation detail.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[repr(u8)]
pub enum ExitNumber {
    /// Success.
    Success = 0,
    /// Incorrect use of this tool.
    Usage = 2,
    /// Analysis refused the statement.
    Validation = 3,
    /// Configuration missing or invalid.
    Config = 4,
    /// Network unreachable.
    Network = 5,
    /// Authentication refused.
    Authentication = 6,
    /// Insufficient permission.
    Permission = 7,
    /// Object not found.
    Absence = 8,
    /// Lock conflict, deadlock or constraint.
    Conflict = 9,
    /// Size, row or packet ceiling reached.
    Limit = 10,
    /// Error returned by the server.
    Server = 11,
    /// Time limit reached.
    Timeout = 124,
    /// Interrupted by a signal from the caller.
    Interrupted = 130,
    /// The output channel was closed by the reader.
    BrokenPipe = 141,
}

impl ExitNumber {
    /// The raw process exit code.
    #[must_use]
    pub const fn code(self) -> u8 {
        self as u8
    }
}

impl From<ExitNumber> for std::process::ExitCode {
    fn from(value: ExitNumber) -> Self {
        Self::from(value.code())
    }
}

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

    /// `ALL` holds every variant of `Category`, each exactly once and in its
    /// declared place.
    ///
    /// # Why counting is not enough
    ///
    /// `ALL` is written as `[Self; 13]`, so the compiler counts what is inside
    /// it — but nothing connects that count to the enum. Adding a variant and
    /// leaving `ALL` alone compiles: thirteen elements are still thirteen
    /// elements, and every test that walks `ALL` keeps passing over a set that
    /// is no longer the whole of it. `std::mem::variant_count` would close this
    /// directly and is not stable, so the bridge is built here instead.
    ///
    /// The bridge is the `match`, and it has to yield a position rather than a
    /// yes or no. Exhaustiveness means a variant added to the enum stops this
    /// file from building until it is named here, which puts whoever adds one
    /// inside the block where `ALL` is written rather than somewhere that never
    /// mentions it. Naming it then forces a position, and a position that
    /// belongs to another variant fails the comparison below.
    ///
    /// # What this still does not catch
    ///
    /// A variant named here with a position past the end of `ALL` and left out
    /// of `ALL` itself. The loop walks `ALL`, so it never reaches that variant
    /// to check it, and thirteen elements are still thirteen. Closing it needs
    /// the variant count the language does not hand out on stable. What is left
    /// is deliberate rather than accidental: it takes writing a number nothing
    /// in the array answers to, in the same block as the array.
    #[test]
    fn all_holds_every_category_in_its_declared_place() {
        /// Where each variant sits in `ALL`. Exhaustive on purpose.
        const fn place(category: Category) -> usize {
            match category {
                Category::Usage => 0,
                Category::Validation => 1,
                Category::Config => 2,
                Category::Network => 3,
                Category::Authentication => 4,
                Category::Permission => 5,
                Category::Absence => 6,
                Category::Conflict => 7,
                Category::Timeout => 8,
                Category::Server => 9,
                Category::Limit => 10,
                Category::Interrupted => 11,
                Category::ChannelClosed => 12,
            }
        }

        for (index, category) in Category::ALL.into_iter().enumerate() {
            assert_eq!(
                place(category),
                index,
                "{category:?} is declared at {} and sits at {index} in `ALL`",
                place(category)
            );
        }
    }

    /// Every category maps to a distinct number, so a caller can tell them
    /// apart by exit code alone.
    #[test]
    fn categories_map_to_distinct_numbers() {
        let mut seen = std::collections::BTreeSet::new();
        for category in Category::ALL {
            assert!(
                seen.insert(category.exit_number().code()),
                "duplicate exit number for {category:?}",
            );
        }
        assert_eq!(seen.len(), Category::ALL.len());
    }

    /// The numbers are exactly the ones the contract publishes.
    #[test]
    fn exit_numbers_match_the_published_table() {
        assert_eq!(ExitNumber::Success.code(), 0);
        assert_eq!(ExitNumber::Usage.code(), 2);
        assert_eq!(ExitNumber::Validation.code(), 3);
        assert_eq!(ExitNumber::Config.code(), 4);
        assert_eq!(ExitNumber::Network.code(), 5);
        assert_eq!(ExitNumber::Authentication.code(), 6);
        assert_eq!(ExitNumber::Permission.code(), 7);
        assert_eq!(ExitNumber::Absence.code(), 8);
        assert_eq!(ExitNumber::Conflict.code(), 9);
        assert_eq!(ExitNumber::Limit.code(), 10);
        assert_eq!(ExitNumber::Server.code(), 11);
        assert_eq!(ExitNumber::Timeout.code(), 124);
        assert_eq!(ExitNumber::Interrupted.code(), 130);
        assert_eq!(ExitNumber::BrokenPipe.code(), 141);
    }

    /// Only the three transient categories are retryable without changing input.
    #[test]
    fn only_transient_categories_are_retryable() {
        assert!(Category::Network.is_retryable());
        assert!(Category::Conflict.is_retryable());
        assert!(Category::Timeout.is_retryable());
        assert!(!Category::Usage.is_retryable());
        assert!(!Category::Validation.is_retryable());
        assert!(!Category::Permission.is_retryable());
        assert!(!Category::Absence.is_retryable());
    }
}