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    /// A start that required its permission profile could not prove the host
152    /// committed it. The session is open on the host, but no handle to it is
153    /// returned; resume it by `session_id` or start again.
154    #[error(
155        "required permission profile {requested:?} was not applied: the committed selection is {} (session {session_id})",
156        served.as_deref().map_or_else(|| "unknown".to_owned(), |served| format!("{served:?}"))
157    )]
158    PermissionProfileNotApplied {
159        /// The profile id the caller required.
160        requested: String,
161        /// The committed profile id the host reported, or `None` when it
162        /// reported none.
163        served: Option<String>,
164        /// The session the start opened.
165        session_id: String,
166    },
167    /// The command was discarded locally, because the last handle that could
168    /// await it was dropped.
169    #[error("command {command_id} was discarded locally")]
170    Discarded {
171        /// The discarded command's id.
172        command_id: String,
173    },
174    /// Reading from or writing to the transport failed.
175    #[error("transport failed: {0}")]
176    Transport(#[from] io::Error),
177    /// The host process could not be started.
178    #[error(transparent)]
179    Spawn(#[from] SpawnError),
180    /// The server refused the request with a typed MSP error.
181    #[error(transparent)]
182    Msp(#[from] MspError),
183    /// A failure the client raised itself rather than a typed MSP error from
184    /// the server. See [`ProtocolError`].
185    #[error(transparent)]
186    Protocol(#[from] ProtocolError),
187}
188
189/// A page or live event named a different session than its consumer.
190#[derive(Debug, Error, Clone, PartialEq, Eq)]
191#[error("event for session {actual} was routed to session {expected}")]
192pub struct ForeignSessionError {
193    /// The session the consumer serves.
194    pub expected: String,
195    /// The session the page or event named.
196    pub actual: String,
197}
198
199/// One delivery-gap recovery attempt failed without making the fold current.
200#[derive(Debug, Error)]
201#[non_exhaustive]
202pub enum GapFillError {
203    /// A gap, event or page could not be used: [`GapFill`](crate::gap::GapFill)
204    /// returns this when one names another session, or when a page arrives
205    /// with no gap pending. Code that sends the page requests can also wrap an
206    /// [`MspError`] or a transport error in it. [`GapFillError::page_failure`]
207    /// names the cause.
208    #[error("view/gap ({after}, {next}) page failed")]
209    PageFailed {
210        /// The refused gap's `after` cursor, else the pending gap's, or empty
211        /// when no gap was pending.
212        after: String,
213        /// The refused gap's `next` cursor, else the pending gap's, or empty
214        /// when no gap was pending.
215        next: String,
216        /// The underlying failure.
217        #[source]
218        source: Box<dyn StdError + Send + Sync>,
219    },
220    /// A page made no progress: it said more pages follow but held no events,
221    /// or it returned the cursor it was requested from.
222    #[error("view/gap ({after}, {next}) page stalled at {cursor}")]
223    PageStalled {
224        /// The gap's `after` cursor.
225        after: String,
226        /// The gap's `next` cursor.
227        next: String,
228        /// The cursor the stalled page was requested from.
229        cursor: String,
230    },
231}
232
233/// The typed cause behind a failed gap-page operation.
234#[derive(Debug)]
235#[non_exhaustive]
236pub enum GapPageFailure<'a> {
237    /// A page arrived without a gap waiting for it.
238    NoPendingGap(&'a ProtocolError),
239    /// A page or event named a different session.
240    ForeignSession(&'a ForeignSessionError),
241    /// The server refused the page request with a typed MSP error.
242    Msp(&'a MspError),
243    /// The page response violated the MSP protocol.
244    Protocol(&'a ProtocolError),
245    /// The page request failed outside local gap validation.
246    Transport(&'a (dyn StdError + Send + Sync + 'static)),
247}
248
249impl GapFillError {
250    /// Whether this is [`Self::PageFailed`].
251    #[must_use]
252    pub const fn is_page_failed(&self) -> bool {
253        matches!(self, Self::PageFailed { .. })
254    }
255
256    /// Whether this is [`Self::PageStalled`].
257    #[must_use]
258    pub const fn is_page_stalled(&self) -> bool {
259        matches!(self, Self::PageStalled { .. })
260    }
261
262    /// Returns the typed cause of [`Self::PageFailed`].
263    #[must_use]
264    pub fn page_failure(&self) -> Option<GapPageFailure<'_>> {
265        let Self::PageFailed { source, .. } = self else {
266            return None;
267        };
268        if let Some(error) = source.downcast_ref::<ProtocolError>() {
269            return Some(match error {
270                ProtocolError::Other { .. } => GapPageFailure::NoPendingGap(error),
271                ProtocolError::MissingErrorData => GapPageFailure::Protocol(error),
272            });
273        }
274        if let Some(error) = source.downcast_ref::<ForeignSessionError>() {
275            return Some(GapPageFailure::ForeignSession(error));
276        }
277        if let Some(error) = source.downcast_ref::<MspError>() {
278            return Some(GapPageFailure::Msp(error));
279        }
280        Some(GapPageFailure::Transport(source.as_ref()))
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use crate::msp::error::ErrorCode;
287
288    use crate::msp::{ErrorData, ErrorObject};
289
290    use super::{MspError, ProtocolError};
291
292    type TestResult = Result<(), Box<dyn std::error::Error>>;
293
294    #[test]
295    fn typed_msp_errors_are_bound_to_every_generated_registry_pair() -> TestResult {
296        for code in ErrorCode::ALL {
297            for kind in std::iter::once(code.kind()).chain(code.override_kinds().iter().copied()) {
298                let object = ErrorObject {
299                    code: code.code(),
300                    message: format!("{kind:?}"),
301                    data: Some(Box::new(ErrorData::new(kind))),
302                };
303                let error = MspError::try_from(object.clone())?;
304
305                assert_eq!(error.code(), code.code());
306                assert_eq!(error.kind(), kind);
307                assert_eq!(Some(error.data()), object.data.as_deref());
308                assert_eq!(error.retryable(), code.retryable());
309                assert!(error.matches(code));
310            }
311        }
312        Ok(())
313    }
314
315    #[test]
316    fn contradictory_code_and_kind_remain_visible_but_do_not_match() -> TestResult {
317        let code = ErrorCode::ALL[0];
318        let other = ErrorCode::ALL[1];
319        let object = ErrorObject {
320            code: code.code(),
321            message: "contradictory registry pair".to_owned(),
322            data: Some(Box::new(ErrorData::new(other.kind()))),
323        };
324        let error = MspError::try_from(object)?;
325
326        assert_eq!(error.code(), code.code());
327        assert_eq!(error.kind(), other.kind());
328        assert!(!error.matches(code));
329        assert_eq!(error.retryable(), None);
330        Ok(())
331    }
332
333    #[test]
334    fn missing_error_kind_is_a_typed_protocol_failure() {
335        let object = ErrorObject {
336            code: ErrorCode::ALL[0].code(),
337            message: "missing data".to_owned(),
338            data: None,
339        };
340        let error = MspError::try_from(object).expect_err("MSP errors require data.kind");
341
342        assert!(matches!(error, ProtocolError::MissingErrorData));
343    }
344
345    #[test]
346    fn payload_retry_guidance_overrides_the_generated_default() -> TestResult {
347        let Some(code) = ErrorCode::ALL
348            .into_iter()
349            .find(|code| code.retryable() == Some(false))
350        else {
351            return Err("the registry has no non-retryable row".into());
352        };
353        let mut data = ErrorData::new(code.kind());
354        data.retryable = Some(true);
355        let error = MspError::try_from(ErrorObject {
356            code: code.code(),
357            message: "payload override".to_owned(),
358            data: Some(Box::new(data)),
359        })?;
360
361        assert_eq!(error.retryable(), Some(true));
362        Ok(())
363    }
364}