Skip to main content

plexus_client/
error.rs

1//! The two error layers a Plexus client sees, kept apart by type.
2//!
3//! The wire has two independent failure modes and conflating them is the
4//! bug this split exists to prevent:
5//!
6//! | Layer | Meaning | Type |
7//! |---|---|---|
8//! | transport | the connection/HTTP call failed; nothing was said about the request | [`TransportError`] |
9//! | remote | the server answered, and the answer is an error frame: the call failed, typed | [`ClientError::Remote`] ([`RemoteError`]) |
10//!
11//! Neither is the activation saying no. That is an `err` *item* — data, the
12//! `Err` half of a `Result<T, E>` item — and it reaches the caller as a
13//! value, never as a `ClientError` (RETURNS-1 decision 8). The one rule for
14//! a receiver: `?` is the call failing; a match on the item is the
15//! activation's answer.
16//!
17//! ```
18//! # use plexus_client::{ClientError, RemoteError};
19//! # fn show(_: u32) {}
20//! # fn missing(_: &str) {}
21//! # fn check(answer: Result<Result<u32, String>, ClientError>) -> Result<(), ClientError> {
22//! match answer? {                       // ? = the call failed
23//!     Ok(n) => show(n),                 // the activation's yes
24//!     Err(why) => missing(&why),        // the activation's no
25//! }
26//! # Ok(()) }
27//! # let failed: Result<Result<u32, String>, ClientError> = Err(ClientError::Remote(RemoteError::Unauthenticated));
28//! # assert!(check(failed).unwrap_err().is_remote());
29//! ```
30
31use std::fmt;
32
33use crate::remote_error::RemoteError;
34
35/// What kind of transport failure occurred.
36#[derive(Debug, Clone, PartialEq, Eq)]
37#[non_exhaustive]
38pub enum TransportErrorKind {
39    /// Could not establish the connection at all.
40    Connect,
41    /// The peer spoke something this transport could not parse (a malformed
42    /// JSON-RPC frame, an SSE frame with no `data:` line that was required,
43    /// a JSON-RPC `error` response to the subscribe call).
44    Protocol,
45    /// A non-success HTTP status.
46    Http { status: u16 },
47    /// The stream ended without a terminal item.
48    Closed,
49    /// Anything the transport wants to report that is none of the above.
50    Other,
51}
52
53/// A failure of the transport itself — the request never got an answer, or
54/// the answer was unintelligible.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct TransportError {
57    pub kind: TransportErrorKind,
58    pub message: String,
59}
60
61impl TransportError {
62    pub fn new(kind: TransportErrorKind, message: impl Into<String>) -> Self {
63        Self {
64            kind,
65            message: message.into(),
66        }
67    }
68    pub fn connect(message: impl Into<String>) -> Self {
69        Self::new(TransportErrorKind::Connect, message)
70    }
71    pub fn protocol(message: impl Into<String>) -> Self {
72        Self::new(TransportErrorKind::Protocol, message)
73    }
74    pub fn http(status: u16, message: impl Into<String>) -> Self {
75        Self::new(TransportErrorKind::Http { status }, message)
76    }
77    pub fn closed(message: impl Into<String>) -> Self {
78        Self::new(TransportErrorKind::Closed, message)
79    }
80    pub fn other(message: impl Into<String>) -> Self {
81        Self::new(TransportErrorKind::Other, message)
82    }
83}
84
85impl fmt::Display for TransportError {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        match self.kind {
88            TransportErrorKind::Connect => write!(f, "transport connect: {}", self.message),
89            TransportErrorKind::Protocol => write!(f, "transport protocol: {}", self.message),
90            TransportErrorKind::Http { status } => {
91                write!(f, "transport http {}: {}", status, self.message)
92            }
93            TransportErrorKind::Closed => write!(f, "transport closed: {}", self.message),
94            TransportErrorKind::Other => write!(f, "transport: {}", self.message),
95        }
96    }
97}
98
99impl std::error::Error for TransportError {}
100
101/// Everything that can go wrong on a typed client call — the call failing,
102/// never the activation saying no (that is an `err` item).
103#[derive(Debug, Clone, PartialEq)]
104#[non_exhaustive]
105pub enum ClientError {
106    /// The transport failed. See [`TransportError`].
107    Transport(TransportError),
108
109    /// The server answered with an error frame: the call failed — no such
110    /// activation or method, bad params, not authenticated, not allowed, or
111    /// the method blew up. Typed and exhaustive; match on it.
112    ///
113    /// The frame's `recoverable` flag is not carried (RETURNS-1 decision
114    /// 9): an error frame ends the call either way.
115    Remote(RemoteError),
116
117    /// The server's answer does not fit the method's declared contract: a
118    /// `data` item whose `content` does not deserialize into the method's
119    /// item type, a `progress` item that does not deserialize into its
120    /// progress type, or a one-item method that sent no item or more than
121    /// one. A contract break between client and server (a renamed field, a
122    /// version skew); it terminates the stream.
123    Decode {
124        /// The item's `content_type` (`"tickets.get"`), when the transport
125        /// carried one; the called method's, when the break is in the count.
126        content_type: Option<String>,
127        message: String,
128    },
129
130    /// An argument could not be serialized into the call's params object,
131    /// so nothing was sent. A generated client reports this rather than
132    /// panicking — a panic in a wasm32 consumer is an unrecoverable trap.
133    Encode {
134        /// The parameter that failed.
135        param: &'static str,
136        message: String,
137    },
138
139    /// RETURNS-46: a dynamic child's instance name the service would route
140    /// elsewhere than to that instance — so nothing was sent. Every call
141    /// through the instance's client, and through any client below it, is
142    /// this, at once.
143    InvalidName {
144        /// The name the accessor was given.
145        name: String,
146        /// Why it cannot name an instance.
147        reason: NameRefusal,
148    },
149
150    /// NEST-14: an untyped client made typed (`Untyped::typed`) against a
151    /// node that does not serve the typed client's interface — the methods
152    /// it serves under another shape, or not at all. Nothing was called.
153    ShapeMismatch {
154        /// The node's dotted path.
155        path: String,
156        /// The typed client's interface hash.
157        wanted: String,
158        /// The node's.
159        got: String,
160        /// The client's methods the node serves otherwise, or not at all.
161        methods: Vec<String>,
162    },
163}
164
165/// Why an instance name cannot reach its instance (RETURNS-46): the service
166/// routes `<parent>.<name>.<method>` by `name`'s segment — a static child
167/// before the dynamic one — and refuses a path whose segments are not
168/// `[a-z][a-z0-9_]*` (plexus-auth-core's `MethodPath`). A name that is a
169/// method of the parent is the instance: the service takes the first segment
170/// after the parent as a child, never as the parent's method.
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
172#[non_exhaustive]
173pub enum NameRefusal {
174    /// `""`: there is no segment.
175    Empty,
176    /// It holds a `.`: the service would read two segments.
177    Dotted,
178    /// It is not a segment of the service's path grammar,
179    /// `[a-z][a-z0-9_]*`: the service refuses the call (`" "`, `"LEFT"`,
180    /// `"acme-co"`, `"acme"`).
181    NotASegment,
182    /// It is a static sibling's segment: the service routes it there.
183    StaticChild,
184}
185
186impl fmt::Display for NameRefusal {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        f.write_str(match self {
189            NameRefusal::Empty => "it is empty",
190            NameRefusal::Dotted => "it contains '.', which the service reads as two segments",
191            NameRefusal::StaticChild => "it is a static child's segment, which the service routes there",
192            NameRefusal::NotASegment => "it is not a route segment ([a-z][a-z0-9_]*), which the service refuses",
193        })
194    }
195}
196
197impl ClientError {
198    /// `true` when the failure came from the transport rather than the peer.
199    pub fn is_transport(&self) -> bool {
200        matches!(self, ClientError::Transport(_))
201    }
202
203    /// `true` when the peer answered with an error frame.
204    pub fn is_remote(&self) -> bool {
205        matches!(self, ClientError::Remote(_))
206    }
207
208    /// The error frame's [`RemoteError`], when the call failed remotely.
209    pub fn remote(&self) -> Option<&RemoteError> {
210        match self {
211            ClientError::Remote(e) => Some(e),
212            _ => None,
213        }
214    }
215}
216
217impl From<TransportError> for ClientError {
218    fn from(e: TransportError) -> Self {
219        ClientError::Transport(e)
220    }
221}
222
223impl From<RemoteError> for ClientError {
224    fn from(e: RemoteError) -> Self {
225        ClientError::Remote(e)
226    }
227}
228
229impl fmt::Display for ClientError {
230    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231        match self {
232            ClientError::Transport(e) => write!(f, "{e}"),
233            // Main's line: the method's own failure reads as the message it
234            // carries ("remote error: no"); any other kind as its line.
235            ClientError::Remote(crate::RemoteError::Execution { message }) => write!(f, "remote error: {message}"),
236            ClientError::Remote(e) => write!(f, "remote error: {e}"),
237            ClientError::Decode {
238                content_type: Some(ct),
239                message,
240            } => write!(f, "decode {ct}: {message}"),
241            ClientError::Decode { message, .. } => write!(f, "decode: {message}"),
242            ClientError::Encode { param, message } => {
243                write!(f, "encode param `{param}`: {message}")
244            }
245            ClientError::InvalidName { name, reason } => {
246                write!(f, "instance name {name:?} refused, nothing sent: {reason}")
247            }
248            ClientError::ShapeMismatch { path, wanted, got, methods } => write!(
249                f,
250                "`{path}` does not serve the interface wanted ({wanted}, it serves {got}): {}",
251                methods.join(", ")
252            ),
253        }
254    }
255}
256
257impl std::error::Error for ClientError {
258    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
259        match self {
260            ClientError::Transport(e) => Some(e),
261            ClientError::Remote(e) => Some(e),
262            ClientError::Decode { .. }
263            | ClientError::Encode { .. }
264            | ClientError::InvalidName { .. }
265            | ClientError::ShapeMismatch { .. } => None,
266        }
267    }
268}