1use 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
34pub type Result<T, E = NodeError> = core::result::Result<T, E>;
36
37#[derive(Debug, thiserror::Error)]
39#[non_exhaustive]
40pub enum NodeError {
41 #[error("node configuration: {0}")]
43 Config(#[source] NodeConfigError),
44
45 #[error("environment variable {name} is not set (was this node spawned by an AstRS daemon?)")]
47 MissingEnv {
48 name: &'static str,
50 },
51
52 #[error("environment variable {name}={value} is invalid: {reason}")]
54 BadEnv {
55 name: &'static str,
57 value: String,
59 reason: String,
61 },
62
63 #[error("could not reach the daemon: {}", format_attempts(.attempts))]
70 Connect {
71 attempts: Vec<(String, String)>,
73 },
74
75 #[error("handshake with the daemon failed: {0}")]
78 Handshake(String),
79
80 #[error("the daemon refused this node's registration: {0}")]
82 Registration(String),
83
84 #[error("the daemon connection closed")]
86 DaemonGone,
87
88 #[error("transport: {0}")]
90 Transport(#[source] TransportError),
91
92 #[error("wire protocol: {0}")]
94 Wire(#[source] WireError),
95
96 #[error("payload: {0}")]
98 Data(#[source] DataError),
99
100 #[error("payload encoding: {0}")]
102 Ipc(#[source] IpcError),
103
104 #[error("type: {0}")]
107 TypeUrn(#[source] TypeUrnError),
108
109 #[error("shared memory: {0}")]
111 Shm(#[source] ShmError),
112
113 #[error("identifier: {0}")]
115 Id(#[source] IdError),
116
117 #[error("scheduler: {0}")]
119 Scheduler(#[source] SchedulerError),
120
121 #[error("this node has no output named `{output}`")]
123 UnknownOutput {
124 output: DataId,
126 },
127
128 #[error("this node has no input named `{input}`")]
130 UnknownInput {
131 input: DataId,
133 },
134
135 #[error("port `{port}` is declared as `{declared}`, but the handle is typed `{requested}`")]
138 TypeMismatch {
139 port: DataId,
141 declared: String,
143 requested: String,
145 },
146
147 #[error("payload of {len} bytes exceeds the {max}-byte limit")]
149 PayloadTooLarge {
150 len: usize,
152 max: usize,
154 },
155
156 #[error(
162 "{method} blocks, and this is a current-thread tokio runtime; call {alternative} instead"
163 )]
164 BlockingInAsync {
165 method: &'static str,
167 alternative: &'static str,
169 },
170
171 #[error("the dataflow stopped this node")]
176 Stopped,
177
178 #[error("the supervising process {parent_pid} exited; this node is orphaned")]
180 Orphaned {
181 parent_pid: u32,
183 },
184
185 #[error("{operation} timed out after {millis} ms")]
187 Timeout {
188 operation: &'static str,
190 millis: u64,
192 },
193
194 #[error("the daemon request queue is full ({depth} messages)")]
200 Backpressure {
201 depth: usize,
203 },
204
205 #[error("could not start a runtime for this node: {0}")]
207 Runtime(String),
208
209 #[error("{0}")]
211 Pattern(String),
212
213 #[error("test harness: {0}")]
215 Testing(String),
216}
217
218impl NodeError {
219 #[must_use]
232 pub const fn is_shutdown(&self) -> bool {
233 matches!(self, Self::Stopped | Self::Orphaned { .. })
234 }
235
236 #[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 #[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 #[must_use]
283 pub const fn exit_code(&self) -> i32 {
284 if self.is_shutdown() { 0 } else { 1 }
285 }
286
287 #[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 #[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
333fn 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}