Skip to main content

astrs_node_api/
error.rs

1//! [`NodeError`] — every way a node can fail, named.
2//!
3//! One error type for the whole surface, because a node author writes
4//! `-> Result<(), NodeError>` on `main` exactly once and never wants to think
5//! about it again (blueprint §9.1). The variants are grouped by *who is at
6//! fault*, which is what a caller actually branches on:
7//!
8//! | Group | Variants | Typical response |
9//! |---|---|---|
10//! | Environment | [`NodeError::Config`], [`NodeError::MissingEnv`], [`NodeError::BadEnv`] | The node was launched wrong; exit non-zero |
11//! | Connection | [`NodeError::Connect`], [`NodeError::Transport`], [`NodeError::Handshake`], [`NodeError::DaemonGone`] | The daemon is unreachable; exit and let supervision restart |
12//! | Lifecycle | [`NodeError::Stopped`], [`NodeError::Orphaned`] | Wind down cleanly; these are *expected* endings |
13//! | Usage | [`NodeError::UnknownOutput`], [`NodeError::UnknownInput`], [`NodeError::TypeMismatch`], [`NodeError::BlockingInAsync`] | A bug in the node; fix the call |
14//! | Payload | [`NodeError::Data`], [`NodeError::PayloadTooLarge`], [`NodeError::Shm`] | Bad or oversized data |
15//!
16//! # Examples
17//!
18//! ```
19//! use astrs_node_api::NodeError;
20//!
21//! let error = NodeError::Stopped;
22//! assert!(error.is_shutdown());
23//! assert!(!error.is_retryable());
24//! assert_eq!(error.exit_code(), 0, "a requested stop is a clean exit");
25//! ```
26
27use astrs_data::ipc::IpcError;
28use astrs_data::{DataError, TypeUrnError};
29use astrs_scheduler::SchedulerError;
30use astrs_shm::ShmError;
31use astrs_transport::TransportError;
32use astrs_wire::{DataId, IdError, NodeConfigError, StopCause, WireError};
33
34/// The node API's result alias.
35pub type Result<T, E = NodeError> = core::result::Result<T, E>;
36
37/// Everything that can go wrong in a node.
38#[derive(Debug, thiserror::Error)]
39#[non_exhaustive]
40pub enum NodeError {
41    /// The `ASTRS_NODE_CONFIG` blob was missing, corrupt or unusable (§24.2).
42    #[error("node configuration: {0}")]
43    Config(#[source] NodeConfigError),
44
45    /// A required environment variable was unset.
46    #[error("environment variable {name} is not set (was this node spawned by an AstRS daemon?)")]
47    MissingEnv {
48        /// The variable that was looked for.
49        name: &'static str,
50    },
51
52    /// An environment variable held something this build cannot parse.
53    #[error("environment variable {name}={value} is invalid: {reason}")]
54    BadEnv {
55        /// The variable.
56        name: &'static str,
57        /// What it held.
58        value: String,
59        /// Why that is not usable.
60        reason: String,
61    },
62
63    /// No daemon endpoint could be dialled.
64    ///
65    /// Carries every attempt, because "connection refused" on the Unix socket
66    /// and "no route to host" on the TCP fallback are two different
67    /// diagnoses and a node that reports only the last one sends its operator
68    /// looking in the wrong place.
69    #[error("could not reach the daemon: {}", format_attempts(.attempts))]
70    Connect {
71        /// One `(endpoint, reason)` pair per attempt, in the order tried.
72        attempts: Vec<(String, String)>,
73    },
74
75    /// The daemon refused the greeting, or the greeting could not be
76    /// completed (§7.2).
77    #[error("handshake with the daemon failed: {0}")]
78    Handshake(String),
79
80    /// The daemon refused the registration (§7.3 `Register`).
81    #[error("the daemon refused this node's registration: {0}")]
82    Registration(String),
83
84    /// The connection to the daemon ended.
85    #[error("the daemon connection closed")]
86    DaemonGone,
87
88    /// A transport-level failure.
89    #[error("transport: {0}")]
90    Transport(#[source] TransportError),
91
92    /// A protocol-level failure.
93    #[error("wire protocol: {0}")]
94    Wire(#[source] WireError),
95
96    /// A columnar payload could not be built, encoded or decoded.
97    #[error("payload: {0}")]
98    Data(#[source] DataError),
99
100    /// An Arrow IPC stream could not be encoded or decoded (§6.1).
101    #[error("payload encoding: {0}")]
102    Ipc(#[source] IpcError),
103
104    /// A type URN was malformed, unknown, or did not match a port's declared
105    /// layout.
106    #[error("type: {0}")]
107    TypeUrn(#[source] TypeUrnError),
108
109    /// A shared-memory operation failed (§6.2).
110    #[error("shared memory: {0}")]
111    Shm(#[source] ShmError),
112
113    /// An identifier failed its grammar.
114    #[error("identifier: {0}")]
115    Id(#[source] IdError),
116
117    /// An input queue could not be created or registered (§11.2).
118    #[error("scheduler: {0}")]
119    Scheduler(#[source] SchedulerError),
120
121    /// The node has no such output.
122    #[error("this node has no output named `{output}`")]
123    UnknownOutput {
124        /// The name that was asked for.
125        output: DataId,
126    },
127
128    /// The node has no such input.
129    #[error("this node has no input named `{input}`")]
130    UnknownInput {
131        /// The name that was asked for.
132        input: DataId,
133    },
134
135    /// A typed handle was opened on a port whose declared URN says something
136    /// else (§9.2, `ASTRS_TYPE_CHECK=error`).
137    #[error("port `{port}` is declared as `{declared}`, but the handle is typed `{requested}`")]
138    TypeMismatch {
139        /// The port.
140        port: DataId,
141        /// What the manifest says.
142        declared: String,
143        /// What the code asked for.
144        requested: String,
145    },
146
147    /// A payload exceeded the §6.1 cap or the negotiated frame limit.
148    #[error("payload of {len} bytes exceeds the {max}-byte limit")]
149    PayloadTooLarge {
150        /// The payload size.
151        len: usize,
152        /// The applicable ceiling.
153        max: usize,
154    },
155
156    /// A blocking call was made from a single-threaded async context, where
157    /// blocking would deadlock the only worker.
158    ///
159    /// The fix is always the same: call the `_async` twin of whatever was
160    /// called, or run the node's loop on a multi-thread runtime.
161    #[error(
162        "{method} blocks, and this is a current-thread tokio runtime; call {alternative} instead"
163    )]
164    BlockingInAsync {
165        /// The blocking method that was called.
166        method: &'static str,
167        /// The method to call instead.
168        alternative: &'static str,
169    },
170
171    /// The node was asked to stop (§7.3 `Stop`).
172    ///
173    /// Returned by operations attempted after the event stream fused. It is
174    /// an *expected* ending, not a failure — see [`NodeError::is_shutdown`].
175    #[error("the dataflow stopped this node")]
176    Stopped,
177
178    /// The supervising process disappeared, so this node is an orphan (§4.2).
179    #[error("the supervising process {parent_pid} exited; this node is orphaned")]
180    Orphaned {
181        /// The process that went away.
182        parent_pid: u32,
183    },
184
185    /// An operation ran out of time.
186    #[error("{operation} timed out after {millis} ms")]
187    Timeout {
188        /// What was being waited for.
189        operation: &'static str,
190        /// How long it was waited for.
191        millis: u64,
192    },
193
194    /// The request channel to the daemon is full and the caller asked not to
195    /// wait.
196    ///
197    /// The channel is bounded on purpose: an unbounded one turns a wedged
198    /// daemon into unbounded memory growth in every node at once.
199    #[error("the daemon request queue is full ({depth} messages)")]
200    Backpressure {
201        /// The channel's capacity.
202        depth: usize,
203    },
204
205    /// A tokio runtime could not be built for a node created outside one.
206    #[error("could not start a runtime for this node: {0}")]
207    Runtime(String),
208
209    /// A pattern helper was used out of order (§9.4).
210    #[error("{0}")]
211    Pattern(String),
212
213    /// The testing harness could not be driven as asked.
214    #[error("test harness: {0}")]
215    Testing(String),
216}
217
218impl NodeError {
219    /// Whether this error means "shut down cleanly" rather than "something
220    /// broke".
221    ///
222    /// # Examples
223    ///
224    /// ```
225    /// use astrs_node_api::NodeError;
226    ///
227    /// assert!(NodeError::Stopped.is_shutdown());
228    /// assert!(NodeError::Orphaned { parent_pid: 1 }.is_shutdown());
229    /// assert!(!NodeError::DaemonGone.is_shutdown());
230    /// ```
231    #[must_use]
232    pub const fn is_shutdown(&self) -> bool {
233        matches!(self, Self::Stopped | Self::Orphaned { .. })
234    }
235
236    /// Whether retrying the same operation could plausibly succeed.
237    ///
238    /// # Examples
239    ///
240    /// ```
241    /// use astrs_node_api::NodeError;
242    ///
243    /// assert!(NodeError::Backpressure { depth: 64 }.is_retryable());
244    /// assert!(!NodeError::UnknownInput { input: "x".parse()? }.is_retryable());
245    /// # Ok::<(), astrs_wire::IdError>(())
246    /// ```
247    #[must_use]
248    pub const fn is_retryable(&self) -> bool {
249        matches!(
250            self,
251            Self::Backpressure { .. } | Self::Timeout { .. } | Self::Connect { .. }
252        )
253    }
254
255    /// Whether this error is the node's own fault — a call that can never
256    /// succeed as written.
257    #[must_use]
258    pub const fn is_usage_error(&self) -> bool {
259        matches!(
260            self,
261            Self::UnknownOutput { .. }
262                | Self::UnknownInput { .. }
263                | Self::TypeMismatch { .. }
264                | Self::BlockingInAsync { .. }
265                | Self::Pattern(_)
266        )
267    }
268
269    /// The process exit status a `main` should use for this error.
270    ///
271    /// A clean shutdown is `0`; everything else is `1`, which is what the
272    /// daemon's restart policy (§12) reads as a failure.
273    ///
274    /// # Examples
275    ///
276    /// ```
277    /// use astrs_node_api::NodeError;
278    ///
279    /// assert_eq!(NodeError::Stopped.exit_code(), 0);
280    /// assert_eq!(NodeError::DaemonGone.exit_code(), 1);
281    /// ```
282    #[must_use]
283    pub const fn exit_code(&self) -> i32 {
284        if self.is_shutdown() { 0 } else { 1 }
285    }
286
287    /// A short, stable slug for metrics labels and structured logs.
288    #[must_use]
289    pub const fn kind_name(&self) -> &'static str {
290        match self {
291            Self::Config(_) => "config",
292            Self::MissingEnv { .. } => "missing_env",
293            Self::BadEnv { .. } => "bad_env",
294            Self::Connect { .. } => "connect",
295            Self::Handshake(_) => "handshake",
296            Self::Registration(_) => "registration",
297            Self::DaemonGone => "daemon_gone",
298            Self::Transport(_) => "transport",
299            Self::Wire(_) => "wire",
300            Self::Data(_) => "data",
301            Self::Ipc(_) => "ipc",
302            Self::TypeUrn(_) => "type_urn",
303            Self::Shm(_) => "shm",
304            Self::Id(_) => "id",
305            Self::Scheduler(_) => "scheduler",
306            Self::UnknownOutput { .. } => "unknown_output",
307            Self::UnknownInput { .. } => "unknown_input",
308            Self::TypeMismatch { .. } => "type_mismatch",
309            Self::PayloadTooLarge { .. } => "payload_too_large",
310            Self::BlockingInAsync { .. } => "blocking_in_async",
311            Self::Stopped => "stopped",
312            Self::Orphaned { .. } => "orphaned",
313            Self::Timeout { .. } => "timeout",
314            Self::Backpressure { .. } => "backpressure",
315            Self::Runtime(_) => "runtime",
316            Self::Pattern(_) => "pattern",
317            Self::Testing(_) => "testing",
318        }
319    }
320
321    /// The stop cause a node should report for this error, when it reports
322    /// one.
323    #[must_use]
324    pub const fn stop_cause(&self) -> Option<StopCause> {
325        match self {
326            Self::Stopped => Some(StopCause::Requested),
327            Self::Orphaned { .. } | Self::DaemonGone => Some(StopCause::DaemonShutdown),
328            _ => None,
329        }
330    }
331}
332
333/// Renders the attempt list of [`NodeError::Connect`].
334fn format_attempts(attempts: &[(String, String)]) -> String {
335    if attempts.is_empty() {
336        return "no endpoints were configured".to_owned();
337    }
338    attempts
339        .iter()
340        .map(|(endpoint, reason)| format!("{endpoint} ({reason})"))
341        .collect::<Vec<_>>()
342        .join("; ")
343}
344
345impl From<NodeConfigError> for NodeError {
346    fn from(error: NodeConfigError) -> Self {
347        Self::Config(error)
348    }
349}
350
351impl From<TransportError> for NodeError {
352    fn from(error: TransportError) -> Self {
353        Self::Transport(error)
354    }
355}
356
357impl From<WireError> for NodeError {
358    fn from(error: WireError) -> Self {
359        Self::Wire(error)
360    }
361}
362
363impl From<DataError> for NodeError {
364    fn from(error: DataError) -> Self {
365        Self::Data(error)
366    }
367}
368
369impl From<IpcError> for NodeError {
370    fn from(error: IpcError) -> Self {
371        Self::Ipc(error)
372    }
373}
374
375impl From<TypeUrnError> for NodeError {
376    fn from(error: TypeUrnError) -> Self {
377        Self::TypeUrn(error)
378    }
379}
380
381impl From<ShmError> for NodeError {
382    fn from(error: ShmError) -> Self {
383        Self::Shm(error)
384    }
385}
386
387impl From<IdError> for NodeError {
388    fn from(error: IdError) -> Self {
389        Self::Id(error)
390    }
391}
392
393impl From<SchedulerError> for NodeError {
394    fn from(error: SchedulerError) -> Self {
395        Self::Scheduler(error)
396    }
397}
398
399#[cfg(test)]
400mod tests {
401    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
402
403    use super::*;
404
405    fn every_variant() -> Vec<NodeError> {
406        vec![
407            NodeError::Config(NodeConfigError::Base64(
408                astrs_wire::Base64Error::NonCanonicalTail,
409            )),
410            NodeError::MissingEnv {
411                name: "ASTRS_NODE_CONFIG",
412            },
413            NodeError::BadEnv {
414                name: "ASTRS_TYPE_CHECK",
415                value: "loud".to_owned(),
416                reason: "expected off, warn or error".to_owned(),
417            },
418            NodeError::Connect {
419                attempts: vec![("uds:/tmp/x".to_owned(), "refused".to_owned())],
420            },
421            NodeError::Handshake("refused".to_owned()),
422            NodeError::Registration("wrong generation".to_owned()),
423            NodeError::DaemonGone,
424            NodeError::Transport(TransportError::Closed {
425                reason: astrs_transport::CloseReason::Eof,
426            }),
427            NodeError::Wire(WireError::MissingCrc),
428            NodeError::Data(DataError::AllocationFailed { bytes: 8 }),
429            NodeError::Ipc(IpcError::EmptyStream),
430            NodeError::TypeUrn(TypeUrnError::UnknownType {
431                urn: "std/core/v1/Nope".to_owned(),
432            }),
433            NodeError::Shm(ShmError::Closed {
434                name: "astrs-test".to_owned(),
435            }),
436            NodeError::Id(astrs_wire::DataId::new("bad name").unwrap_err()),
437            NodeError::Scheduler(SchedulerError::DuplicateInput(
438                astrs_wire::DataId::new("x").unwrap(),
439            )),
440            NodeError::UnknownOutput {
441                output: astrs_wire::DataId::new("nope").unwrap(),
442            },
443            NodeError::UnknownInput {
444                input: astrs_wire::DataId::new("nope").unwrap(),
445            },
446            NodeError::TypeMismatch {
447                port: astrs_wire::DataId::new("image").unwrap(),
448                declared: "std/media/v1/Image".to_owned(),
449                requested: "std/core/v1/Float64".to_owned(),
450            },
451            NodeError::PayloadTooLarge { len: 1, max: 0 },
452            NodeError::BlockingInAsync {
453                method: "EventStream::recv",
454                alternative: "EventStream::recv_async",
455            },
456            NodeError::Stopped,
457            NodeError::Orphaned { parent_pid: 7 },
458            NodeError::Timeout {
459                operation: "ext_load",
460                millis: 500,
461            },
462            NodeError::Backpressure { depth: 64 },
463            NodeError::Runtime("no threads".to_owned()),
464            NodeError::Pattern("respond() without a request_id".to_owned()),
465            NodeError::Testing("no such node".to_owned()),
466        ]
467    }
468
469    #[test]
470    fn every_variant_renders_and_classifies() {
471        for error in every_variant() {
472            assert!(!error.to_string().is_empty(), "{error:?}");
473            assert!(!error.kind_name().is_empty(), "{error:?}");
474            assert!(error.exit_code() == 0 || error.exit_code() == 1);
475            let _: &dyn std::error::Error = &error;
476        }
477    }
478
479    #[test]
480    fn kind_names_are_unique() {
481        let mut names: Vec<&str> = every_variant().iter().map(NodeError::kind_name).collect();
482        let total = names.len();
483        names.sort_unstable();
484        names.dedup();
485        assert_eq!(names.len(), total, "kind names must identify a variant");
486    }
487
488    #[test]
489    fn shutdown_errors_exit_zero() {
490        assert!(NodeError::Stopped.is_shutdown());
491        assert_eq!(NodeError::Stopped.exit_code(), 0);
492        assert!(NodeError::Orphaned { parent_pid: 3 }.is_shutdown());
493        assert_eq!(NodeError::Orphaned { parent_pid: 3 }.exit_code(), 0);
494        assert!(!NodeError::DaemonGone.is_shutdown());
495        assert_eq!(NodeError::DaemonGone.exit_code(), 1);
496    }
497
498    #[test]
499    fn retryable_and_usage_classes_are_disjoint() {
500        for error in every_variant() {
501            assert!(
502                !(error.is_retryable() && error.is_usage_error()),
503                "{error:?} cannot be both"
504            );
505        }
506        assert!(NodeError::Backpressure { depth: 1 }.is_retryable());
507        assert!(
508            NodeError::BlockingInAsync {
509                method: "a",
510                alternative: "b"
511            }
512            .is_usage_error()
513        );
514    }
515
516    #[test]
517    fn stop_causes_are_reported_only_for_endings() {
518        assert_eq!(NodeError::Stopped.stop_cause(), Some(StopCause::Requested));
519        assert_eq!(
520            NodeError::DaemonGone.stop_cause(),
521            Some(StopCause::DaemonShutdown)
522        );
523        assert_eq!(NodeError::Handshake(String::new()).stop_cause(), None);
524    }
525
526    #[test]
527    fn connect_errors_list_every_attempt() {
528        let error = NodeError::Connect {
529            attempts: vec![
530                (
531                    "uds:/run/astrs/daemon.sock".to_owned(),
532                    "refused".to_owned(),
533                ),
534                ("tcp:127.0.0.1:7408".to_owned(), "timed out".to_owned()),
535            ],
536        };
537        let text = error.to_string();
538        assert!(text.contains("daemon.sock"), "{text}");
539        assert!(text.contains("127.0.0.1:7408"), "{text}");
540        assert!(
541            text.contains("refused") && text.contains("timed out"),
542            "{text}"
543        );
544
545        let empty = NodeError::Connect {
546            attempts: Vec::new(),
547        };
548        assert!(empty.to_string().contains("no endpoints"));
549    }
550
551    #[test]
552    fn conversions_wrap_rather_than_flatten() {
553        let wire: NodeError = WireError::MissingCrc.into();
554        assert_eq!(wire.kind_name(), "wire");
555        let id: NodeError = astrs_wire::DataId::new("").unwrap_err().into();
556        assert_eq!(id.kind_name(), "id");
557        let shm: NodeError = ShmError::Closed {
558            name: "astrs-test".to_owned(),
559        }
560        .into();
561        assert_eq!(shm.kind_name(), "shm");
562        let data: NodeError = DataError::AllocationFailed { bytes: 8 }.into();
563        assert_eq!(data.kind_name(), "data");
564    }
565}