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, a probe that did not read back, an answer naming
95    /// another member or state than the one acted on, or an existing
96    /// profile card that does not name its owner.
97    #[error("refused: {0}")]
98    Refused(String),
99    /// A preview reported validation errors, so nothing was sent to apply.
100    #[error("the previewed configuration is invalid")]
101    InvalidPreview {
102        /// The validation errors, as `path: message`.
103        details: Vec<String>,
104    },
105    /// Changes were previewed but not confirmed, so nothing was applied. Also
106    /// returned by every other command that asks first (`join`, `pod rm`,
107    /// `member repair`, `member cancel`): nothing was sent.
108    #[error("not applied: confirm interactively or pass --yes")]
109    NotConfirmed,
110    /// A bounded wait ran out: `join` waited for the node to provision the
111    /// pod (rerunning `join` continues from where it stopped), or
112    /// `member suspend --wait` waited for the suspension to be `enforced`.
113    #[error("{0}")]
114    TimedOut(String),
115    /// `export` wrote its archive and manifest, but entries changed,
116    /// vanished or were skipped during the walk; the manifest lists them.
117    #[error("{0}")]
118    ExportIncomplete(String),
119    /// Writing output, reading the clock or the random source, or signing
120    /// failed.
121    #[error("{0}")]
122    Local(String),
123    /// `app install`: a container's ACL did not read back as it was
124    /// written, so consent was not sent. The message names the container.
125    #[error("{0}")]
126    ReadBackMismatch(String),
127    /// `app install`: consent was refused, by the node or because the
128    /// installation stopped being `pending_consent` before a write. The
129    /// message says which, and lists anything written that could not be
130    /// removed.
131    #[error("{0}")]
132    ConsentRefused(String),
133    /// `app withdraw` or `app cleanup`: the withdrawn grant's ACL cleanup
134    /// is still pending for at least one container.
135    #[error("{0}")]
136    CleanupPending(String),
137    /// An ACL the client would have to rewrite holds a statement it does
138    /// not evaluate, so it wrote nothing to that ACL. The message names the
139    /// ACL and the statement.
140    #[error("{0}")]
141    AclNotEvaluated(String),
142}
143
144impl CliError {
145    /// Returns the process exit code; see [`exit`](crate::exit).
146    ///
147    /// # Examples
148    ///
149    /// ```
150    /// use stratum_node_cli::{exit, CliError};
151    ///
152    /// let err = CliError::Server {
153    ///     status: 409,
154    ///     code: "conflict".into(),
155    ///     message: "stale base revision".into(),
156    ///     details: Vec::new(),
157    /// };
158    /// assert_eq!(err.to_string(), "conflict: stale base revision");
159    /// assert_eq!(err.exit_code(), exit::CONFLICT);
160    /// ```
161    pub fn exit_code(&self) -> u8 {
162        match self {
163            Self::Usage(_) | Self::Url(_) | Self::MissingKeyFile => exit::USAGE,
164            Self::KeyFile { .. }
165            | Self::TokenFile { .. }
166            | Self::File { .. }
167            | Self::FileContents { .. }
168            | Self::Local(_) => exit::FAILURE,
169            Self::Unreachable { .. } => exit::UNREACHABLE,
170            Self::Protocol(_) => exit::PROTOCOL,
171            Self::Server { code, .. } => exit::for_server_code(code),
172            Self::Refused(_) => exit::REFUSED,
173            Self::InvalidPreview { .. } => exit::INVALID,
174            Self::NotConfirmed => exit::NOT_CONFIRMED,
175            Self::TimedOut(_) => exit::TIMED_OUT,
176            Self::ExportIncomplete(_) => exit::EXPORT_INCOMPLETE,
177            Self::ReadBackMismatch(_) | Self::ConsentRefused(_) => exit::GRANT_NOT_CONFIRMED,
178            Self::CleanupPending(_) => exit::CLEANUP_PENDING,
179            Self::AclNotEvaluated(_) => exit::ACL_NOT_EVALUATED,
180        }
181    }
182
183    /// Returns a short machine-readable code: the server's `error.code`, or
184    /// one of `usage`, `local`, `unreachable`, `protocol`, `refused`,
185    /// `invalid`, `not_confirmed`, `timed_out`, `export_incomplete`,
186    /// `read_back_mismatch`, `consent_refused`, `cleanup_pending` and
187    /// `acl_not_evaluated` for failures found by the client.
188    pub fn code(&self) -> &str {
189        match self {
190            Self::Usage(_) | Self::Url(_) | Self::MissingKeyFile => "usage",
191            Self::KeyFile { .. }
192            | Self::TokenFile { .. }
193            | Self::File { .. }
194            | Self::FileContents { .. }
195            | Self::Local(_) => "local",
196            Self::Unreachable { .. } => "unreachable",
197            Self::Protocol(_) => "protocol",
198            Self::Server { code, .. } => code,
199            Self::Refused(_) => "refused",
200            Self::InvalidPreview { .. } => "invalid",
201            Self::NotConfirmed => "not_confirmed",
202            Self::TimedOut(_) => "timed_out",
203            Self::ExportIncomplete(_) => "export_incomplete",
204            Self::ReadBackMismatch(_) => "read_back_mismatch",
205            Self::ConsentRefused(_) => "consent_refused",
206            Self::CleanupPending(_) => "cleanup_pending",
207            Self::AclNotEvaluated(_) => "acl_not_evaluated",
208        }
209    }
210
211    /// Returns advice for a failure whose code alone does not say what to do
212    /// next, or `None`: a server error a person can meet, or one of the
213    /// client's own grant and cleanup failures. The code, message and exit
214    /// code are not changed; the hint is printed after them.
215    ///
216    /// # Examples
217    ///
218    /// ```
219    /// use stratum_node_cli::CliError;
220    ///
221    /// let err = CliError::Server {
222    ///     status: 409,
223    ///     code: "archive_required".into(),
224    ///     message: "no archive for this suspension".into(),
225    ///     details: Vec::new(),
226    /// };
227    /// assert!(err.hint().is_some_and(|hint| hint.contains("--no-archive")));
228    /// assert_eq!(CliError::NotConfirmed.hint(), None);
229    /// ```
230    pub fn hint(&self) -> Option<&'static str> {
231        let code =
232            match self {
233                Self::Server { code, .. } => code.as_str(),
234                Self::ReadBackMismatch(_) => return Some(
235                    "a granted container's ACL did not read back as written, so consent was not \
236                     sent and what was written was removed; another writer may have changed it. \
237                     Run `stratum app install` again, or withdraw the pending installation with \
238                     `stratum app withdraw`",
239                ),
240                Self::ConsentRefused(_) => return Some(
241                    "the installation was not consented to and what this run wrote was removed; \
242                     `stratum app show <installation>` reports its state. Anything listed as not \
243                     removed can be edited with `stratum pod acl get` and `stratum pod acl put`",
244                ),
245                Self::CleanupPending(_) => return Some(
246                    "the application's authorisation is still in at least one container's ACL; \
247                     its key is disabled, so the grant is inert, but run `stratum app cleanup \
248                     <installation>` to remove it and report the cleanup",
249                ),
250                Self::AclNotEvaluated(_) => return Some(
251                    "the client writes only ACLs it can reason about: remove or rewrite the named \
252                     statement with `stratum pod acl get` and `stratum pod acl put`, then run the \
253                     command again",
254                ),
255                _ => return None,
256            };
257        let hint = match code {
258            "suspended" => {
259                "the node's administrator has suspended a membership this request depends on: \
260                 yours, or that of the pod's owner. Signed requests by or to a suspended member \
261                 are refused until the administrator resumes it; a public profile stays readable \
262                 with `stratum profile show`"
263            }
264            "archive_required" => {
265                "removal needs an archive taken during the member's current suspension: run \
266                 `stratum member archive <did>` first, or pass --no-archive to remove without \
267                 one (the waiver is signed and recorded)"
268            }
269            "pod_data_present" => {
270                "this key's pod data from an earlier membership is still on disk: the operator \
271                 must run `stratumd purge --member <did>` once its grace period has passed, and \
272                 then issue a new invitation"
273            }
274            "gate_unavailable" => {
275                "the gate cannot serve this request now: pod writes are paused for a backup or \
276                 archive, or the gate has not heard from the node's controller in time; nothing \
277                 was forwarded. Retry shortly; if it persists, the operator should check that \
278                 stratumd is running"
279            }
280            "pod_unavailable" => {
281                "the node's pod server could not be reached, or the node has no pods or no \
282                 canonical origin yet; nothing about your membership changed. Retry shortly; \
283                 if it persists, tell the operator"
284            }
285            "insufficient_storage" => {
286                "writes are refused: the pod is over its storage quota (PUT is refused; reading \
287                 and deleting still work), or the node's pod volume is low. Delete data, or ask \
288                 the administrator to raise limits.pod_bytes_per_tenant"
289            }
290            "app_forbidden" => {
291                "this key is not permitted on this listener or path: application keys reach only \
292                 non-ACL paths in their owner's pod through the proxy listener, and member keys \
293                 reach only the member listener"
294            }
295            "rate_limited" => {
296                "the gate refused the signed pod request because the principal, application-key \
297                 or node rate limit is exhausted; wait for Retry-After seconds and try again"
298            }
299            "workspace_unavailable" => {
300                "this node has no workspace slot for the installation (in this release no slot \
301                 exists at all): install again with --workspace none"
302            }
303            "application_unavailable" => {
304                "the application is withdrawn or disabled and cannot be installed now; \
305                 `stratum app catalogue` lists the applications that can"
306            }
307            "image_absent" => {
308                "the tenant daemon does not hold the manifest's image ID: load the image into the \
309                 tenant daemon as the tenant daemon user from the host shell, then approve again"
310            }
311            "image_has_volumes" => {
312                "the image declares a VOLUME, which would give each job an unlimited anonymous \
313                 volume: rebuild the image without VOLUME and approve the new image ID"
314            }
315            "runner_unavailable" => {
316                "the node's runner could not be reached or refused, so the image could not be \
317                 checked and nothing was stored; approve again shortly, and if it persists the \
318                 operator should check the stratum-runner service"
319            }
320            "signer_unavailable" => {
321                "the node recorded the request, but its signer has not yet made or enabled the \
322                 application key. After an install, run `stratum app install` again with the \
323                 same --operation-id (or `stratum app list`) to finish it; after a consent the \
324                 node keeps trying, and `stratum app show` reports when it is active"
325            }
326            _ => return None,
327        };
328        Some(hint)
329    }
330
331    /// Returns the validation errors attached to an `invalid` failure, as
332    /// `path: message` lines; empty for every other failure.
333    pub fn details(&self) -> &[String] {
334        match self {
335            Self::Server { details, .. } | Self::InvalidPreview { details } => details,
336            _ => &[],
337        }
338    }
339}