Skip to main content

stratum_node_cli/
error.rs

1//! The error type of every `stratum` command.
2
3use std::path::PathBuf;
4
5use crate::exit;
6use crate::key::KeyFileError;
7use crate::private_file::PrivateFileError;
8use crate::token::TokenFileError;
9use crate::url::ParseUrlError;
10
11/// Why a `stratum` command failed.
12///
13/// Each variant maps to a stable process exit code through
14/// [`exit_code`](Self::exit_code) and to a short machine-readable code
15/// through [`code`](Self::code). A server error displays as
16/// `code: message`, exactly as the node sent it (with control characters
17/// escaped). No variant ever carries the operator's secret key or the
18/// bootstrap token.
19#[derive(Debug, thiserror::Error)]
20#[non_exhaustive]
21pub enum CliError {
22    /// The command line asks for something impossible, such as an unknown
23    /// configuration path or a value of the wrong type.
24    #[error("{0}")]
25    Usage(String),
26    /// The `--url` value was refused.
27    #[error("invalid --url")]
28    Url(#[source] ParseUrlError),
29    /// A command needs the operator key and no `--key-file` was given.
30    #[error("this command needs the operator key: pass --key-file or set STRATUM_KEY_FILE")]
31    MissingKeyFile,
32    /// The operator key file could not be created or loaded.
33    #[error("key file {}", path.display())]
34    KeyFile {
35        /// The key file.
36        path: PathBuf,
37        /// What went wrong.
38        #[source]
39        source: KeyFileError,
40    },
41    /// The bootstrap token file could not be read.
42    #[error("token file {}", path.display())]
43    TokenFile {
44        /// The token file.
45        path: PathBuf,
46        /// What went wrong.
47        #[source]
48        source: TokenFileError,
49    },
50    /// A file other than the key or token file (resume file, claim body
51    /// file) could not be created, read or removed.
52    #[error("file {}", path.display())]
53    File {
54        /// The file.
55        path: PathBuf,
56        /// What went wrong.
57        #[source]
58        source: PrivateFileError,
59    },
60    /// A file was readable but its contents are not what the command needs.
61    #[error("file {}: {message}", path.display())]
62    FileContents {
63        /// The file.
64        path: PathBuf,
65        /// What is wrong with it.
66        message: String,
67    },
68    /// The node could not be reached.
69    #[error("cannot reach the node at {url}: {message}")]
70    Unreachable {
71        /// The URL that was tried.
72        url: String,
73        /// The transport error.
74        message: String,
75    },
76    /// The node answered with something the API contract does not allow.
77    #[error("unexpected response from the node: {0}")]
78    Protocol(String),
79    /// The node refused the request with an error from the API contract.
80    #[error("{code}: {message}")]
81    Server {
82        /// The HTTP status.
83        status: u16,
84        /// The `error.code` member.
85        code: String,
86        /// The `error.message` member.
87        message: String,
88        /// Validation errors sent with an `invalid` error, as `path: message`.
89        details: Vec<String>,
90    },
91    /// A local check refused what the node sent: a claim body naming
92    /// another claimant or node, an expired claim, a manifest with a bad
93    /// signature or another author, an admission notice for another node or
94    /// with another hash, or a probe that did not read back.
95    #[error("refused: {0}")]
96    Refused(String),
97    /// A preview reported validation errors, so nothing was sent to apply.
98    #[error("the previewed configuration is invalid")]
99    InvalidPreview {
100        /// The validation errors, as `path: message`.
101        details: Vec<String>,
102    },
103    /// Changes were previewed but not confirmed, so nothing was applied. Also
104    /// returned by every other command that asks first (`join`, `pod rm`,
105    /// `member repair`, `member cancel`): nothing was sent.
106    #[error("not applied: confirm interactively or pass --yes")]
107    NotConfirmed,
108    /// `join` waited for the node to provision the pod and it did not
109    /// finish in time; rerunning `join` continues from where it stopped.
110    #[error("{0}")]
111    TimedOut(String),
112    /// `export` wrote its archive and manifest, but entries changed,
113    /// vanished or were skipped during the walk; the manifest lists them.
114    #[error("{0}")]
115    ExportIncomplete(String),
116    /// Writing output, reading the clock or the random source, or signing
117    /// failed.
118    #[error("{0}")]
119    Local(String),
120}
121
122impl CliError {
123    /// Returns the process exit code; see [`exit`](crate::exit).
124    ///
125    /// # Examples
126    ///
127    /// ```
128    /// use stratum_node_cli::{exit, CliError};
129    ///
130    /// let err = CliError::Server {
131    ///     status: 409,
132    ///     code: "conflict".into(),
133    ///     message: "stale base revision".into(),
134    ///     details: Vec::new(),
135    /// };
136    /// assert_eq!(err.to_string(), "conflict: stale base revision");
137    /// assert_eq!(err.exit_code(), exit::CONFLICT);
138    /// ```
139    pub fn exit_code(&self) -> u8 {
140        match self {
141            Self::Usage(_) | Self::Url(_) | Self::MissingKeyFile => exit::USAGE,
142            Self::KeyFile { .. }
143            | Self::TokenFile { .. }
144            | Self::File { .. }
145            | Self::FileContents { .. }
146            | Self::Local(_) => exit::FAILURE,
147            Self::Unreachable { .. } => exit::UNREACHABLE,
148            Self::Protocol(_) => exit::PROTOCOL,
149            Self::Server { code, .. } => exit::for_server_code(code),
150            Self::Refused(_) => exit::REFUSED,
151            Self::InvalidPreview { .. } => exit::INVALID,
152            Self::NotConfirmed => exit::NOT_CONFIRMED,
153            Self::TimedOut(_) => exit::TIMED_OUT,
154            Self::ExportIncomplete(_) => exit::EXPORT_INCOMPLETE,
155        }
156    }
157
158    /// Returns a short machine-readable code: the server's `error.code`, or
159    /// one of `usage`, `local`, `unreachable`, `protocol`, `refused`,
160    /// `invalid`, `not_confirmed`, `timed_out` and `export_incomplete` for
161    /// failures found by the client.
162    pub fn code(&self) -> &str {
163        match self {
164            Self::Usage(_) | Self::Url(_) | Self::MissingKeyFile => "usage",
165            Self::KeyFile { .. }
166            | Self::TokenFile { .. }
167            | Self::File { .. }
168            | Self::FileContents { .. }
169            | Self::Local(_) => "local",
170            Self::Unreachable { .. } => "unreachable",
171            Self::Protocol(_) => "protocol",
172            Self::Server { code, .. } => code,
173            Self::Refused(_) => "refused",
174            Self::InvalidPreview { .. } => "invalid",
175            Self::NotConfirmed => "not_confirmed",
176            Self::TimedOut(_) => "timed_out",
177            Self::ExportIncomplete(_) => "export_incomplete",
178        }
179    }
180
181    /// Returns the validation errors attached to an `invalid` failure, as
182    /// `path: message` lines; empty for every other failure.
183    pub fn details(&self) -> &[String] {
184        match self {
185            Self::Server { details, .. } | Self::InvalidPreview { details } => details,
186            _ => &[],
187        }
188    }
189}