1use isothrum_runner::store::OperationId;
4use isothrum_runner::{ErrorCode, ErrorReport};
5
6#[derive(Debug, thiserror::Error)]
8#[non_exhaustive]
9pub enum ClientError {
10 #[error("no runner service for this home: {0}")]
12 Unavailable(String),
13 #[error("protocol: {0}")]
15 Protocol(String),
16 #[error("{0}")]
19 Refused(Box<ErrorReport>),
20 #[error("{0}")]
22 Operation(Box<ErrorReport>),
23 #[error("the runner service (Isothrum {version}, pid {pid}) has {} operation(s) queued or running: it was left running", operations.len())]
26 Busy {
27 version: String,
29 pid: u32,
31 operations: Vec<OperationId>,
33 },
34 #[error("the runner service is Isothrum {service}, this client {client}")]
36 Version {
37 client: String,
39 service: String,
41 },
42 #[error(transparent)]
44 Io(#[from] std::io::Error),
45 #[error("the runner service's connection ended before it answered")]
48 Unanswered,
49}
50
51impl ClientError {
52 #[must_use]
58 pub fn is_broken(&self) -> bool {
59 matches!(
60 self,
61 ClientError::Io(_) | ClientError::Protocol(_) | ClientError::Unavailable(_) | ClientError::Unanswered
62 )
63 }
64
65 #[must_use]
67 pub fn code(&self) -> ErrorCode {
68 match self {
69 ClientError::Refused(report) | ClientError::Operation(report) => report.code,
70 ClientError::Busy { .. } => ErrorCode::Locked,
71 ClientError::Version { .. } => ErrorCode::Unsupported,
72 ClientError::Unavailable(_) | ClientError::Protocol(_) | ClientError::Io(_) | ClientError::Unanswered => ErrorCode::Io,
73 }
74 }
75
76 #[must_use]
78 pub fn report(&self) -> Option<&ErrorReport> {
79 match self {
80 ClientError::Refused(report) | ClientError::Operation(report) => Some(report),
81 _ => None,
82 }
83 }
84
85 pub(crate) fn closed() -> ClientError {
87 ClientError::Unavailable("the service closed the connection".to_owned())
88 }
89}
90
91#[cfg(test)]
92mod tests {
93 use super::*;
94
95 #[test]
96 fn each_failure_has_the_code_an_error_event_would() {
97 let refused = ClientError::Refused(Box::new(ErrorReport::new(ErrorCode::NotRunning, "x")));
98 assert_eq!(refused.code(), ErrorCode::NotRunning);
99 let busy = ClientError::Busy {
100 version: "2.1.7".into(),
101 pid: 1,
102 operations: Vec::new(),
103 };
104 assert_eq!(busy.code(), ErrorCode::Locked);
105 let version = ClientError::Version {
106 client: "3.0.0".into(),
107 service: "2.1.7".into(),
108 };
109 assert_eq!(version.code(), ErrorCode::Unsupported);
110 for io in [
111 ClientError::Protocol("x".into()),
112 ClientError::Unavailable("x".into()),
113 ClientError::closed(),
114 ClientError::Unanswered,
115 ] {
116 assert_eq!(io.code(), ErrorCode::Io, "{io}");
117 }
118 assert!(matches!(ClientError::closed(), ClientError::Unavailable(m) if m == "the service closed the connection"));
119 }
120}