rpc_io/error.rs
1//! [`Error`] (the connection) and [`CallError`] (one outgoing request).
2
3use std::{fmt, io};
4
5use jsonx_lib::Kind;
6
7use crate::{error_object::ErrorObject, framing::FrameError};
8
9/// Why the connection, or an operation on it, failed.
10///
11/// # Examples
12///
13/// ```
14/// use rpc_io::{Error, FrameError, Framing, Router};
15///
16/// // A broken header section ends the session: the stream has no reliable
17/// // message boundary left.
18/// let input: &[u8] = b"Content-Length: x\r\n\r\n";
19/// let result = rpc_io::serve(input, std::io::sink(), Framing::ContentLength, Router::new());
20/// assert!(matches!(result, Err(Error::Frame(FrameError::InvalidContentLength))));
21/// ```
22#[derive(Debug)]
23#[non_exhaustive]
24pub enum Error {
25 /// Reading or writing the transport failed. The connection is closed.
26 Io(io::Error),
27 /// The input stream broke its framing in a way that leaves no reliable
28 /// message boundary (see [`FrameError::is_recoverable`]). The connection is
29 /// closed.
30 Frame(FrameError),
31 /// The connection is closed: the endpoint stopped, its input ended, or its
32 /// output failed earlier. Nothing more can be sent.
33 Closed,
34 /// Outgoing `params` must be an array, an object, or `null` (sent as no
35 /// params); this was another kind of value. Nothing was sent.
36 InvalidParams(Kind),
37 /// The request was already answered (the peer cancelled it, or the
38 /// connection answered it for a panicking handler). This reply, or a
39 /// progress report for a request that is over, was not sent.
40 AlreadyAnswered,
41 /// The [`Gate`](crate::Gate) is shut and the messages held behind it
42 /// already reach [`Config::max_held_bytes`](crate::Config). This one was
43 /// not sent or held; the connection is still open.
44 Backlog,
45 /// A value could not be written as JSON (a [`Progress`](crate::Progress)
46 /// number that is not finite; with the `serde` feature, a map whose keys
47 /// are not strings, or a `Serialize` that failed); this says why. Nothing
48 /// was sent.
49 Serialize(String),
50 /// A [`Progress`](crate::Progress) report whose value does not exceed
51 /// the last one sent for its token: MCP requires `progress` to increase
52 /// with every report. Nothing was sent; report a larger value.
53 ProgressNotIncreasing {
54 /// The value last sent.
55 last: f64,
56 /// The value refused.
57 next: f64,
58 },
59}
60
61impl fmt::Display for Error {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 match self {
64 Error::Io(e) => write!(f, "the transport failed: {e}"),
65 Error::Frame(e) => write!(f, "the input lost its framing: {e}"),
66 Error::Closed => f.write_str("the connection is closed"),
67 Error::InvalidParams(kind) => write!(
68 f,
69 "params must be an array, an object, or null, not {} {kind}",
70 if matches!(kind, Kind::Array | Kind::Object) {
71 "an"
72 } else {
73 "a"
74 }
75 ),
76 Error::AlreadyAnswered => f.write_str("the request was already answered"),
77 Error::Backlog => f.write_str(
78 "too much is already held until the opening request succeeds; nothing was sent",
79 ),
80 Error::Serialize(why) => write!(f, "the value is not JSON: {why}"),
81 Error::ProgressNotIncreasing { last, next } => write!(
82 f,
83 "progress must increase with every report: {next} does not exceed {last}; nothing was sent"
84 ),
85 }
86 }
87}
88
89impl std::error::Error for Error {
90 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
91 match self {
92 Error::Io(e) => Some(e),
93 Error::Frame(e) => Some(e),
94 _ => None,
95 }
96 }
97}
98
99impl From<io::Error> for Error {
100 fn from(e: io::Error) -> Self {
101 Error::Io(e)
102 }
103}
104
105impl From<FrameError> for Error {
106 fn from(e: FrameError) -> Self {
107 Error::Frame(e)
108 }
109}
110
111impl From<Error> for ErrorObject {
112 /// An `-32603` internal error saying what failed, so a handler can apply
113 /// `?` to a send through its [`Context`](crate::Context).
114 ///
115 /// An [`Error::Io`] says only that the transport failed: the operating
116 /// system's text (which can name paths and hosts) stays on this side. Log
117 /// the [`Error`] itself for the detail.
118 ///
119 /// # Examples
120 ///
121 /// ```
122 /// use rpc_io::{Error, ErrorCode, ErrorObject};
123 ///
124 /// let e = ErrorObject::from(Error::Closed);
125 /// assert_eq!(e.code(), ErrorCode::INTERNAL_ERROR);
126 /// assert_eq!(e.message(), "the connection is closed");
127 ///
128 /// let io = std::io::Error::other("C:\\secret\\path is locked");
129 /// assert_eq!(ErrorObject::from(Error::Io(io)).message(), "the transport failed");
130 /// ```
131 fn from(error: Error) -> Self {
132 match error {
133 Error::Io(_) => ErrorObject::internal_error("the transport failed"),
134 other => ErrorObject::internal_error(other.to_string()),
135 }
136 }
137}
138
139/// Why an outgoing request produced no result.
140///
141/// Every request ends in exactly one outcome: its result, or one of these.
142///
143/// # Examples
144///
145/// ```
146/// use rpc_io::{CallError, ErrorObject};
147///
148/// let e = CallError::Rejected(ErrorObject::method_not_found("x"));
149/// assert_eq!(e.to_string(), "the peer answered with an error: method not found: `x` (code -32601)");
150/// assert_eq!(CallError::TimedOut.to_string(), "the request timed out");
151/// ```
152#[derive(Clone, Debug, PartialEq, Eq)]
153#[non_exhaustive]
154pub enum CallError {
155 /// The peer answered with this error.
156 Rejected(ErrorObject),
157 /// The peer's answer was not a valid response; this describes how.
158 InvalidResponse(ErrorObject),
159 /// The deadline passed without an answer. The peer was told to cancel.
160 TimedOut,
161 /// The request was cancelled (by [`Call::cancel`](crate::Call::cancel), a
162 /// [`Canceller`](crate::Canceller), or because the gate's opening request
163 /// failed before it was sent).
164 Cancelled,
165 /// More requests were outstanding than [`Config::max_pending`](crate::Config)
166 /// allows and this was the oldest. The peer was told to cancel.
167 Evicted,
168 /// The connection closed before an answer arrived.
169 Closed,
170 /// Waiting here would block the thread that reads the answer: a handler
171 /// cannot wait for a request it sent. The call, consumed by `wait`, is
172 /// cancelled. Use [`Call::try_wait`](crate::Call::try_wait) later, or wait
173 /// on another thread.
174 WouldDeadlock,
175}
176
177impl fmt::Display for CallError {
178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179 match self {
180 CallError::Rejected(e) => write!(f, "the peer answered with an error: {e}"),
181 CallError::InvalidResponse(e) => write!(f, "the peer's answer was invalid: {e}"),
182 CallError::TimedOut => f.write_str("the request timed out"),
183 CallError::Cancelled => f.write_str("the request was cancelled"),
184 CallError::Evicted => {
185 f.write_str("the request was dropped: too many requests were outstanding")
186 }
187 CallError::Closed => f.write_str("the connection closed before an answer arrived"),
188 CallError::WouldDeadlock => {
189 f.write_str("waiting would block the endpoint's own thread, which reads the answer")
190 }
191 }
192 }
193}
194
195impl std::error::Error for CallError {}