ntex_io/lib.rs
1//! Asynchronous I/O abstractions for the ntex ecosystem.
2//!
3//! [`Io`] wraps an underlying [`IoStream`] and coordinates buffered reads,
4//! writes, backpressure, timeouts, and shutdown. Protocol transforms can be
5//! composed through [`Filter`] layers, while [`Framed`] combines an I/O stream
6//! with an `ntex-codec` encoder and decoder.
7//!
8//! Use [`IoConfig`] to configure buffer thresholds and connection timeouts.
9#![deny(clippy::pedantic)]
10#![allow(
11 clippy::missing_fields_in_debug,
12 clippy::missing_errors_doc,
13 clippy::missing_panics_doc,
14 clippy::must_use_candidate
15)]
16#![cfg_attr(docsrs, feature(doc_cfg))]
17use std::io::{Error as IoError, Result as IoResult};
18use std::{any::Any, any::TypeId, fmt, task::Poll};
19
20pub mod cfg;
21pub mod testing;
22pub mod types;
23
24mod buf;
25mod ctx;
26mod filter;
27mod filterptr;
28mod flags;
29mod framed;
30mod io;
31mod ioref;
32mod macros;
33mod metrics;
34mod ops;
35mod seal;
36#[cfg(feature = "tokio")]
37mod tokio;
38mod utils;
39mod waiters;
40
41use ntex_codec::Decoder;
42
43pub use self::buf::{FilterBuf, FilterCtx};
44#[cfg(feature = "tracker")]
45pub use self::cfg::BufTracker;
46pub use self::cfg::IoConfig;
47pub use self::ctx::IoContext;
48pub use self::filter::{Base, Filter, Layer};
49pub use self::framed::Framed;
50pub use self::io::{Io, IoRef};
51pub use self::metrics::{
52 CloseReason, CloseStats, IoConfigMetrics, IoMetrics, IoMetricsGroup, IoMetricsSnapshot,
53};
54pub use self::ops::{Id, TimerHandle};
55pub use self::seal::{IoBoxed, Sealed};
56pub use self::utils::Decoded;
57pub use self::waiters::Waiter;
58
59#[doc(hidden)]
60pub use self::flags::Flags;
61
62/// Filter readiness state.
63#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
64pub enum Readiness {
65 /// The I/O task may proceed with I/O operations.
66 Ready,
67 /// The transport must be closed gracefully.
68 ///
69 /// The I/O task must close both directions of the connection and then
70 /// release it. For a socket this is `shutdown(SHUT_RDWR)` followed by
71 /// `close()`. Any operation still in flight should be canceled.
72 ///
73 /// During a graceful shutdown buffered output is drained before this is
74 /// reported. If the connection ended because of a failure or an expired
75 /// shutdown deadline, output may instead be undeliverable and discarded.
76 /// In every case the I/O task must not attempt another flush.
77 Close,
78 /// The transport must be released immediately.
79 ///
80 /// This is reported only for an explicit force close through
81 /// [`IoRef::terminate`](crate::IoRef::terminate), so whatever is still
82 /// buffered is discarded on purpose. The I/O task must not perform a
83 /// graceful close: no receive queue drain and no `shutdown(SHUT_RDWR)`,
84 /// just release the connection. That keeps an aborted stream
85 /// distinguishable from one that ended normally, instead of terminating a
86 /// truncated response with a clean `FIN`.
87 ///
88 /// A connection that ends because of an I/O failure, a filter failure or an
89 /// expired shutdown deadline reports [`Close`](Self::Close) instead: the
90 /// transport is gone or unusable, so there is nothing to gain from
91 /// aborting it.
92 Terminate,
93}
94
95impl Readiness {
96 /// Merges two readiness states without regard to argument order.
97 ///
98 /// `Terminate` overrides every other state, `Close` overrides `Pending` and
99 /// `Ready`, and `Pending` overrides `Ready`.
100 pub fn merge(val1: Poll<Readiness>, val2: Poll<Readiness>) -> Poll<Readiness> {
101 match (val1, val2) {
102 (Poll::Ready(Readiness::Terminate), _) | (_, Poll::Ready(Readiness::Terminate)) => {
103 Poll::Ready(Readiness::Terminate)
104 }
105 (Poll::Ready(Readiness::Close), _) | (_, Poll::Ready(Readiness::Close)) => {
106 Poll::Ready(Readiness::Close)
107 }
108 (Poll::Pending, _) | (_, Poll::Pending) => Poll::Pending,
109 (Poll::Ready(Readiness::Ready), Poll::Ready(Readiness::Ready)) => {
110 Poll::Ready(Readiness::Ready)
111 }
112 }
113 }
114}
115
116/// A processing layer that transforms an I/O stream's read and write buffers.
117///
118/// Read processing runs from the transport toward the application. Write and
119/// shutdown processing run from the application toward the transport. Each
120/// callback receives the buffers immediately before and after this layer.
121///
122/// Implementations must move or transform all bytes they consume. Bytes left
123/// in a source buffer remain available to the layer on a later callback.
124#[allow(unused_variables)]
125pub trait FilterLayer: fmt::Debug + 'static {
126 /// Returns type-indexed information exposed by this layer.
127 ///
128 /// Returning `None` allows the query to continue through the remaining
129 /// filter chain.
130 fn query(&self, id: TypeId) -> Option<Box<dyn Any>> {
131 None
132 }
133
134 /// Processes incoming data from the transport-facing source buffer into
135 /// the application-facing destination buffer.
136 ///
137 /// This is also called once after clean transport read EOF, with
138 /// [`IoRef::is_read_eof`] returning `true`.
139 fn process_read_buf(&self, buf: &FilterBuf<'_>) -> IoResult<()>;
140
141 /// Processes outgoing data from the application-facing source buffer into
142 /// the transport-facing destination buffer.
143 ///
144 /// A filter may leave source data in place, for example while a TLS
145 /// handshake is in progress. The transport write task then pauses, and
146 /// this is called again once new output is queued or new input has been
147 /// processed. A filter that waits for anything else wakes the read task
148 /// through [`Filter::poll_ready`], its output is processed again once the
149 /// chain is ready.
150 fn process_write_buf(&self, buf: &FilterBuf<'_>) -> IoResult<()>;
151
152 /// Performs graceful filter shutdown.
153 ///
154 /// Returning `Poll::Pending` keeps the filter active and causes shutdown to
155 /// be polled again after the I/O task is notified. A ready result allows
156 /// shutdown to continue toward the transport.
157 ///
158 /// A filter that waits for input from the peer must check
159 /// [`IoRef::is_read_eof`] and return a ready result once it is set: after a
160 /// clean read EOF no further input can arrive, so pending forever would
161 /// only stall the close until the shutdown timeout expires. The runtime
162 /// also ends the shutdown phase itself in that case, but it cannot know
163 /// whether the filter considers the shutdown complete.
164 ///
165 /// Once this returns a ready result, [`process_write_buf`](Self::process_write_buf)
166 /// runs one final time and the layer is finished. Output still left in
167 /// the layer's write source after that pass is discarded and shutdown
168 /// fails with an error reporting the lost byte count. The default
169 /// implementation is ready immediately, so a filter that retains output
170 /// (for example until a handshake completes) must override this method
171 /// and return `Poll::Pending` until that output has been processed.
172 fn shutdown(&self, buf: &FilterBuf<'_>) -> IoResult<Poll<()>> {
173 Ok(Poll::Ready(()))
174 }
175}
176
177/// An underlying transport that can be managed by [`Io`].
178///
179/// [`start`](IoStream::start) is called exactly once when the transport is
180/// wrapped in [`Io`]. The implementation must start its read and write tasks,
181/// use the supplied [`IoContext`] to exchange buffers and readiness state, and
182/// return a handle that remains valid for the connection's lifetime.
183pub trait IoStream {
184 /// Starts transport-specific I/O tasks and returns their control handle.
185 fn start(self, _: IoContext) -> Box<dyn Handle>;
186}
187
188#[doc(hidden)]
189/// Callbacks invoked around filter-chain processing.
190pub trait IoCallbacks {
191 /// Called before processing the read or write filter chain.
192 fn before_processing(&self, io: &IoRef);
193
194 /// Called after processing the read or write filter chain.
195 fn after_processing(&self, io: &IoRef);
196}
197
198/// Control handle for transport-specific I/O tasks.
199///
200/// The handle is called synchronously by the connection state and must not
201/// block.
202pub trait Handle {
203 /// Returns type-indexed transport information.
204 fn query(&self, _: TypeId) -> Option<Box<dyn Any>> {
205 None
206 }
207
208 #[inline]
209 /// Requests that the transport start or resume a write operation.
210 fn write(&self, _: &IoContext) {}
211}
212
213/// Current status of the I/O state.
214#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
215pub enum IoTaskStatus {
216 /// Work remains, the task should perform another I/O operation.
217 ///
218 /// This reports that the connection still has work to do, not that the
219 /// transport can accept or supply bytes right now. A task must re-arm
220 /// transport readiness before the next operation. On the write side it is
221 /// returned whenever output is still buffered, including after an attempt
222 /// that made no progress.
223 Io,
224 /// Pause the task until the context wakes it.
225 Pause,
226 /// Stop the task and release its transport resources.
227 Stop,
228}
229
230/// I/O status update events.
231#[derive(Debug)]
232pub enum IoStatusUpdate {
233 /// The dispatcher timer has expired.
234 Timeout,
235 /// Write backpressure is currently active.
236 WriteBackpressure,
237 /// The connection is no longer usable.
238 ///
239 /// Reported once the connection can no longer dispatch frames, whether
240 /// because transport shutdown has begun, the peer disconnected, an error
241 /// occurred, or shutdown was started locally with
242 /// [`IoRef::close`](crate::IoRef::close) or
243 /// [`IoRef::terminate`](crate::IoRef::terminate). The transport backend
244 /// may still be finishing teardown.
245 ///
246 /// Carries the connection error, which may originate from the transport,
247 /// a filter, or shutdown. `None` means no error was recorded.
248 PeerGone(Option<IoError>),
249}
250
251/// Errors that can occur while receiving data.
252pub enum RecvError<U: Decoder> {
253 /// The dispatcher timer has expired.
254 Timeout,
255 /// Write backpressure is currently active.
256 WriteBackpressure,
257 /// Failed to decode an incoming frame.
258 Decoder(U::Error),
259 /// The connection is no longer usable.
260 ///
261 /// Reported once the connection can no longer dispatch frames, whether
262 /// because transport shutdown has begun, the peer disconnected, an error
263 /// occurred, or shutdown was started locally with
264 /// [`IoRef::close`](crate::IoRef::close) or
265 /// [`IoRef::terminate`](crate::IoRef::terminate). The transport backend
266 /// may still be finishing teardown.
267 ///
268 /// Carries the connection error, which may originate from the transport,
269 /// a filter, or shutdown. A clean peer EOF that leaves undecodable bytes
270 /// in the read buffer is reported as an
271 /// [`io::ErrorKind::UnexpectedEof`](std::io::ErrorKind::UnexpectedEof)
272 /// error. `None` means the connection closed without an error and without
273 /// a truncated frame.
274 PeerGone(Option<IoError>),
275}
276
277impl<U> fmt::Debug for RecvError<U>
278where
279 U: Decoder,
280 <U as Decoder>::Error: fmt::Debug,
281{
282 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
283 match *self {
284 RecvError::Timeout => {
285 write!(fmt, "RecvError::Timeout")
286 }
287 RecvError::WriteBackpressure => {
288 write!(fmt, "RecvError::WriteBackpressure")
289 }
290 RecvError::Decoder(ref e) => {
291 write!(fmt, "RecvError::Decoder({e:?})")
292 }
293 RecvError::PeerGone(ref e) => {
294 write!(fmt, "RecvError::PeerGone({e:?})")
295 }
296 }
297 }
298}
299
300#[cfg(test)]
301mod tests {
302 use super::*;
303 use ntex_codec::BytesCodec;
304 use std::io;
305
306 /// STATEMENT: `RecvError` debug output identifies the represented variants.
307 ///
308 /// HOW:
309 /// - Format timeout, backpressure, decoder, and peer-gone variants and check their names.
310 #[test]
311 fn test_fmt() {
312 assert!(format!("{:?}", RecvError::<BytesCodec>::Timeout).contains("Timeout"));
313 assert!(
314 format!("{:?}", RecvError::<BytesCodec>::WriteBackpressure)
315 .contains("WriteBackpressure")
316 );
317 assert!(
318 format!(
319 "{:?}",
320 RecvError::<BytesCodec>::Decoder(io::Error::other("err"))
321 )
322 .contains("RecvError::Decoder")
323 );
324 assert!(
325 format!(
326 "{:?}",
327 RecvError::<BytesCodec>::PeerGone(Some(io::Error::other("err")))
328 )
329 .contains("RecvError::PeerGone")
330 );
331 }
332
333 /// STATEMENT: Readiness merging is commutative and prioritizes termination and close over waiting.
334 ///
335 /// HOW:
336 /// - Compare both argument orders for every readiness pair.
337 /// - Check representative pending, ready, close, and terminate precedence combinations.
338 #[test]
339 fn readiness_merge() {
340 let states = [
341 Poll::Pending,
342 Poll::Ready(Readiness::Ready),
343 Poll::Ready(Readiness::Close),
344 Poll::Ready(Readiness::Terminate),
345 ];
346
347 for val1 in states {
348 for val2 in states {
349 assert_eq!(Readiness::merge(val1, val2), Readiness::merge(val2, val1));
350 }
351 }
352
353 assert_eq!(
354 Readiness::merge(Poll::Pending, Poll::Ready(Readiness::Ready)),
355 Poll::Pending
356 );
357 assert_eq!(
358 Readiness::merge(Poll::Pending, Poll::Ready(Readiness::Close)),
359 Poll::Ready(Readiness::Close)
360 );
361 assert_eq!(
362 Readiness::merge(Poll::Ready(Readiness::Ready), Poll::Ready(Readiness::Close)),
363 Poll::Ready(Readiness::Close)
364 );
365 assert_eq!(
366 Readiness::merge(Poll::Pending, Poll::Ready(Readiness::Terminate)),
367 Poll::Ready(Readiness::Terminate)
368 );
369 assert_eq!(
370 Readiness::merge(
371 Poll::Ready(Readiness::Close),
372 Poll::Ready(Readiness::Terminate)
373 ),
374 Poll::Ready(Readiness::Terminate)
375 );
376 }
377}