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    /// Stop io stream handling
133    Stop,
134    /// Peer is disconnected
135    PeerGone(Option<IoError>),
136}
137
138/// Recv error
139#[derive(Debug)]
140pub enum RecvError<U: Decoder> {
141    /// Keep-alive timeout occured
142    KeepAlive,
143    /// Write backpressure is enabled
144    WriteBackpressure,
145    /// Stop io stream handling
146    Stop,
147    /// Unrecoverable frame decoding errors
148    Decoder(U::Error),
149    /// Peer is disconnected
150    PeerGone(Option<IoError>),
151}
152
153/// Dispatcher item
154pub enum DispatchItem<U: Encoder + Decoder> {
155    Item(<U as Decoder>::Item),
156    /// Write back-pressure enabled
157    WBackPressureEnabled,
158    /// Write back-pressure disabled
159    WBackPressureDisabled,
160    /// Keep alive timeout
161    KeepAliveTimeout,
162    /// Frame read timeout
163    ReadTimeout,
164    /// Decoder parse error
165    DecoderError(<U as Decoder>::Error),
166    /// Encoder parse error
167    EncoderError(<U as Encoder>::Error),
168    /// Socket is disconnected
169    Disconnect(Option<IoError>),
170}
171
172impl<U> fmt::Debug for DispatchItem<U>
173where
174    U: Encoder + Decoder,
175    <U as Decoder>::Item: fmt::Debug,
176{
177    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
178        match *self {
179            DispatchItem::Item(ref item) => {
180                write!(fmt, "DispatchItem::Item({item:?})")
181            }
182            DispatchItem::WBackPressureEnabled => {
183                write!(fmt, "DispatchItem::WBackPressureEnabled")
184            }
185            DispatchItem::WBackPressureDisabled => {
186                write!(fmt, "DispatchItem::WBackPressureDisabled")
187            }
188            DispatchItem::KeepAliveTimeout => {
189                write!(fmt, "DispatchItem::KeepAliveTimeout")
190            }
191            DispatchItem::ReadTimeout => {
192                write!(fmt, "DispatchItem::ReadTimeout")
193            }
194            DispatchItem::EncoderError(ref e) => {
195                write!(fmt, "DispatchItem::EncoderError({e:?})")
196            }
197            DispatchItem::DecoderError(ref e) => {
198                write!(fmt, "DispatchItem::DecoderError({e:?})")
199            }
200            DispatchItem::Disconnect(ref e) => {
201                write!(fmt, "DispatchItem::Disconnect({e:?})")
202            }
203        }
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210    use ntex_codec::BytesCodec;
211    use std::io;
212
213    #[test]
214    fn test_fmt() {
215        type T = DispatchItem<BytesCodec>;
216
217        let err = T::EncoderError(io::Error::other("err"));
218        assert!(format!("{err:?}").contains("DispatchItem::Encoder"));
219        let err = T::DecoderError(io::Error::other("err"));
220        assert!(format!("{err:?}").contains("DispatchItem::Decoder"));
221        let err = T::Disconnect(Some(io::Error::other("err")));
222        assert!(format!("{err:?}").contains("DispatchItem::Disconnect"));
223
224        assert!(
225            format!("{:?}", T::WBackPressureEnabled)
226                .contains("DispatchItem::WBackPressureEnabled")
227        );
228        assert!(
229            format!("{:?}", T::WBackPressureDisabled)
230                .contains("DispatchItem::WBackPressureDisabled")
231        );
232        assert!(
233            format!("{:?}", T::KeepAliveTimeout).contains("DispatchItem::KeepAliveTimeout")
234        );
235        assert!(format!("{:?}", T::ReadTimeout).contains("DispatchItem::ReadTimeout"));
236
237        assert!(format!("{:?}", IoStatusUpdate::KeepAlive).contains("KeepAlive"));
238        assert!(format!("{:?}", RecvError::<BytesCodec>::KeepAlive).contains("KeepAlive"));
239    }
240}