Skip to main content

muse_code_sdk/
errors.rs

1//! Typed SDK errors.
2
3use 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/// A server-authored MSP error whose branch key is `error.data.kind`.
14#[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    /// The JSON-RPC error code.
24    #[must_use]
25    pub const fn code(&self) -> i64 {
26        self.code
27    }
28
29    /// The server's human-readable error message.
30    #[must_use]
31    pub fn message(&self) -> &str {
32        &self.message
33    }
34
35    /// The branch key, `error.data.kind`.
36    #[must_use]
37    pub const fn kind(&self) -> ErrorKind {
38        self.data.kind
39    }
40
41    /// The whole `error.data` payload.
42    #[must_use]
43    pub const fn data(&self) -> &ErrorData {
44        &self.data
45    }
46
47    /// Whether this error is one of a registry row's admitted kind/code pairs.
48    #[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    /// Payload guidance wins; otherwise use a matching generated registry row.
55    #[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/// A failure the client raises itself. It is never a typed MSP error from the
82/// server, though its message can quote one.
83#[derive(Debug, Error, Clone, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum ProtocolError {
86    /// An MSP error response carried no `error.data`, so it has no kind to
87    /// branch on.
88    #[error("MSP error response has no data.kind")]
89    MissingErrorData,
90    /// A failure the client detected or raised itself, for example: a frame
91    /// that broke MSP framing or request correlation; arguments it refused (a
92    /// pending turn from another session); its own event delivery failing (a
93    /// notification backlog overflow); or, as a turn's failure, an approval
94    /// answer that could not be sent, that the server refused with an
95    /// unexpected error, or that named a choice the server did not offer. The
96    /// message says what went wrong. A later release may give one of these
97    /// cases its own variant, so match `Other` only as a fallback, never to
98    /// detect a specific case.
99    #[error("{message}")]
100    Other {
101        /// What went wrong.
102        message: String,
103        /// The offending NDJSON line, when the failure came from a complete
104        /// frame.
105        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    /// Human-readable protocol failure detail.
118    #[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    /// The offending NDJSON line, when the failure came from a complete frame.
127    #[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/// A typed failure returned by the public client and session facade.
137#[derive(Debug, Error)]
138#[non_exhaustive]
139pub enum MuseError {
140    /// The client was closed, so the call could not complete.
141    #[error("client is closed")]
142    ClientClosed,
143    /// The transport ended before the server answered, or had already ended
144    /// when the call was made.
145    #[error("transport ended before the server answered")]
146    TransportEnded,
147    /// The session with this id was discarded: its transport ended on a client
148    /// that is not durable, so nothing survives to resume.
149    #[error("session {0} was discarded after an ephemeral transport ended")]
150    SessionDiscarded(String),
151    /// The command was discarded locally, because the last handle that could
152    /// await it was dropped.
153    #[error("command {command_id} was discarded locally")]
154    Discarded {
155        /// The discarded command's id.
156        command_id: String,
157    },
158    /// Reading from or writing to the transport failed.
159    #[error("transport failed: {0}")]
160    Transport(#[from] io::Error),
161    /// The host process could not be started.
162    #[error(transparent)]
163    Spawn(#[from] SpawnError),
164    /// The server refused the request with a typed MSP error.
165    #[error(transparent)]
166    Msp(#[from] MspError),
167    /// A failure the client raised itself rather than a typed MSP error from
168    /// the server. See [`ProtocolError`].
169    #[error(transparent)]
170    Protocol(#[from] ProtocolError),
171}
172
173/// A page or live event named a different session than its consumer.
174#[derive(Debug, Error, Clone, PartialEq, Eq)]
175#[error("event for session {actual} was routed to session {expected}")]
176pub struct ForeignSessionError {
177    /// The session the consumer serves.
178    pub expected: String,
179    /// The session the page or event named.
180    pub actual: String,
181}
182
183/// One delivery-gap recovery attempt failed without making the fold current.
184#[derive(Debug, Error)]
185#[non_exhaustive]
186pub enum GapFillError {
187    /// A gap, event or page could not be used: [`GapFill`](crate::gap::GapFill)
188    /// returns this when one names another session, or when a page arrives
189    /// with no gap pending. Code that sends the page requests can also wrap an
190    /// [`MspError`] or a transport error in it. [`GapFillError::page_failure`]
191    /// names the cause.
192    #[error("view/gap ({after}, {next}) page failed")]
193    PageFailed {
194        /// The refused gap's `after` cursor, else the pending gap's, or empty
195        /// when no gap was pending.
196        after: String,
197        /// The refused gap's `next` cursor, else the pending gap's, or empty
198        /// when no gap was pending.
199        next: String,
200        /// The underlying failure.
201        #[source]
202        source: Box<dyn StdError + Send + Sync>,
203    },
204    /// A page made no progress: it said more pages follow but held no events,
205    /// or it returned the cursor it was requested from.
206    #[error("view/gap ({after}, {next}) page stalled at {cursor}")]
207    PageStalled {
208        /// The gap's `after` cursor.
209        after: String,
210        /// The gap's `next` cursor.
211        next: String,
212        /// The cursor the stalled page was requested from.
213        cursor: String,
214    },
215}
216
217/// The typed cause behind a failed gap-page operation.
218#[derive(Debug)]
219#[non_exhaustive]
220pub enum GapPageFailure<'a> {
221    /// A page arrived without a gap waiting for it.
222    NoPendingGap(&'a ProtocolError),
223    /// A page or event named a different session.
224    ForeignSession(&'a ForeignSessionError),
225    /// The server refused the page request with a typed MSP error.
226    Msp(&'a MspError),
227    /// The page response violated the MSP protocol.
228    Protocol(&'a ProtocolError),
229    /// The page request failed outside local gap validation.
230    Transport(&'a (dyn StdError + Send + Sync + 'static)),
231}
232
233impl GapFillError {
234    /// Whether this is [`Self::PageFailed`].
235    #[must_use]
236    pub const fn is_page_failed(&self) -> bool {
237        matches!(self, Self::PageFailed { .. })
238    }
239
240    /// Whether this is [`Self::PageStalled`].
241    #[must_use]
242    pub const fn is_page_stalled(&self) -> bool {
243        matches!(self, Self::PageStalled { .. })
244    }
245
246    /// Returns the typed cause of [`Self::PageFailed`].
247    #[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}