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}
124
125impl CliError {
126 /// Returns the process exit code; see [`exit`](crate::exit).
127 ///
128 /// # Examples
129 ///
130 /// ```
131 /// use stratum_node_cli::{exit, CliError};
132 ///
133 /// let err = CliError::Server {
134 /// status: 409,
135 /// code: "conflict".into(),
136 /// message: "stale base revision".into(),
137 /// details: Vec::new(),
138 /// };
139 /// assert_eq!(err.to_string(), "conflict: stale base revision");
140 /// assert_eq!(err.exit_code(), exit::CONFLICT);
141 /// ```
142 pub fn exit_code(&self) -> u8 {
143 match self {
144 Self::Usage(_) | Self::Url(_) | Self::MissingKeyFile => exit::USAGE,
145 Self::KeyFile { .. }
146 | Self::TokenFile { .. }
147 | Self::File { .. }
148 | Self::FileContents { .. }
149 | Self::Local(_) => exit::FAILURE,
150 Self::Unreachable { .. } => exit::UNREACHABLE,
151 Self::Protocol(_) => exit::PROTOCOL,
152 Self::Server { code, .. } => exit::for_server_code(code),
153 Self::Refused(_) => exit::REFUSED,
154 Self::InvalidPreview { .. } => exit::INVALID,
155 Self::NotConfirmed => exit::NOT_CONFIRMED,
156 Self::TimedOut(_) => exit::TIMED_OUT,
157 Self::ExportIncomplete(_) => exit::EXPORT_INCOMPLETE,
158 }
159 }
160
161 /// Returns a short machine-readable code: the server's `error.code`, or
162 /// one of `usage`, `local`, `unreachable`, `protocol`, `refused`,
163 /// `invalid`, `not_confirmed`, `timed_out` and `export_incomplete` for
164 /// failures found by the client.
165 pub fn code(&self) -> &str {
166 match self {
167 Self::Usage(_) | Self::Url(_) | Self::MissingKeyFile => "usage",
168 Self::KeyFile { .. }
169 | Self::TokenFile { .. }
170 | Self::File { .. }
171 | Self::FileContents { .. }
172 | Self::Local(_) => "local",
173 Self::Unreachable { .. } => "unreachable",
174 Self::Protocol(_) => "protocol",
175 Self::Server { code, .. } => code,
176 Self::Refused(_) => "refused",
177 Self::InvalidPreview { .. } => "invalid",
178 Self::NotConfirmed => "not_confirmed",
179 Self::TimedOut(_) => "timed_out",
180 Self::ExportIncomplete(_) => "export_incomplete",
181 }
182 }
183
184 /// Returns advice for a server error whose code alone does not say what
185 /// to do next, or `None`. The code, message and exit code are not
186 /// changed; the hint is printed after them.
187 ///
188 /// # Examples
189 ///
190 /// ```
191 /// use stratum_node_cli::CliError;
192 ///
193 /// let err = CliError::Server {
194 /// status: 409,
195 /// code: "archive_required".into(),
196 /// message: "no archive for this suspension".into(),
197 /// details: Vec::new(),
198 /// };
199 /// assert!(err.hint().is_some_and(|hint| hint.contains("--no-archive")));
200 /// assert_eq!(CliError::NotConfirmed.hint(), None);
201 /// ```
202 pub fn hint(&self) -> Option<&'static str> {
203 let Self::Server { code, .. } = self else {
204 return None;
205 };
206 let hint = match code.as_str() {
207 "suspended" => {
208 "the node's administrator has suspended a membership this request depends on: \
209 yours, or that of the pod's owner. Signed requests by or to a suspended member \
210 are refused until the administrator resumes it; a public profile stays readable \
211 with `stratum profile show`"
212 }
213 "archive_required" => {
214 "removal needs an archive taken during the member's current suspension: run \
215 `stratum member archive <did>` first, or pass --no-archive to remove without \
216 one (the waiver is signed and recorded)"
217 }
218 "pod_data_present" => {
219 "this key's pod data from an earlier membership is still on disk: the operator \
220 must run `stratumd purge --member <did>` once its grace period has passed, and \
221 then issue a new invitation"
222 }
223 "gate_unavailable" => {
224 "the gate cannot serve this request now: pod writes are paused for a backup or \
225 archive, or the gate has not heard from the node's controller in time; nothing \
226 was forwarded. Retry shortly; if it persists, the operator should check that \
227 stratumd is running"
228 }
229 "pod_unavailable" => {
230 "the node's pod server could not be reached, or the node has no pods or no \
231 canonical origin yet; nothing about your membership changed. Retry shortly; \
232 if it persists, tell the operator"
233 }
234 "insufficient_storage" => {
235 "writes are refused: the pod is over its storage quota (PUT is refused; reading \
236 and deleting still work), or the node's pod volume is low. Delete data, or ask \
237 the administrator to raise limits.pod_bytes_per_tenant"
238 }
239 "app_forbidden" => {
240 "this key is not permitted on this listener or path: application keys reach only \
241 non-ACL paths in their owner's pod through the proxy listener, and member keys \
242 reach only the member listener"
243 }
244 "rate_limited" => {
245 "the gate refused the signed pod request because the principal, application-key \
246 or node rate limit is exhausted; wait for Retry-After seconds and try again"
247 }
248 _ => return None,
249 };
250 Some(hint)
251 }
252
253 /// Returns the validation errors attached to an `invalid` failure, as
254 /// `path: message` lines; empty for every other failure.
255 pub fn details(&self) -> &[String] {
256 match self {
257 Self::Server { details, .. } | Self::InvalidPreview { details } => details,
258 _ => &[],
259 }
260 }
261}