stratum-node-cli 0.1.0-alpha.4

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, a probe that did not read back, an answer naming
    /// another member or state than the one acted on, or an existing
    /// profile card that does not name its owner.
    #[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,
    /// A bounded wait ran out: `join` waited for the node to provision the
    /// pod (rerunning `join` continues from where it stopped), or
    /// `member suspend --wait` waited for the suspension to be `enforced`.
    #[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),
    /// `app install`: a container's ACL did not read back as it was
    /// written, so consent was not sent. The message names the container.
    #[error("{0}")]
    ReadBackMismatch(String),
    /// `app install`: consent was refused, by the node or because the
    /// installation stopped being `pending_consent` before a write. The
    /// message says which, and lists anything written that could not be
    /// removed.
    #[error("{0}")]
    ConsentRefused(String),
    /// `app withdraw` or `app cleanup`: the withdrawn grant's ACL cleanup
    /// is still pending for at least one container.
    #[error("{0}")]
    CleanupPending(String),
    /// An ACL the client would have to rewrite holds a statement it does
    /// not evaluate, so it wrote nothing to that ACL. The message names the
    /// ACL and the statement.
    #[error("{0}")]
    AclNotEvaluated(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,
            Self::ReadBackMismatch(_) | Self::ConsentRefused(_) => exit::GRANT_NOT_CONFIRMED,
            Self::CleanupPending(_) => exit::CLEANUP_PENDING,
            Self::AclNotEvaluated(_) => exit::ACL_NOT_EVALUATED,
        }
    }

    /// Returns a short machine-readable code: the server's `error.code`, or
    /// one of `usage`, `local`, `unreachable`, `protocol`, `refused`,
    /// `invalid`, `not_confirmed`, `timed_out`, `export_incomplete`,
    /// `read_back_mismatch`, `consent_refused`, `cleanup_pending` and
    /// `acl_not_evaluated` 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",
            Self::ReadBackMismatch(_) => "read_back_mismatch",
            Self::ConsentRefused(_) => "consent_refused",
            Self::CleanupPending(_) => "cleanup_pending",
            Self::AclNotEvaluated(_) => "acl_not_evaluated",
        }
    }

    /// Returns advice for a failure whose code alone does not say what to do
    /// next, or `None`: a server error a person can meet, or one of the
    /// client's own grant and cleanup failures. The code, message and exit
    /// code are not changed; the hint is printed after them.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_cli::CliError;
    ///
    /// let err = CliError::Server {
    ///     status: 409,
    ///     code: "archive_required".into(),
    ///     message: "no archive for this suspension".into(),
    ///     details: Vec::new(),
    /// };
    /// assert!(err.hint().is_some_and(|hint| hint.contains("--no-archive")));
    /// assert_eq!(CliError::NotConfirmed.hint(), None);
    /// ```
    pub fn hint(&self) -> Option<&'static str> {
        let code =
            match self {
                Self::Server { code, .. } => code.as_str(),
                Self::ReadBackMismatch(_) => return Some(
                    "a granted container's ACL did not read back as written, so consent was not \
                     sent and what was written was removed; another writer may have changed it. \
                     Run `stratum app install` again, or withdraw the pending installation with \
                     `stratum app withdraw`",
                ),
                Self::ConsentRefused(_) => return Some(
                    "the installation was not consented to and what this run wrote was removed; \
                     `stratum app show <installation>` reports its state. Anything listed as not \
                     removed can be edited with `stratum pod acl get` and `stratum pod acl put`",
                ),
                Self::CleanupPending(_) => return Some(
                    "the application's authorisation is still in at least one container's ACL; \
                     its key is disabled, so the grant is inert, but run `stratum app cleanup \
                     <installation>` to remove it and report the cleanup",
                ),
                Self::AclNotEvaluated(_) => return Some(
                    "the client writes only ACLs it can reason about: remove or rewrite the named \
                     statement with `stratum pod acl get` and `stratum pod acl put`, then run the \
                     command again",
                ),
                _ => return None,
            };
        let hint = match code {
            "suspended" => {
                "the node's administrator has suspended a membership this request depends on: \
                 yours, or that of the pod's owner. Signed requests by or to a suspended member \
                 are refused until the administrator resumes it; a public profile stays readable \
                 with `stratum profile show`"
            }
            "archive_required" => {
                "removal needs an archive taken during the member's current suspension: run \
                 `stratum member archive <did>` first, or pass --no-archive to remove without \
                 one (the waiver is signed and recorded)"
            }
            "pod_data_present" => {
                "this key's pod data from an earlier membership is still on disk: the operator \
                 must run `stratumd purge --member <did>` once its grace period has passed, and \
                 then issue a new invitation"
            }
            "gate_unavailable" => {
                "the gate cannot serve this request now: pod writes are paused for a backup or \
                 archive, or the gate has not heard from the node's controller in time; nothing \
                 was forwarded. Retry shortly; if it persists, the operator should check that \
                 stratumd is running"
            }
            "pod_unavailable" => {
                "the node's pod server could not be reached, or the node has no pods or no \
                 canonical origin yet; nothing about your membership changed. Retry shortly; \
                 if it persists, tell the operator"
            }
            "insufficient_storage" => {
                "writes are refused: the pod is over its storage quota (PUT is refused; reading \
                 and deleting still work), or the node's pod volume is low. Delete data, or ask \
                 the administrator to raise limits.pod_bytes_per_tenant"
            }
            "app_forbidden" => {
                "this key is not permitted on this listener or path: application keys reach only \
                 non-ACL paths in their owner's pod through the proxy listener, and member keys \
                 reach only the member listener"
            }
            "rate_limited" => {
                "the gate refused the signed pod request because the principal, application-key \
                 or node rate limit is exhausted; wait for Retry-After seconds and try again"
            }
            "workspace_unavailable" => {
                "this node has no workspace slot for the installation (in this release no slot \
                 exists at all): install again with --workspace none"
            }
            "application_unavailable" => {
                "the application is withdrawn or disabled and cannot be installed now; \
                 `stratum app catalogue` lists the applications that can"
            }
            "image_absent" => {
                "the tenant daemon does not hold the manifest's image ID: load the image into the \
                 tenant daemon as the tenant daemon user from the host shell, then approve again"
            }
            "image_has_volumes" => {
                "the image declares a VOLUME, which would give each job an unlimited anonymous \
                 volume: rebuild the image without VOLUME and approve the new image ID"
            }
            "runner_unavailable" => {
                "the node's runner could not be reached or refused, so the image could not be \
                 checked and nothing was stored; approve again shortly, and if it persists the \
                 operator should check the stratum-runner service"
            }
            "signer_unavailable" => {
                "the node recorded the request, but its signer has not yet made or enabled the \
                 application key. After an install, run `stratum app install` again with the \
                 same --operation-id (or `stratum app list`) to finish it; after a consent the \
                 node keeps trying, and `stratum app show` reports when it is active"
            }
            _ => return None,
        };
        Some(hint)
    }

    /// 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,
            _ => &[],
        }
    }
}