Skip to main content

weida_core/
error.rs

1//! The single error type of the framework.
2//!
3//! Hand-written `Display`/`Error` impls: the project's dependency discipline
4//! (master doc §72) does not admit `thiserror` for one enum.
5
6use std::fmt;
7
8/// Convenience alias used throughout the framework.
9pub type Result<T> = std::result::Result<T, Error>;
10
11/// Everything that can go wrong in a weida operation.
12///
13/// The variants are deliberately outcome-shaped rather than cause-shaped: an
14/// application must distinguish `ConnectionLost` (definitely not delivered)
15/// from `Indeterminate` (may or may not have been delivered) because the two
16/// permit different retry decisions. See `docs/FAILURE_MODEL.md`.
17#[derive(Debug)]
18pub enum Error {
19    /// The runtime could not be created or used (e.g. no ambient reactor).
20    Runtime(String),
21    /// A `weida://` URL could not be parsed.
22    InvalidAddress(String),
23    /// An endpoint path violated the addressing rules.
24    InvalidEndpointPath,
25    /// A fingerprint's text form was not `sha256:` plus 64 hex digits.
26    InvalidFingerprint(String),
27    /// An endpoint path is already registered on this listener.
28    AlreadyRegistered,
29    /// The endpoint has no usable peer connection.
30    NotConnected,
31    /// The connection was lost before the local transfer reached FIN; the
32    /// payload was definitely not delivered. The [`LossCause`] says why,
33    /// which is what an application deciding whether to redial needs.
34    ConnectionLost(LossCause),
35    /// Version/capability negotiation failed.
36    Negotiation(String),
37    /// The peer violated the wire protocol.
38    Protocol(String),
39    /// The peer refused the transfer (`STOP_SENDING(REJECTED)` or
40    /// `ERROR{REJECTED}`).
41    Rejected,
42    /// The peer has no endpoint registered under the requested path.
43    UnknownEndpoint,
44    /// The peer does not support a requested protocol feature.
45    Unsupported,
46    /// A stream toward the peer was needed and the peer had parked no
47    /// connection for one. Only a local socket transport can produce this:
48    /// an accepted socket cannot be dialled back, so fan-out rides the
49    /// connections a subscriber parks
50    /// ([decisions/0012](../../../docs/decisions/0012-local-connection-grouping.md)
51    /// §4.4). A publisher treats it as a drop of that copy, not as a failure
52    /// of the subscription.
53    NoParkedConnection,
54    /// The peer accepted the request but never opened a reply stream.
55    NoReply,
56    /// The transfer was canceled, locally or by the peer.
57    Canceled,
58    /// The transfer's deadline passed before the peer acknowledged every
59    /// byte, so this side reset it with `CANCELED`
60    /// ([decisions/0034](../../../docs/decisions/0034-late-is-lost.md) §4.3).
61    /// **Not** a definite failure: the peer may have read every byte before
62    /// the reset landed.
63    Expired,
64    /// The connection was lost after the local FIN while awaiting an ACK or a
65    /// reply: the outcome is genuinely unknown (master doc §22).
66    Indeterminate,
67    /// A local or negotiated resource limit was reached.
68    LimitExceeded,
69    /// The connection carries no datagrams: one side's profile did not
70    /// enable flows, so capability code `1` was not agreed
71    /// ([decisions/0034](../../../docs/decisions/0034-late-is-lost.md) §4.5).
72    /// weida never substitutes a stream, which would deliver the unit late.
73    DatagramsUnavailable,
74    /// A datagram payload exceeds the largest datagram this connection
75    /// carries right now, `max` bytes after the flow id's prefix.
76    TooLarge {
77        /// The largest payload the connection carries.
78        max: usize,
79    },
80    /// TLS material could not be loaded or configured, or the handshake
81    /// failed for a reason other than an untrusted peer.
82    Tls(String),
83    /// The peer proved possession of a key whose fingerprint is neither
84    /// pinned nor certified by a configured anchor. Carries what the peer
85    /// presented, so an operator can pin it after checking it out of band.
86    Untrusted(crate::identity::Fingerprint),
87    /// Underlying I/O failure.
88    Io(std::io::Error),
89    /// Transport-level failure that is not one of the modelled outcomes.
90    Transport(String),
91}
92
93/// Why a connection is gone.
94///
95/// The *outcome* is the same whichever it is — nothing that was in flight
96/// completed, which is what [`Error::ConnectionLost`] promises — so this is
97/// not a second outcome vocabulary. It exists because the next action differs:
98/// an idle timeout invites a redial, a peer that closed deliberately may not
99/// want one yet, and a local close means the application already decided.
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub enum LossCause {
102    /// No traffic for the idle period, on whichever side's timeout was
103    /// shorter. Nothing is wrong with either peer.
104    IdleTimeout,
105    /// The peer closed the connection deliberately, with a code this side
106    /// does not map to a more specific outcome — a shutdown, typically.
107    PeerClosed,
108    /// The peer closed with `RESTARTING`: its server is being replaced, and a
109    /// successor serves, or is about to serve, the same address. A redial is
110    /// due at once.
111    PeerRestarting,
112    /// This side closed it: `Runtime::shutdown`, or a dropped runtime.
113    LocallyClosed,
114    /// A stateless reset: the peer has forgotten the connection, usually
115    /// because it restarted.
116    Reset,
117    /// A QUIC transport error ended the connection. Either peer may be at
118    /// fault, and a redial is unlikely to behave differently.
119    TransportError,
120}
121
122impl fmt::Display for LossCause {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        f.write_str(match self {
125            LossCause::IdleTimeout => "idle timeout",
126            LossCause::PeerClosed => "closed by the peer",
127            LossCause::PeerRestarting => "the peer is restarting",
128            LossCause::LocallyClosed => "closed locally",
129            LossCause::Reset => "stateless reset",
130            LossCause::TransportError => "transport error",
131        })
132    }
133}
134
135impl fmt::Display for Error {
136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137        match self {
138            Error::Runtime(m) => write!(f, "runtime error: {m}"),
139            Error::InvalidAddress(m) => write!(f, "invalid address: {m}"),
140            Error::InvalidEndpointPath => f.write_str(
141                "invalid endpoint path: must start with '/', be 1..=512 bytes and contain no control bytes",
142            ),
143            Error::InvalidFingerprint(m) => {
144                write!(f, "invalid fingerprint: expected sha256:<64 hex digits>, got {m:?}")
145            }
146            Error::AlreadyRegistered => f.write_str("endpoint path already registered"),
147            Error::NotConnected => f.write_str("endpoint is not connected to any peer"),
148            Error::ConnectionLost(cause) => {
149                write!(f, "connection lost before the transfer completed: {cause}")
150            }
151            Error::Negotiation(m) => write!(f, "negotiation failed: {m}"),
152            Error::Protocol(m) => write!(f, "protocol violation: {m}"),
153            Error::Rejected => f.write_str("peer rejected the transfer"),
154            Error::UnknownEndpoint => f.write_str("peer has no such endpoint"),
155            Error::Unsupported => f.write_str("peer does not support the requested feature"),
156            Error::NoParkedConnection => {
157                f.write_str("peer has no parked connection for a stream toward it")
158            }
159            Error::NoReply => f.write_str("peer accepted the request but sent no reply"),
160            Error::Canceled => f.write_str("transfer canceled"),
161            Error::Expired => {
162                f.write_str("the transfer expired before the peer acknowledged it")
163            }
164            Error::Indeterminate => {
165                f.write_str("outcome indeterminate: the transfer may or may not have been accepted")
166            }
167            Error::LimitExceeded => f.write_str("resource limit exceeded"),
168            Error::DatagramsUnavailable => {
169                f.write_str("datagrams are not available on this connection")
170            }
171            Error::TooLarge { max } => write!(
172                f,
173                "payload exceeds the largest datagram this connection carries ({max} bytes)"
174            ),
175            Error::Tls(m) => write!(f, "tls error: {m}"),
176            Error::Untrusted(fp) => write!(f, "peer identity {fp} is not trusted"),
177            Error::Io(e) => write!(f, "io error: {e}"),
178            Error::Transport(m) => write!(f, "transport error: {m}"),
179        }
180    }
181}
182
183impl std::error::Error for Error {
184    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
185        match self {
186            Error::Io(e) => Some(e),
187            _ => None,
188        }
189    }
190}
191
192/// An `io::Error` that carries an [`Error`] (built by the reverse conversion
193/// below, which is how a stream reports weida's outcome through `AsyncRead`
194/// and `AsyncWrite`) gives that error back; any other is [`Error::Io`].
195impl From<std::io::Error> for Error {
196    fn from(e: std::io::Error) -> Self {
197        if e.get_ref().is_some_and(|inner| inner.is::<Error>()) {
198            let inner = e.into_inner().expect("checked above");
199            return *inner.downcast::<Error>().expect("checked above");
200        }
201        Error::Io(e)
202    }
203}
204
205/// Carries the error inside an `io::Error`, so a reader of the I/O traits
206/// still learns weida's outcome with `Error::from`. The kind is the closest
207/// I/O reading of the outcome; [`Error::Io`] gives its own error back.
208impl From<Error> for std::io::Error {
209    fn from(e: Error) -> Self {
210        use std::io::ErrorKind;
211        let kind = match e {
212            Error::Io(io) => return io,
213            Error::Expired => ErrorKind::TimedOut,
214            Error::ConnectionLost(_) | Error::Indeterminate => ErrorKind::NotConnected,
215            Error::Rejected
216            | Error::Canceled
217            | Error::UnknownEndpoint
218            | Error::NoReply
219            | Error::LimitExceeded => ErrorKind::ConnectionReset,
220            _ => ErrorKind::Other,
221        };
222        std::io::Error::new(kind, e)
223    }
224}
225
226impl Error {
227    /// True if the error proves the transfer had no effect at the peer.
228    ///
229    /// `Indeterminate` is deliberately *not* in this set: modelling it apart
230    /// from definite failure is the point of master doc §22. Neither is
231    /// `NoReply` — the request was accepted and may well have had an effect;
232    /// only the answer is missing.
233    pub fn is_definite_failure(&self) -> bool {
234        matches!(
235            self,
236            Error::ConnectionLost(_)
237                | Error::Rejected
238                | Error::UnknownEndpoint
239                | Error::Unsupported
240                | Error::NoParkedConnection
241                | Error::Canceled
242                | Error::NotConnected
243                | Error::LimitExceeded
244                | Error::DatagramsUnavailable
245                | Error::TooLarge { .. }
246                | Error::Untrusted(_)
247        )
248    }
249}
250
251/// Wire codes carried in an ERROR frame (`docs/PROTOCOL.md` §6.4).
252#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
253pub enum ErrorCode {
254    /// No endpoint is registered for the requested path.
255    UnknownEndpoint,
256    /// The receiving side declined the transfer.
257    Rejected,
258    /// A reserved or unsupported header value was requested.
259    Unsupported,
260    /// The receiving side failed internally.
261    Internal,
262    /// The request was accepted but no reply will be produced.
263    NoReply,
264}
265
266impl ErrorCode {
267    /// The wire code.
268    pub const fn to_wire(self) -> u64 {
269        match self {
270            ErrorCode::UnknownEndpoint => 1,
271            ErrorCode::Rejected => 2,
272            ErrorCode::Unsupported => 3,
273            ErrorCode::Internal => 4,
274            ErrorCode::NoReply => 5,
275        }
276    }
277
278    /// Interprets a wire code, returning `None` for unknown values.
279    pub const fn from_wire(code: u64) -> Option<ErrorCode> {
280        match code {
281            1 => Some(ErrorCode::UnknownEndpoint),
282            2 => Some(ErrorCode::Rejected),
283            3 => Some(ErrorCode::Unsupported),
284            4 => Some(ErrorCode::Internal),
285            5 => Some(ErrorCode::NoReply),
286            _ => None,
287        }
288    }
289}
290
291impl From<ErrorCode> for Error {
292    fn from(code: ErrorCode) -> Error {
293        match code {
294            ErrorCode::UnknownEndpoint => Error::UnknownEndpoint,
295            ErrorCode::Rejected => Error::Rejected,
296            ErrorCode::Unsupported => Error::Unsupported,
297            ErrorCode::Internal => Error::Transport("peer reported an internal error".into()),
298            ErrorCode::NoReply => Error::NoReply,
299        }
300    }
301}
302
303/// Why a peer refused to receive more payload, as carried by
304/// `STOP_SENDING`'s QUIC application error code.
305///
306/// The transport maps the numeric code (`weida_protocol::codes`) onto this enum;
307/// the core stays free of transport constants.
308#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
309pub enum StopReason {
310    /// `REJECTED`: the application declined the transfer.
311    Rejected,
312    /// `CANCELED`: the peer is no longer interested.
313    Canceled,
314    /// `UNKNOWN_ENDPOINT`: no endpoint is registered for the path.
315    UnknownEndpoint,
316    /// `UNSUPPORTED`: the endpoint exists but does not serve this stream kind.
317    Unsupported,
318    /// `LIMIT_EXCEEDED`: the endpoint is at a capacity bound — a paired
319    /// endpoint that already has its peer, for instance. A refusal of this
320    /// stream, not of the connection.
321    LimitExceeded,
322    /// `SHUTDOWN`: the peer's runtime has stopped admitting work — it is
323    /// draining or closing, and this stream arrived too late.
324    ShuttingDown,
325    /// Any other code, kept for diagnostics.
326    Other(u64),
327}
328
329impl From<StopReason> for Error {
330    fn from(reason: StopReason) -> Error {
331        match reason {
332            StopReason::Rejected => Error::Rejected,
333            StopReason::Canceled => Error::Canceled,
334            StopReason::UnknownEndpoint => Error::UnknownEndpoint,
335            StopReason::Unsupported => Error::Unsupported,
336            StopReason::LimitExceeded => Error::LimitExceeded,
337            // A refusal, and a definite one: nothing of this transfer was
338            // taken, and the peer will not take it later either. It is
339            // `Rejected` rather than a variant of its own because the outcome
340            // an application must act on is identical — do not retry against
341            // this peer — and a second word for the same outcome would add
342            // nothing.
343            StopReason::ShuttingDown => Error::Rejected,
344            StopReason::Other(code) => {
345                Error::Transport(format!("peer stopped receiving with code {code}"))
346            }
347        }
348    }
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    #[test]
356    fn display_is_non_empty_for_every_variant() {
357        let variants = [
358            Error::Runtime("x".into()),
359            Error::InvalidAddress("x".into()),
360            Error::InvalidEndpointPath,
361            Error::AlreadyRegistered,
362            Error::NotConnected,
363            Error::ConnectionLost(LossCause::IdleTimeout),
364            Error::Negotiation("x".into()),
365            Error::Protocol("x".into()),
366            Error::Rejected,
367            Error::UnknownEndpoint,
368            Error::Unsupported,
369            Error::NoReply,
370            Error::Canceled,
371            Error::Expired,
372            Error::Indeterminate,
373            Error::LimitExceeded,
374            Error::DatagramsUnavailable,
375            Error::TooLarge { max: 1200 },
376            Error::Tls("x".into()),
377            Error::Io(std::io::Error::other("x")),
378            Error::Transport("x".into()),
379        ];
380        for v in &variants {
381            assert!(!v.to_string().is_empty(), "{v:?}");
382        }
383    }
384
385    #[test]
386    fn definite_failures_exclude_the_unknowable_ones() {
387        // A typed refusal proves the payload never reached an application.
388        for definite in [
389            Error::ConnectionLost(LossCause::PeerClosed),
390            Error::Rejected,
391            Error::UnknownEndpoint,
392            Error::Unsupported,
393            Error::Canceled,
394            Error::NotConnected,
395            Error::LimitExceeded,
396            Error::DatagramsUnavailable,
397            Error::TooLarge { max: 1200 },
398        ] {
399            assert!(definite.is_definite_failure(), "{definite:?}");
400        }
401        // `Indeterminate` is unknown by construction, a missing reply says
402        // nothing about whether the request had an effect, and an expired
403        // transfer may have been read whole before its reset landed.
404        assert!(!Error::Indeterminate.is_definite_failure());
405        assert!(!Error::NoReply.is_definite_failure());
406        assert!(!Error::Expired.is_definite_failure());
407    }
408
409    #[test]
410    fn io_error_is_the_source() {
411        use std::error::Error as _;
412        let e = Error::Io(std::io::Error::other("boom"));
413        assert!(e.source().is_some());
414        assert!(Error::Canceled.source().is_none());
415    }
416
417    #[test]
418    fn an_outcome_survives_a_round_trip_through_io_error() {
419        let back = Error::from(std::io::Error::from(Error::Canceled));
420        assert!(matches!(back, Error::Canceled), "{back:?}");
421        assert_eq!(
422            std::io::Error::from(Error::Expired).kind(),
423            std::io::ErrorKind::TimedOut
424        );
425        assert!(matches!(
426            Error::from(std::io::Error::other("x")),
427            Error::Io(_)
428        ));
429    }
430}