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 connection was lost after the local FIN while awaiting an ACK or a
59 /// reply: the outcome is genuinely unknown (master doc §22).
60 Indeterminate,
61 /// A local or negotiated resource limit was reached.
62 LimitExceeded,
63 /// TLS material could not be loaded or configured, or the handshake
64 /// failed for a reason other than an untrusted peer.
65 Tls(String),
66 /// The peer proved possession of a key whose fingerprint is neither
67 /// pinned nor certified by a configured anchor. Carries what the peer
68 /// presented, so an operator can pin it after checking it out of band.
69 Untrusted(crate::identity::Fingerprint),
70 /// Underlying I/O failure.
71 Io(std::io::Error),
72 /// Transport-level failure that is not one of the modelled outcomes.
73 Transport(String),
74}
75
76/// Why a connection is gone.
77///
78/// The *outcome* is the same whichever it is — nothing that was in flight
79/// completed, which is what [`Error::ConnectionLost`] promises — so this is
80/// not a second outcome vocabulary. It exists because the next action differs:
81/// an idle timeout invites a redial, a peer that closed deliberately may not
82/// want one yet, and a local close means the application already decided.
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub enum LossCause {
85 /// No traffic for the idle period, on whichever side's timeout was
86 /// shorter. Nothing is wrong with either peer.
87 IdleTimeout,
88 /// The peer closed the connection deliberately, with a code this side
89 /// does not map to a more specific outcome — a shutdown, typically.
90 PeerClosed,
91 /// This side closed it: `Runtime::shutdown`, or a dropped runtime.
92 LocallyClosed,
93 /// A stateless reset: the peer has forgotten the connection, usually
94 /// because it restarted.
95 Reset,
96 /// A QUIC transport error ended the connection. Either peer may be at
97 /// fault, and a redial is unlikely to behave differently.
98 TransportError,
99}
100
101impl fmt::Display for LossCause {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 f.write_str(match self {
104 LossCause::IdleTimeout => "idle timeout",
105 LossCause::PeerClosed => "closed by the peer",
106 LossCause::LocallyClosed => "closed locally",
107 LossCause::Reset => "stateless reset",
108 LossCause::TransportError => "transport error",
109 })
110 }
111}
112
113impl fmt::Display for Error {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 match self {
116 Error::Runtime(m) => write!(f, "runtime error: {m}"),
117 Error::InvalidAddress(m) => write!(f, "invalid address: {m}"),
118 Error::InvalidEndpointPath => f.write_str(
119 "invalid endpoint path: must start with '/', be 1..=512 bytes and contain no control bytes",
120 ),
121 Error::InvalidFingerprint(m) => {
122 write!(f, "invalid fingerprint: expected sha256:<64 hex digits>, got {m:?}")
123 }
124 Error::AlreadyRegistered => f.write_str("endpoint path already registered"),
125 Error::NotConnected => f.write_str("endpoint is not connected to any peer"),
126 Error::ConnectionLost(cause) => {
127 write!(f, "connection lost before the transfer completed: {cause}")
128 }
129 Error::Negotiation(m) => write!(f, "negotiation failed: {m}"),
130 Error::Protocol(m) => write!(f, "protocol violation: {m}"),
131 Error::Rejected => f.write_str("peer rejected the transfer"),
132 Error::UnknownEndpoint => f.write_str("peer has no such endpoint"),
133 Error::Unsupported => f.write_str("peer does not support the requested feature"),
134 Error::NoParkedConnection => {
135 f.write_str("peer has no parked connection for a stream toward it")
136 }
137 Error::NoReply => f.write_str("peer accepted the request but sent no reply"),
138 Error::Canceled => f.write_str("transfer canceled"),
139 Error::Indeterminate => {
140 f.write_str("outcome indeterminate: the transfer may or may not have been accepted")
141 }
142 Error::LimitExceeded => f.write_str("resource limit exceeded"),
143 Error::Tls(m) => write!(f, "tls error: {m}"),
144 Error::Untrusted(fp) => write!(f, "peer identity {fp} is not trusted"),
145 Error::Io(e) => write!(f, "io error: {e}"),
146 Error::Transport(m) => write!(f, "transport error: {m}"),
147 }
148 }
149}
150
151impl std::error::Error for Error {
152 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
153 match self {
154 Error::Io(e) => Some(e),
155 _ => None,
156 }
157 }
158}
159
160impl From<std::io::Error> for Error {
161 fn from(e: std::io::Error) -> Self {
162 Error::Io(e)
163 }
164}
165
166impl Error {
167 /// True if the error proves the transfer had no effect at the peer.
168 ///
169 /// `Indeterminate` is deliberately *not* in this set: modelling it apart
170 /// from definite failure is the point of master doc §22. Neither is
171 /// `NoReply` — the request was accepted and may well have had an effect;
172 /// only the answer is missing.
173 pub fn is_definite_failure(&self) -> bool {
174 matches!(
175 self,
176 Error::ConnectionLost(_)
177 | Error::Rejected
178 | Error::UnknownEndpoint
179 | Error::Unsupported
180 | Error::NoParkedConnection
181 | Error::Canceled
182 | Error::NotConnected
183 | Error::LimitExceeded
184 | Error::Untrusted(_)
185 )
186 }
187}
188
189/// Wire codes carried in an ERROR frame (`docs/PROTOCOL.md` §6.4).
190#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
191pub enum ErrorCode {
192 /// No endpoint is registered for the requested path.
193 UnknownEndpoint,
194 /// The receiving side declined the transfer.
195 Rejected,
196 /// A reserved or unsupported header value was requested.
197 Unsupported,
198 /// The receiving side failed internally.
199 Internal,
200 /// The request was accepted but no reply will be produced.
201 NoReply,
202}
203
204impl ErrorCode {
205 /// The wire code.
206 pub const fn to_wire(self) -> u64 {
207 match self {
208 ErrorCode::UnknownEndpoint => 1,
209 ErrorCode::Rejected => 2,
210 ErrorCode::Unsupported => 3,
211 ErrorCode::Internal => 4,
212 ErrorCode::NoReply => 5,
213 }
214 }
215
216 /// Interprets a wire code, returning `None` for unknown values.
217 pub const fn from_wire(code: u64) -> Option<ErrorCode> {
218 match code {
219 1 => Some(ErrorCode::UnknownEndpoint),
220 2 => Some(ErrorCode::Rejected),
221 3 => Some(ErrorCode::Unsupported),
222 4 => Some(ErrorCode::Internal),
223 5 => Some(ErrorCode::NoReply),
224 _ => None,
225 }
226 }
227}
228
229impl From<ErrorCode> for Error {
230 fn from(code: ErrorCode) -> Error {
231 match code {
232 ErrorCode::UnknownEndpoint => Error::UnknownEndpoint,
233 ErrorCode::Rejected => Error::Rejected,
234 ErrorCode::Unsupported => Error::Unsupported,
235 ErrorCode::Internal => Error::Transport("peer reported an internal error".into()),
236 ErrorCode::NoReply => Error::NoReply,
237 }
238 }
239}
240
241/// Why a peer refused to receive more payload, as carried by
242/// `STOP_SENDING`'s QUIC application error code.
243///
244/// The transport maps the numeric code (`weida_protocol::codes`) onto this enum;
245/// the core stays free of transport constants.
246#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
247pub enum StopReason {
248 /// `REJECTED`: the application declined the transfer.
249 Rejected,
250 /// `CANCELED`: the peer is no longer interested.
251 Canceled,
252 /// `UNKNOWN_ENDPOINT`: no endpoint is registered for the path.
253 UnknownEndpoint,
254 /// `UNSUPPORTED`: the endpoint exists but does not serve this stream kind.
255 Unsupported,
256 /// `LIMIT_EXCEEDED`: the endpoint is at a capacity bound — a paired
257 /// endpoint that already has its peer, for instance. A refusal of this
258 /// stream, not of the connection.
259 LimitExceeded,
260 /// `SHUTDOWN`: the peer's runtime has stopped admitting work — it is
261 /// draining or closing, and this stream arrived too late.
262 ShuttingDown,
263 /// Any other code, kept for diagnostics.
264 Other(u64),
265}
266
267impl From<StopReason> for Error {
268 fn from(reason: StopReason) -> Error {
269 match reason {
270 StopReason::Rejected => Error::Rejected,
271 StopReason::Canceled => Error::Canceled,
272 StopReason::UnknownEndpoint => Error::UnknownEndpoint,
273 StopReason::Unsupported => Error::Unsupported,
274 StopReason::LimitExceeded => Error::LimitExceeded,
275 // A refusal, and a definite one: nothing of this transfer was
276 // taken, and the peer will not take it later either. It is
277 // `Rejected` rather than a variant of its own because the outcome
278 // an application must act on is identical — do not retry against
279 // this peer — and a second word for the same outcome is what
280 // `LossCause` was introduced to avoid.
281 StopReason::ShuttingDown => Error::Rejected,
282 StopReason::Other(code) => {
283 Error::Transport(format!("peer stopped receiving with code {code}"))
284 }
285 }
286 }
287}
288
289#[cfg(test)]
290mod tests {
291 use super::*;
292
293 #[test]
294 fn display_is_non_empty_for_every_variant() {
295 let variants = [
296 Error::Runtime("x".into()),
297 Error::InvalidAddress("x".into()),
298 Error::InvalidEndpointPath,
299 Error::AlreadyRegistered,
300 Error::NotConnected,
301 Error::ConnectionLost(LossCause::IdleTimeout),
302 Error::Negotiation("x".into()),
303 Error::Protocol("x".into()),
304 Error::Rejected,
305 Error::UnknownEndpoint,
306 Error::Unsupported,
307 Error::NoReply,
308 Error::Canceled,
309 Error::Indeterminate,
310 Error::LimitExceeded,
311 Error::Tls("x".into()),
312 Error::Io(std::io::Error::other("x")),
313 Error::Transport("x".into()),
314 ];
315 for v in &variants {
316 assert!(!v.to_string().is_empty(), "{v:?}");
317 }
318 }
319
320 #[test]
321 fn definite_failures_exclude_the_unknowable_ones() {
322 // A typed refusal proves the payload never reached an application.
323 for definite in [
324 Error::ConnectionLost(LossCause::PeerClosed),
325 Error::Rejected,
326 Error::UnknownEndpoint,
327 Error::Unsupported,
328 Error::Canceled,
329 Error::NotConnected,
330 Error::LimitExceeded,
331 ] {
332 assert!(definite.is_definite_failure(), "{definite:?}");
333 }
334 // `Indeterminate` is unknown by construction, and a missing reply says
335 // nothing about whether the request had an effect.
336 assert!(!Error::Indeterminate.is_definite_failure());
337 assert!(!Error::NoReply.is_definite_failure());
338 }
339
340 #[test]
341 fn io_error_is_the_source() {
342 use std::error::Error as _;
343 let e = Error::Io(std::io::Error::other("boom"));
344 assert!(e.source().is_some());
345 assert!(Error::Canceled.source().is_none());
346 }
347}