astrs_cli/error.rs
1//! The `astrs` CLI's single error type.
2//!
3//! Every library-testable command function (`command::validate::run`,
4//! `command::expand::run`, ...) returns `Result<Report, CliError>`.
5//! [`crate::dispatch`] maps the `Err` case to [`CliError::exit_code`] and a
6//! one-line message on the caller's error sink — the only two things
7//! `main.rs` needs to turn into a process exit code (blueprint: "main maps
8//! to exit codes — no `process::exit` inside lib paths").
9//!
10//! Most commands realistically never *return* this as an `Err`: a
11//! diagnostic tool like `validate` or `doctor` embeds every failure mode
12//! (a manifest that fails to parse, a port that is not bindable) as
13//! *content* of its typed report instead, so the report itself is what a
14//! test asserts against. `CliError` exists for the failure modes that
15//! really do abort a command outright — an artifact generator (`expand`,
16//! `graph`, `schema`) with nothing sensible to print because its input
17//! never became a valid manifest, a refusal from the coordinator, a verb
18//! whose engine belongs to a later wave, or a path-safety violation in
19//! `new`.
20
21use std::path::Path;
22
23/// `EX_UNAVAILABLE` (sysexits.h §3): the requested command exists but the
24/// service it needs is not available. Used for
25/// [`CliError::NotImplementedYet`] and [`CliError::FeatureNotEnabled`] so
26/// a script can tell "this AstRS build doesn't have this yet" apart from
27/// an ordinary usage or data error (exit code `1`) without parsing the
28/// message text.
29pub const EXIT_UNAVAILABLE: i32 = 69;
30
31/// Everything that can abort an `astrs` command outright.
32#[derive(Debug, thiserror::Error)]
33#[non_exhaustive]
34pub enum CliError {
35 /// A file could not be read or written.
36 #[error("failed to access `{path}`: {source}")]
37 Io {
38 /// The path that could not be accessed.
39 path: String,
40 /// The underlying I/O error.
41 #[source]
42 source: std::io::Error,
43 },
44
45 /// The manifest did not even parse as YAML.
46 #[error(transparent)]
47 Manifest(#[from] astrs_manifest::ManifestError),
48
49 /// The manifest parsed but failed structural validation.
50 #[error("manifest failed validation:\n{0}")]
51 Validation(#[from] astrs_manifest::ValidationErrors),
52
53 /// Module expansion failed.
54 #[error(transparent)]
55 Expand(#[from] astrs_manifest::expand::ExpandError),
56
57 /// The (validated, expanded) manifest could not become a dataflow
58 /// graph.
59 #[error(transparent)]
60 Graph(#[from] astrs_graph::GraphBuildError),
61
62 /// `migrate from-dora` failed.
63 #[error(transparent)]
64 DoraMigrate(#[from] astrs_migrate::DoraMigrateError),
65
66 /// `migrate from-ros2` failed.
67 #[error(transparent)]
68 Ros2Migrate(#[from] astrs_migrate::Ros2MigrateError),
69
70 /// The embedded daemon (`astrs run`) or the hidden `astrs daemon`
71 /// process failed.
72 #[error(transparent)]
73 Daemon(#[from] astrs_daemon::DaemonError),
74
75 /// The hidden `astrs coordinator` process failed.
76 #[error(transparent)]
77 Coordinator(#[from] astrs_coordinator::CoordinatorError),
78
79 /// The coordinator's parameter/state store could not be opened.
80 #[error("the coordinator store is unusable: {0}")]
81 Store(#[from] astrs_store::Error),
82
83 /// A connection to the coordinator failed.
84 #[error(transparent)]
85 Transport(#[from] astrs_transport::TransportError),
86
87 /// The hidden `astrs runtime` process failed.
88 #[error(transparent)]
89 Runtime(#[from] astrs_runtime::RuntimeError),
90
91 /// A node could not connect to its daemon (`astrs runtime`).
92 #[error(transparent)]
93 Node(#[from] astrs_node_api::NodeError),
94
95 /// An `.arec` recording could not be read (`astrs bag info`, `astrs
96 /// replay`).
97 #[error(transparent)]
98 Recording(#[from] astrs_recording::RecordingError),
99
100 /// A rosbag2 `.db3`/`.mcap` file could not be read or written, or a
101 /// requested `astrs bag convert` direction is not one this build
102 /// bridges (`astrs bag info`, `astrs bag convert`).
103 #[error(transparent)]
104 Rosbag(#[from] astrs_rosbag::RosbagError),
105
106 /// The `astrs ros2` probe could not join the DDS domain, or its report
107 /// could not be rendered (blueprint §17, §10.2).
108 ///
109 /// A *finding* — an empty domain, a refused multicast join — is never
110 /// this: `ros2 doctor` reports those as checks. This is the case where
111 /// there is nothing to report on because the participant itself would
112 /// not start.
113 #[error("the ROS 2 probe failed: {0}")]
114 Ros2(String),
115
116 /// `astrs top` could not enter or run the terminal (blueprint §17).
117 #[error(transparent)]
118 Tui(#[from] astrs_tui::TuiError),
119
120 /// `astrs top` could not connect to the coordinator.
121 #[error(transparent)]
122 CoordinatorSource(#[from] astrs_tui::CoordinatorSourceError),
123
124 /// `astrs top --replay` could not open its recording.
125 #[error(transparent)]
126 Replay(#[from] astrs_tui::ReplaySourceError),
127
128 /// The coordinator answered a request with an error reply.
129 #[error("the coordinator refused `{request}`: {message}")]
130 Refused {
131 /// The request that was refused, e.g. `"list"`.
132 request: &'static str,
133 /// The coordinator's own message.
134 message: String,
135 },
136
137 /// The coordinator answered with a reply this verb cannot use — a
138 /// protocol violation rather than a refusal.
139 #[error("the coordinator answered `{request}` with an unexpected `{reply}`")]
140 UnexpectedReply {
141 /// The request that was sent.
142 request: &'static str,
143 /// The reply variant that came back.
144 reply: &'static str,
145 },
146
147 /// No cluster token could be found, and the verb needs one (§16).
148 #[error(
149 "no cluster token: pass `--token`/`--token-file`, set `{env}`, or run `astrs up` in a directory whose `{file}` this process can read"
150 )]
151 NoToken {
152 /// The environment variable that would have supplied it.
153 env: &'static str,
154 /// The conventional file name (§16).
155 file: &'static str,
156 },
157
158 /// A token was found but is not a 64-hex value (§16).
159 #[error("the cluster token in `{path}` is not a 64-hex value: {source}")]
160 BadToken {
161 /// Where the bad token came from.
162 path: String,
163 /// Why it was rejected.
164 #[source]
165 source: astrs_wire::AuthTokenError,
166 },
167
168 /// A `host[:port]` (or bare port) argument could not be resolved.
169 #[error("`{input}` is not a usable coordinator address: {reason}")]
170 BadAddress {
171 /// What the user typed.
172 input: String,
173 /// Why it could not be used.
174 reason: String,
175 },
176
177 /// A flag's value was not of the shape the flag needs.
178 #[error("`--{flag} {value}` is not valid: {reason}")]
179 BadArgument {
180 /// The flag, without its leading dashes.
181 flag: &'static str,
182 /// The value that was rejected.
183 value: String,
184 /// Why it was rejected.
185 reason: String,
186 },
187
188 /// A cluster process could not be started or stopped.
189 #[error("could not {action} the {process}: {reason}")]
190 Cluster {
191 /// What was attempted, e.g. `"start"`.
192 action: &'static str,
193 /// Which process, e.g. `"coordinator"`.
194 process: &'static str,
195 /// Why it failed.
196 reason: String,
197 },
198
199 /// A verb that needs a live cluster found none.
200 #[error("no cluster is running here (`{detail}`); start one with `astrs up`")]
201 NoCluster {
202 /// What the probe actually observed.
203 detail: String,
204 },
205
206 /// A dataflow reference named nothing the coordinator knows (or named
207 /// more than one thing).
208 #[error("`{reference}` does not name one dataflow: {reason}")]
209 UnknownDataflow {
210 /// What the user typed.
211 reference: String,
212 /// What was found instead.
213 reason: String,
214 },
215
216 /// A cluster process is already running here, and the verb refuses to
217 /// start a second one over it.
218 #[error("a {process} is already running here (pid {pid}{address}); stop it with `astrs down`")]
219 AlreadyRunning {
220 /// Which process, e.g. `"coordinator"`.
221 process: &'static str,
222 /// Its process id, from the pidfile (§24.2).
223 pid: u32,
224 /// Where it listens, rendered with a leading separator, or empty.
225 address: String,
226 },
227
228 /// A verb (or a flag on one) whose implementation belongs to a wave
229 /// this build predates.
230 #[error(
231 "`{verb}` is not implemented yet (scheduled for {wave}); every other verb `astrs --help` lists is available in this build"
232 )]
233 NotImplementedYet {
234 /// The verb (or `group subcommand`) that was invoked, e.g.
235 /// `"node add"` or `"ros2 doctor"`.
236 verb: &'static str,
237 /// The wave this verb is scheduled for, e.g.
238 /// [`crate::command::stub::WAVE_BAG`].
239 wave: &'static str,
240 },
241
242 /// An optional feature exists as a stub but is gated behind a Cargo
243 /// feature this build does not enable.
244 #[error(
245 "{feature} is not enabled in this build (scheduled for {wave}); rebuild with `--features {feature}` once it ships"
246 )]
247 FeatureNotEnabled {
248 /// The Cargo feature name, e.g. `"verify"`.
249 feature: &'static str,
250 /// The wave this feature is scheduled for, e.g. `"W5/W6"`.
251 wave: &'static str,
252 },
253
254 /// `astrs validate --prove` ran on a build without the `verify`
255 /// feature, so no solver was available to discharge the obligations.
256 ///
257 /// Distinct from [`Self::FeatureNotEnabled`], which says a feature has
258 /// not shipped yet: `verify` has shipped, and the obligations were
259 /// still *encoded* and printed — only the verdicts are missing.
260 #[error(
261 "--prove needs the `verify` feature, which this build does not enable; the obligations above were encoded but not solved. Rebuild with `cargo install astrs-cli --features verify` (or `cargo build -p astrs-cli --features verify`)."
262 )]
263 ProofUnavailable,
264
265 /// `run --deterministic` was given without `--from-recording`.
266 ///
267 /// Refused before anything is built or spawned (blueprint §14) — a user
268 /// who asks for a deterministic run never gets a non-deterministic one
269 /// wearing the label, because there is nothing to fix the timer wheel
270 /// to without a recording.
271 #[error(
272 "--deterministic needs --from-recording <path>: a deterministic run fixes the timer wheel to a recording's HLC stream, and none was given"
273 )]
274 DeterministicNeedsRecording,
275
276 /// `new` refused to write outside its target directory.
277 #[error("refusing to write outside the target directory: `{path}`")]
278 UnsafePath {
279 /// The offending resolved path.
280 path: String,
281 },
282
283 /// `new` was asked to write into a directory that already has
284 /// conflicting files in it.
285 #[error("`{path}` already exists; pass `--force` to overwrite, or choose an empty directory")]
286 TargetExists {
287 /// The offending path.
288 path: String,
289 },
290}
291
292impl CliError {
293 /// Build a [`CliError::Io`] from a path and the I/O failure accessing
294 /// it.
295 #[must_use]
296 pub fn io(path: impl AsRef<Path>, source: std::io::Error) -> Self {
297 Self::Io {
298 path: path.as_ref().display().to_string(),
299 source,
300 }
301 }
302
303 /// The process exit code this error should produce.
304 ///
305 /// [`Self::NotImplementedYet`], [`Self::FeatureNotEnabled`] and
306 /// [`Self::ProofUnavailable`] use [`EXIT_UNAVAILABLE`] so scripts can
307 /// tell "this build cannot do that" apart from an ordinary failure;
308 /// everything else is a plain `1` (`EXIT_FAILURE`), matching every
309 /// other Unix CLI tool's default.
310 #[must_use]
311 pub fn exit_code(&self) -> i32 {
312 match self {
313 Self::NotImplementedYet { .. }
314 | Self::FeatureNotEnabled { .. }
315 | Self::ProofUnavailable => EXIT_UNAVAILABLE,
316 _ => 1,
317 }
318 }
319}
320
321#[cfg(test)]
322mod tests {
323 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
324 use super::*;
325
326 #[test]
327 fn proof_unavailable_uses_the_unavailable_exit_code() {
328 let err = CliError::ProofUnavailable;
329 assert_eq!(err.exit_code(), EXIT_UNAVAILABLE);
330 assert!(err.to_string().contains("--features verify"));
331 }
332
333 #[test]
334 fn not_implemented_yet_uses_the_unavailable_exit_code() {
335 let err = CliError::NotImplementedYet {
336 verb: "bag info",
337 wave: crate::command::stub::WAVE_BAG,
338 };
339 assert_eq!(err.exit_code(), EXIT_UNAVAILABLE);
340 assert!(err.to_string().contains("bag info"));
341 assert!(err.to_string().contains("rosbag"));
342 }
343
344 #[test]
345 fn feature_not_enabled_uses_the_unavailable_exit_code() {
346 let err = CliError::FeatureNotEnabled {
347 feature: "verify",
348 wave: "W5/W6",
349 };
350 assert_eq!(err.exit_code(), EXIT_UNAVAILABLE);
351 assert!(err.to_string().contains("verify"));
352 }
353
354 #[test]
355 fn ordinary_errors_use_exit_code_one() {
356 let err = CliError::UnsafePath {
357 path: "/tmp/x".to_string(),
358 };
359 assert_eq!(err.exit_code(), 1);
360 }
361
362 #[test]
363 fn io_helper_carries_the_display_path() {
364 let err = CliError::io(
365 "/tmp/nope",
366 std::io::Error::new(std::io::ErrorKind::NotFound, "nope"),
367 );
368 assert!(err.to_string().contains("/tmp/nope"));
369 }
370
371 #[test]
372 fn manifest_error_converts_via_from() {
373 let source = astrs_manifest::Manifest::from_yaml_str("not: [a, manifest").unwrap_err();
374 let err: CliError = source.into();
375 assert!(matches!(err, CliError::Manifest(_)));
376 }
377}