ntex_io/
lib.rs

1//! Utilities for abstructing io streams
2#![deny(rust_2018_idioms, unreachable_pub, missing_debug_implementations)]
3#![allow(async_fn_in_trait)]
4
5use std::io::{Error as IoError, Result as IoResult};
6use std::{any::Any, any::TypeId, fmt, task::Context, task::Poll};
7
8pub mod cfg;
9pub mod testing;
10pub mod types;
11
12mod buf;
13mod dispatcher;
14mod filter;
15mod flags;
16mod framed;
17mod io;
18mod ioref;
19mod macros;
20mod seal;
21mod tasks;
22mod timer;
23mod utils;
24
25use ntex_codec::{Decoder, Encoder};
26
27pub use self::buf::{FilterCtx, ReadBuf, WriteBuf};
28pub use self::cfg::IoConfig;
29pub use self::dispatcher::Dispatcher;
30pub use self::filter::{Base, Filter, FilterReadStatus, Layer};
31pub use self::framed::Framed;
32pub use self::io::{Io, IoRef, OnDisconnect};
33pub use self::seal::{IoBoxed, Sealed};
34pub use self::tasks::IoContext;
35pub use self::timer::TimerHandle;
36pub use self::utils::{Decoded, seal};
37
38#[doc(hidden)]
39pub use self::flags::Flags;
40
41/// Filter ready state
42#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
43pub enum Readiness {
44    /// Io task is clear to proceed with io operations
45    Ready,
46    /// Initiate graceful io shutdown operation
47    Shutdown,
48    /// Immediately terminate connection
49    Terminate,
50}
51
52impl Readiness {
53    /// Merge two Readiness values
54    pub fn merge(val1: Poll<Readiness>, val2: Poll<Readiness>) -> Poll<Readiness> {
55        match val1 {
56            Poll::Pending => Poll::Pending,
57            Poll::Ready(Readiness::Ready) => val2,
58            Poll::Ready(Readiness::Terminate) => Poll::Ready(Readiness::Terminate),
59            Poll::Ready(Readiness::Shutdown) => {
60                if val2 == Poll::Ready(Readiness::Terminate) {
61                    Poll::Ready(Readiness::Terminate)
62                } else {
63                    Poll::Ready(Readiness::Shutdown)
64                }
65            }
66        }
67    }
68}
69
70#[allow(unused_variables)]
71pub trait FilterLayer: fmt::Debug + 'static {
72    #[inline]
73    /// Check readiness for read operations
74    fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<Readiness> {
75        Poll::Ready(Readiness::Ready)
76    }
77
78    #[inline]
79    /// Check readiness for write operations
80    fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<Readiness> {
81        Poll::Ready(Readiness::Ready)
82    }
83
84    /// Process read buffer
85    ///
86    /// Inner filter must process buffer before current.
87    /// Returns number of new bytes.
88    fn process_read_buf(&self, buf: &ReadBuf<'_>) -> IoResult<usize>;
89
90    /// Process write buffer
91    fn process_write_buf(&self, buf: &WriteBuf<'_>) -> IoResult<()>;
92
93    #[inline]
94    /// Query internal filter data
95    fn query(&self, id: TypeId) -> Option<Box<dyn Any>> {
96        None
97    }
98
99    #[inline]
100    /// Gracefully shutdown filter
101    fn shutdown(&self, buf: &WriteBuf<'_>) -> IoResult<Poll<()>> {
102        Ok(Poll::Ready(()))
103    }
104}
105
106pub trait IoStream {
107    fn start(self, _: IoContext) -> Option<Box<dyn Handle>>;
108}
109
110pub trait Handle {
111    fn query(&self, id: TypeId) -> Option<Box<dyn Any>>;
112}
113
114/// Status for read task
115#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
116pub enum IoTaskStatus {
117    /// More io ops
118    Io,
119    /// Pause io task
120    Pause,
121    /// Stop io task
122    Stop,
123}
124
125/// Io status
126#[derive(Debug)]
127pub enum IoStatusUpdate {
128    /// Keep-alive timeout occured
129    KeepAlive,
130    /// Write backpressure is enabled
131    WriteBackpressure,
132    /// Peer is disconnected
133    PeerGone(Option<IoError>),
134}
135
136/// Recv error
137pub enum RecvError<U: Decoder> {
138    /// Keep-alive timeout occured
139    KeepAlive,
140    /// Write backpressure is enabled
141    WriteBackpressure,
142    /// Unrecoverable frame decoding errors
143    Decoder(U::Error),
144    /// Peer is disconnected
145    PeerGone(Option<IoError>),
146}
147
148impl<U> fmt::Debug for RecvError<U>
149where
150    U: Decoder,
151    <U as Decoder>::Error: fmt::Debug,
152{
153    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
154        match *self {
155            RecvError::KeepAlive => {
156                write!(fmt, "RecvError::KeepAlive")
157            }
158            RecvError::WriteBackpressure => {
159                write!(fmt, "RecvError::WriteBackpressure")
160            }
161            RecvError::Decoder(ref e) => {
162                write!(fmt, "RecvError::Decoder({e:?})")
163            }
164            RecvError::PeerGone(ref e) => {
165                write!(fmt, "RecvError::PeerGone({e:?})")
166            }
167        }
168    }
169}
170
171/// Dispatcher item
172pub enum DispatchItem<U: Encoder + Decoder> {
173    Item(<U as Decoder>::Item),
174    /// Write back-pressure enabled
175    WBackPressureEnabled,
176    /// Write back-pressure disabled
177    WBackPressureDisabled,
178    /// Keep alive timeout
179    KeepAliveTimeout,
180    /// Frame read timeout
181    ReadTimeout,
182    /// Decoder parse error
183    DecoderError(<U as Decoder>::Error),
184    /// Encoder parse error
185    EncoderError(<U as Encoder>::Error),
186    /// Socket is disconnected
187    Disconnect(Option<IoError>),
188}
189
190impl<U> fmt::Debug for DispatchItem<U>
191where
192    U: Encoder + Decoder,
193    <U as Decoder>::Item: fmt::Debug,
194{
195    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
196        match *self {
197            DispatchItem::Item(ref item) => {
198                write!(fmt, "DispatchItem::Item({item:?})")
199            }
200            DispatchItem::WBackPressureEnabled => {
201                write!(fmt, "DispatchItem::WBackPressureEnabled")
202            }
203            DispatchItem::WBackPressureDisabled => {
204                write!(fmt, "DispatchItem::WBackPressureDisabled")
205            }
206            DispatchItem::KeepAliveTimeout => {
207                write!(fmt, "DispatchItem::KeepAliveTimeout")
208            }
209            DispatchItem::ReadTimeout => {
210                write!(fmt, "DispatchItem::ReadTimeout")
211            }
212            DispatchItem::EncoderError(ref e) => {
213                write!(fmt, "DispatchItem::EncoderError({e:?})")
214            }
215            DispatchItem::DecoderError(ref e) => {
216                write!(fmt, "DispatchItem::DecoderError({e:?})")
217            }
218            DispatchItem::Disconnect(ref e) => {
219                write!(fmt, "DispatchItem::Disconnect({e:?})")
220            }
221        }
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228    use ntex_codec::BytesCodec;
229    use std::io;
230
231    #[test]
232    fn test_fmt() {
233        type T = DispatchItem<BytesCodec>;
234
235        let err = T::EncoderError(io::Error::other("err"));
236        assert!(format!("{err:?}").contains("DispatchItem::Encoder"));
237        let err = T::DecoderError(io::Error::other("err"));
238        assert!(format!("{err:?}").contains("DispatchItem::Decoder"));
239        let err = T::Disconnect(Some(io::Error::other("err")));
240        assert!(format!("{err:?}").contains("DispatchItem::Disconnect"));
241
242        assert!(
243            format!("{:?}", T::WBackPressureEnabled)
244                .contains("DispatchItem::WBackPressureEnabled")
245        );
246        assert!(
247            format!("{:?}", T::WBackPressureDisabled)
248                .contains("DispatchItem::WBackPressureDisabled")
249        );
250        assert!(
251            format!("{:?}", T::KeepAliveTimeout).contains("DispatchItem::KeepAliveTimeout")
252        );
253        assert!(format!("{:?}", T::ReadTimeout).contains("DispatchItem::ReadTimeout"));
254
255        assert!(format!("{:?}", IoStatusUpdate::KeepAlive).contains("KeepAlive"));
256        assert!(format!("{:?}", RecvError::<BytesCodec>::KeepAlive).contains("KeepAlive"));
257        assert!(
258            format!("{:?}", RecvError::<BytesCodec>::WriteBackpressure)
259                .contains("WriteBackpressure")
260        );
261        assert!(
262            format!(
263                "{:?}",
264                RecvError::<BytesCodec>::Decoder(io::Error::other("err"))
265            )
266            .contains("RecvError::Decoder")
267        );
268        assert!(
269            format!(
270                "{:?}",
271                RecvError::<BytesCodec>::PeerGone(Some(io::Error::other("err")))
272            )
273            .contains("RecvError::PeerGone")
274        );
275    }
276}