Skip to main content

moq_transport_iroh/
error.rs

1//! The crate's error types.
2
3use std::sync::Arc;
4
5use iroh::endpoint::{
6    ClosedStream, ConnectionError, ReadError, ResetError, SendDatagramError, StoppedError, VarInt,
7    WriteError,
8};
9use moq_net::transport::CloseKind;
10use n0_error::{AnyError, stack_error};
11
12/// An error from dialing or accepting a MoQ connection.
13#[stack_error(derive, add_meta)]
14#[derive(Clone)]
15pub enum Error {
16    /// The peer could not be dialed, or the handshake failed.
17    ///
18    /// The source sits in an [`Arc`] so that the callers waiting on one dial
19    /// can share the failure.
20    #[error("failed to connect to the peer")]
21    Connect {
22        #[error(source, std_err)]
23        source: Arc<AnyError>,
24    },
25    /// The peer negotiated an ALPN this build does not speak.
26    #[error("the peer negotiated an ALPN this build does not speak: {alpn}")]
27    UnsupportedAlpn { alpn: String },
28}
29
30impl Error {
31    /// Returns a [`Connect`](Self::Connect) error for a dial that failed with `source`.
32    ///
33    /// For a caller that dials with its own options, such as iroh's
34    /// `connect_with_opts`, before it hands the connection to
35    /// [`Transport::new`](crate::Transport::new).
36    pub fn connect(source: impl std::error::Error + Send + Sync + 'static) -> Self {
37        n0_error::e!(Self::Connect {
38            source: Arc::new(AnyError::from_std(source))
39        })
40    }
41}
42
43/// A failure of a [`Transport`](crate::Transport)'s connection or of one of its streams.
44///
45/// moq-net reads the application codes from it: a session close code from
46/// [`Connection`](Self::Connection), a stream code from [`Stopped`](Self::Stopped)
47/// and [`Reset`](Self::Reset).
48#[stack_error(derive)]
49#[derive(Clone)]
50pub enum TransportError {
51    /// The connection closed or failed.
52    #[error("connection lost: {_0}")]
53    Connection(#[error(source, std_err)] ConnectionError),
54    /// The peer stopped a stream this side sends on.
55    #[error("stream stopped by the peer with code {_0}")]
56    Stopped(VarInt),
57    /// The peer reset a stream this side reads.
58    #[error("stream reset by the peer with code {_0}")]
59    Reset(VarInt),
60    /// The stream was already finished, reset or stopped.
61    #[error("stream already closed")]
62    ClosedStream,
63    /// The connection refused a datagram.
64    #[error("datagram refused: {_0}")]
65    Datagram(#[error(source, std_err)] SendDatagramError),
66}
67
68impl TransportError {
69    /// Returns the connection failure behind this error, if there is one.
70    fn connection(&self) -> Option<&ConnectionError> {
71        match self {
72            Self::Connection(err) | Self::Datagram(SendDatagramError::ConnectionLost(err)) => {
73                Some(err)
74            }
75            _ => None,
76        }
77    }
78}
79
80impl moq_net::transport::Error for TransportError {
81    fn close_kind(&self) -> CloseKind {
82        match self.connection() {
83            Some(ConnectionError::TimedOut) => CloseKind::IdleTimeout,
84            Some(ConnectionError::LocallyClosed) => CloseKind::Closed,
85            _ => CloseKind::Transport,
86        }
87    }
88
89    fn session_error(&self) -> Option<(u32, String)> {
90        let Some(ConnectionError::ApplicationClosed(close)) = self.connection() else {
91            return None;
92        };
93        let code = u32::try_from(close.error_code.into_inner()).ok()?;
94        Some((code, String::from_utf8_lossy(&close.reason).into_owned()))
95    }
96
97    fn stream_error(&self) -> Option<u32> {
98        match self {
99            Self::Stopped(code) | Self::Reset(code) => u32::try_from(code.into_inner()).ok(),
100            _ => None,
101        }
102    }
103}
104
105impl From<ConnectionError> for TransportError {
106    fn from(err: ConnectionError) -> Self {
107        Self::Connection(err)
108    }
109}
110
111impl From<SendDatagramError> for TransportError {
112    fn from(err: SendDatagramError) -> Self {
113        Self::Datagram(err)
114    }
115}
116
117impl From<ClosedStream> for TransportError {
118    fn from(_: ClosedStream) -> Self {
119        Self::ClosedStream
120    }
121}
122
123// The transport never sends 0-RTT data, so the `ZeroRttRejected` variants below
124// cannot occur. They map to a closed stream rather than a panic.
125
126impl From<WriteError> for TransportError {
127    fn from(err: WriteError) -> Self {
128        match err {
129            WriteError::Stopped(code) => Self::Stopped(code),
130            WriteError::ConnectionLost(err) => Self::Connection(err),
131            WriteError::ClosedStream | WriteError::ZeroRttRejected => Self::ClosedStream,
132        }
133    }
134}
135
136impl From<ReadError> for TransportError {
137    fn from(err: ReadError) -> Self {
138        match err {
139            ReadError::Reset(code) => Self::Reset(code),
140            ReadError::ConnectionLost(err) => Self::Connection(err),
141            ReadError::ClosedStream | ReadError::ZeroRttRejected => Self::ClosedStream,
142        }
143    }
144}
145
146impl From<StoppedError> for TransportError {
147    fn from(err: StoppedError) -> Self {
148        match err {
149            StoppedError::ConnectionLost(err) => Self::Connection(err),
150            StoppedError::ZeroRttRejected => Self::ClosedStream,
151        }
152    }
153}
154
155impl From<ResetError> for TransportError {
156    fn from(err: ResetError) -> Self {
157        match err {
158            ResetError::ConnectionLost(err) => Self::Connection(err),
159            ResetError::ZeroRttRejected => Self::ClosedStream,
160        }
161    }
162}