stratum-node-cli 0.1.0-alpha.2

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
Documentation
//! The error type of every `stratum` command.

use std::path::PathBuf;

use crate::exit;
use crate::key::KeyFileError;
use crate::private_file::PrivateFileError;
use crate::token::TokenFileError;
use crate::url::ParseUrlError;

/// Why a `stratum` command failed.
///
/// Each variant maps to a stable process exit code through
/// [`exit_code`](Self::exit_code) and to a short machine-readable code
/// through [`code`](Self::code). A server error displays as
/// `code: message`, exactly as the node sent it (with control characters
/// escaped). No variant ever carries the operator's secret key or the
/// bootstrap token.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CliError {
    /// The command line asks for something impossible, such as an unknown
    /// configuration path or a value of the wrong type.
    #[error("{0}")]
    Usage(String),
    /// The `--url` value was refused.
    #[error("invalid --url")]
    Url(#[source] ParseUrlError),
    /// A command needs the operator key and no `--key-file` was given.
    #[error("this command needs the operator key: pass --key-file or set STRATUM_KEY_FILE")]
    MissingKeyFile,
    /// The operator key file could not be created or loaded.
    #[error("key file {}", path.display())]
    KeyFile {
        /// The key file.
        path: PathBuf,
        /// What went wrong.
        #[source]
        source: KeyFileError,
    },
    /// The bootstrap token file could not be read.
    #[error("token file {}", path.display())]
    TokenFile {
        /// The token file.
        path: PathBuf,
        /// What went wrong.
        #[source]
        source: TokenFileError,
    },
    /// A file other than the key or token file (resume file, claim body
    /// file) could not be created, read or removed.
    #[error("file {}", path.display())]
    File {
        /// The file.
        path: PathBuf,
        /// What went wrong.
        #[source]
        source: PrivateFileError,
    },
    /// A file was readable but its contents are not what the command needs.
    #[error("file {}: {message}", path.display())]
    FileContents {
        /// The file.
        path: PathBuf,
        /// What is wrong with it.
        message: String,
    },
    /// The node could not be reached.
    #[error("cannot reach the node at {url}: {message}")]
    Unreachable {
        /// The URL that was tried.
        url: String,
        /// The transport error.
        message: String,
    },
    /// The node answered with something the API contract does not allow.
    #[error("unexpected response from the node: {0}")]
    Protocol(String),
    /// The node refused the request with an error from the API contract.
    #[error("{code}: {message}")]
    Server {
        /// The HTTP status.
        status: u16,
        /// The `error.code` member.
        code: String,
        /// The `error.message` member.
        message: String,
        /// Validation errors sent with an `invalid` error, as `path: message`.
        details: Vec<String>,
    },
    /// A local check refused what the node sent: a claim body naming
    /// another claimant or node, an expired claim, a manifest with a bad
    /// signature or another author, an admission notice for another node or
    /// with another hash, or a probe that did not read back.
    #[error("refused: {0}")]
    Refused(String),
    /// A preview reported validation errors, so nothing was sent to apply.
    #[error("the previewed configuration is invalid")]
    InvalidPreview {
        /// The validation errors, as `path: message`.
        details: Vec<String>,
    },
    /// Changes were previewed but not confirmed, so nothing was applied. Also
    /// returned by every other command that asks first (`join`, `pod rm`,
    /// `member repair`, `member cancel`): nothing was sent.
    #[error("not applied: confirm interactively or pass --yes")]
    NotConfirmed,
    /// `join` waited for the node to provision the pod and it did not
    /// finish in time; rerunning `join` continues from where it stopped.
    #[error("{0}")]
    TimedOut(String),
    /// `export` wrote its archive and manifest, but entries changed,
    /// vanished or were skipped during the walk; the manifest lists them.
    #[error("{0}")]
    ExportIncomplete(String),
    /// Writing output, reading the clock or the random source, or signing
    /// failed.
    #[error("{0}")]
    Local(String),
}

impl CliError {
    /// Returns the process exit code; see [`exit`](crate::exit).
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_cli::{exit, CliError};
    ///
    /// let err = CliError::Server {
    ///     status: 409,
    ///     code: "conflict".into(),
    ///     message: "stale base revision".into(),
    ///     details: Vec::new(),
    /// };
    /// assert_eq!(err.to_string(), "conflict: stale base revision");
    /// assert_eq!(err.exit_code(), exit::CONFLICT);
    /// ```
    pub fn exit_code(&self) -> u8 {
        match self {
            Self::Usage(_) | Self::Url(_) | Self::MissingKeyFile => exit::USAGE,
            Self::KeyFile { .. }
            | Self::TokenFile { .. }
            | Self::File { .. }
            | Self::FileContents { .. }
            | Self::Local(_) => exit::FAILURE,
            Self::Unreachable { .. } => exit::UNREACHABLE,
            Self::Protocol(_) => exit::PROTOCOL,
            Self::Server { code, .. } => exit::for_server_code(code),
            Self::Refused(_) => exit::REFUSED,
            Self::InvalidPreview { .. } => exit::INVALID,
            Self::NotConfirmed => exit::NOT_CONFIRMED,
            Self::TimedOut(_) => exit::TIMED_OUT,
            Self::ExportIncomplete(_) => exit::EXPORT_INCOMPLETE,
        }
    }

    /// Returns a short machine-readable code: the server's `error.code`, or
    /// one of `usage`, `local`, `unreachable`, `protocol`, `refused`,
    /// `invalid`, `not_confirmed`, `timed_out` and `export_incomplete` for
    /// failures found by the client.
    pub fn code(&self) -> &str {
        match self {
            Self::Usage(_) | Self::Url(_) | Self::MissingKeyFile => "usage",
            Self::KeyFile { .. }
            | Self::TokenFile { .. }
            | Self::File { .. }
            | Self::FileContents { .. }
            | Self::Local(_) => "local",
            Self::Unreachable { .. } => "unreachable",
            Self::Protocol(_) => "protocol",
            Self::Server { code, .. } => code,
            Self::Refused(_) => "refused",
            Self::InvalidPreview { .. } => "invalid",
            Self::NotConfirmed => "not_confirmed",
            Self::TimedOut(_) => "timed_out",
            Self::ExportIncomplete(_) => "export_incomplete",
        }
    }

    /// Returns the validation errors attached to an `invalid` failure, as
    /// `path: message` lines; empty for every other failure.
    pub fn details(&self) -> &[String] {
        match self {
            Self::Server { details, .. } | Self::InvalidPreview { details } => details,
            _ => &[],
        }
    }
}