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
151/// Why an instance name cannot reach its instance (RETURNS-46): the service
152/// routes `<parent>.<name>.<method>` by `name`'s segment — a static child
153/// before the dynamic one — and refuses a path whose segments are not
154/// `[a-z][a-z0-9_]*` (plexus-auth-core's `MethodPath`). A name that is a
155/// method of the parent is the instance: the service takes the first segment
156/// after the parent as a child, never as the parent's method.
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
158#[non_exhaustive]
159pub enum NameRefusal {
160 /// `""`: there is no segment.
161 Empty,
162 /// It holds a `.`: the service would read two segments.
163 Dotted,
164 /// It is not a segment of the service's path grammar,
165 /// `[a-z][a-z0-9_]*`: the service refuses the call (`" "`, `"LEFT"`,
166 /// `"acme-co"`, `"acme"`).
167 NotASegment,
168 /// It is a static sibling's segment: the service routes it there.
169 StaticChild,
170}
171
172impl fmt::Display for NameRefusal {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 f.write_str(match self {
175 NameRefusal::Empty => "it is empty",
176 NameRefusal::Dotted => "it contains '.', which the service reads as two segments",
177 NameRefusal::StaticChild => "it is a static child's segment, which the service routes there",
178 NameRefusal::NotASegment => "it is not a route segment ([a-z][a-z0-9_]*), which the service refuses",
179 })
180 }
181}
182
183impl ClientError {
184 /// `true` when the failure came from the transport rather than the peer.
185 pub fn is_transport(&self) -> bool {
186 matches!(self, ClientError::Transport(_))
187 }
188
189 /// `true` when the peer answered with an error frame.
190 pub fn is_remote(&self) -> bool {
191 matches!(self, ClientError::Remote(_))
192 }
193
194 /// The error frame's [`RemoteError`], when the call failed remotely.
195 pub fn remote(&self) -> Option<&RemoteError> {
196 match self {
197 ClientError::Remote(e) => Some(e),
198 _ => None,
199 }
200 }
201}
202
203impl From<TransportError> for ClientError {
204 fn from(e: TransportError) -> Self {
205 ClientError::Transport(e)
206 }
207}
208
209impl From<RemoteError> for ClientError {
210 fn from(e: RemoteError) -> Self {
211 ClientError::Remote(e)
212 }
213}
214
215impl fmt::Display for ClientError {
216 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217 match self {
218 ClientError::Transport(e) => write!(f, "{e}"),
219 // Main's line: the method's own failure reads as the message it
220 // carries ("remote error: no"); any other kind as its line.
221 ClientError::Remote(crate::RemoteError::Execution { message }) => write!(f, "remote error: {message}"),
222 ClientError::Remote(e) => write!(f, "remote error: {e}"),
223 ClientError::Decode {
224 content_type: Some(ct),
225 message,
226 } => write!(f, "decode {ct}: {message}"),
227 ClientError::Decode { message, .. } => write!(f, "decode: {message}"),
228 ClientError::Encode { param, message } => {
229 write!(f, "encode param `{param}`: {message}")
230 }
231 ClientError::InvalidName { name, reason } => {
232 write!(f, "instance name {name:?} refused, nothing sent: {reason}")
233 }
234 }
235 }
236}
237
238impl std::error::Error for ClientError {
239 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
240 match self {
241 ClientError::Transport(e) => Some(e),
242 ClientError::Remote(e) => Some(e),
243 ClientError::Decode { .. } | ClientError::Encode { .. } | ClientError::InvalidName { .. } => None,
244 }
245 }
246}