1use std::error::Error as StdError;
4use std::io;
5
6use thiserror::Error;
7
8use crate::msp::{ErrorData, ErrorKind, ErrorObject};
9use crate::spawn::SpawnError;
10
11pub use crate::msp::error::ErrorCode;
12
13#[derive(Clone, Debug, Error, PartialEq)]
15#[error("MSP error {code}: {message}")]
16pub struct MspError {
17 code: i64,
18 message: String,
19 data: Box<ErrorData>,
20}
21
22impl MspError {
23 #[must_use]
25 pub const fn code(&self) -> i64 {
26 self.code
27 }
28
29 #[must_use]
31 pub fn message(&self) -> &str {
32 &self.message
33 }
34
35 #[must_use]
37 pub const fn kind(&self) -> ErrorKind {
38 self.data.kind
39 }
40
41 #[must_use]
43 pub const fn data(&self) -> &ErrorData {
44 &self.data
45 }
46
47 #[must_use]
49 pub fn matches(&self, expected: ErrorCode) -> bool {
50 self.code == expected.code()
51 && (self.kind() == expected.kind() || expected.override_kinds().contains(&self.kind()))
52 }
53
54 #[must_use]
56 pub fn retryable(&self) -> Option<bool> {
57 self.data.retryable.or_else(|| {
58 ErrorCode::ALL
59 .into_iter()
60 .find(|code| self.matches(*code))
61 .and_then(ErrorCode::retryable)
62 })
63 }
64}
65
66impl TryFrom<ErrorObject> for MspError {
67 type Error = ProtocolError;
68
69 fn try_from(error: ErrorObject) -> Result<Self, Self::Error> {
70 let Some(data) = error.data else {
71 return Err(ProtocolError::MissingErrorData);
72 };
73 Ok(Self {
74 code: error.code,
75 message: error.message,
76 data,
77 })
78 }
79}
80
81#[derive(Debug, Error, Clone, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum ProtocolError {
86 #[error("MSP error response has no data.kind")]
89 MissingErrorData,
90 #[error("{message}")]
100 Other {
101 message: String,
103 line: Option<String>,
106 },
107}
108
109impl ProtocolError {
110 pub(crate) fn new(message: impl Into<String>, line: Option<&str>) -> Self {
111 Self::Other {
112 message: message.into(),
113 line: line.map(str::to_owned),
114 }
115 }
116
117 #[must_use]
119 pub fn message(&self) -> &str {
120 match self {
121 Self::MissingErrorData => "MSP error response has no data.kind",
122 Self::Other { message, .. } => message,
123 }
124 }
125
126 #[must_use]
128 pub fn line(&self) -> Option<&str> {
129 match self {
130 Self::MissingErrorData => None,
131 Self::Other { line, .. } => line.as_deref(),
132 }
133 }
134}
135
136#[derive(Debug, Error)]
138#[non_exhaustive]
139pub enum MuseError {
140 #[error("client is closed")]
142 ClientClosed,
143 #[error("transport ended before the server answered")]
146 TransportEnded,
147 #[error("session {0} was discarded after an ephemeral transport ended")]
150 SessionDiscarded(String),
151 #[error("command {command_id} was discarded locally")]
154 Discarded {
155 command_id: String,
157 },
158 #[error("transport failed: {0}")]
160 Transport(#[from] io::Error),
161 #[error(transparent)]
163 Spawn(#[from] SpawnError),
164 #[error(transparent)]
166 Msp(#[from] MspError),
167 #[error(transparent)]
170 Protocol(#[from] ProtocolError),
171}
172
173#[derive(Debug, Error, Clone, PartialEq, Eq)]
175#[error("event for session {actual} was routed to session {expected}")]
176pub struct ForeignSessionError {
177 pub expected: String,
179 pub actual: String,
181}
182
183#[derive(Debug, Error)]
185#[non_exhaustive]
186pub enum GapFillError {
187 #[error("view/gap ({after}, {next}) page failed")]
193 PageFailed {
194 after: String,
197 next: String,
200 #[source]
202 source: Box<dyn StdError + Send + Sync>,
203 },
204 #[error("view/gap ({after}, {next}) page stalled at {cursor}")]
207 PageStalled {
208 after: String,
210 next: String,
212 cursor: String,
214 },
215}
216
217#[derive(Debug)]
219#[non_exhaustive]
220pub enum GapPageFailure<'a> {
221 NoPendingGap(&'a ProtocolError),
223 ForeignSession(&'a ForeignSessionError),
225 Msp(&'a MspError),
227 Protocol(&'a ProtocolError),
229 Transport(&'a (dyn StdError + Send + Sync + 'static)),
231}
232
233impl GapFillError {
234 #[must_use]
236 pub const fn is_page_failed(&self) -> bool {
237 matches!(self, Self::PageFailed { .. })
238 }
239
240 #[must_use]
242 pub const fn is_page_stalled(&self) -> bool {
243 matches!(self, Self::PageStalled { .. })
244 }
245
246 #[must_use]
248 pub fn page_failure(&self) -> Option<GapPageFailure<'_>> {
249 let Self::PageFailed { source, .. } = self else {
250 return None;
251 };
252 if let Some(error) = source.downcast_ref::<ProtocolError>() {
253 return Some(match error {
254 ProtocolError::Other { .. } => GapPageFailure::NoPendingGap(error),
255 ProtocolError::MissingErrorData => GapPageFailure::Protocol(error),
256 });
257 }
258 if let Some(error) = source.downcast_ref::<ForeignSessionError>() {
259 return Some(GapPageFailure::ForeignSession(error));
260 }
261 if let Some(error) = source.downcast_ref::<MspError>() {
262 return Some(GapPageFailure::Msp(error));
263 }
264 Some(GapPageFailure::Transport(source.as_ref()))
265 }
266}
267
268#[cfg(test)]
269mod tests {
270 use crate::msp::error::ErrorCode;
271
272 use crate::msp::{ErrorData, ErrorObject};
273
274 use super::{MspError, ProtocolError};
275
276 type TestResult = Result<(), Box<dyn std::error::Error>>;
277
278 #[test]
279 fn typed_msp_errors_are_bound_to_every_generated_registry_pair() -> TestResult {
280 for code in ErrorCode::ALL {
281 for kind in std::iter::once(code.kind()).chain(code.override_kinds().iter().copied()) {
282 let object = ErrorObject {
283 code: code.code(),
284 message: format!("{kind:?}"),
285 data: Some(Box::new(ErrorData::new(kind))),
286 };
287 let error = MspError::try_from(object.clone())?;
288
289 assert_eq!(error.code(), code.code());
290 assert_eq!(error.kind(), kind);
291 assert_eq!(Some(error.data()), object.data.as_deref());
292 assert_eq!(error.retryable(), code.retryable());
293 assert!(error.matches(code));
294 }
295 }
296 Ok(())
297 }
298
299 #[test]
300 fn contradictory_code_and_kind_remain_visible_but_do_not_match() -> TestResult {
301 let code = ErrorCode::ALL[0];
302 let other = ErrorCode::ALL[1];
303 let object = ErrorObject {
304 code: code.code(),
305 message: "contradictory registry pair".to_owned(),
306 data: Some(Box::new(ErrorData::new(other.kind()))),
307 };
308 let error = MspError::try_from(object)?;
309
310 assert_eq!(error.code(), code.code());
311 assert_eq!(error.kind(), other.kind());
312 assert!(!error.matches(code));
313 assert_eq!(error.retryable(), None);
314 Ok(())
315 }
316
317 #[test]
318 fn missing_error_kind_is_a_typed_protocol_failure() {
319 let object = ErrorObject {
320 code: ErrorCode::ALL[0].code(),
321 message: "missing data".to_owned(),
322 data: None,
323 };
324 let error = MspError::try_from(object).expect_err("MSP errors require data.kind");
325
326 assert!(matches!(error, ProtocolError::MissingErrorData));
327 }
328
329 #[test]
330 fn payload_retry_guidance_overrides_the_generated_default() -> TestResult {
331 let Some(code) = ErrorCode::ALL
332 .into_iter()
333 .find(|code| code.retryable() == Some(false))
334 else {
335 return Err("the registry has no non-retryable row".into());
336 };
337 let mut data = ErrorData::new(code.kind());
338 data.retryable = Some(true);
339 let error = MspError::try_from(ErrorObject {
340 code: code.code(),
341 message: "payload override".to_owned(),
342 data: Some(Box::new(data)),
343 })?;
344
345 assert_eq!(error.retryable(), Some(true));
346 Ok(())
347 }
348}