Skip to main content

ntex_io/
filter.rs

1use std::{any, cell::Cell, io, task::Context, task::Poll};
2
3use crate::{FilterCtx, FilterLayer, IoRef, Readiness, io::IoState};
4
5#[derive(Debug)]
6/// Base filter that connects a filter chain to the underlying transport.
7pub struct Base(IoRef);
8
9impl Base {
10    pub(crate) fn new(inner: IoRef) -> Self {
11        Base(inner)
12    }
13}
14
15#[derive(Debug)]
16/// One processing layer wrapped around an existing filter chain.
17///
18/// Values of this type are created by [`Io::add_filter`](crate::Io::add_filter).
19/// `F` is the outer, newly added layer and `L` is the previously installed
20/// inner chain.
21pub struct Layer<F, L = Base>(pub(crate) F, L, Cell<bool>);
22
23impl<F: FilterLayer, L: Filter> Layer<F, L> {
24    pub(crate) fn new(f: F, l: L) -> Self {
25        Self(f, l, Cell::new(false))
26    }
27}
28
29pub(crate) struct NullFilter;
30
31const NULL: NullFilter = NullFilter;
32
33impl NullFilter {
34    pub(super) const fn get() -> &'static dyn Filter {
35        &NULL
36    }
37}
38
39/// Complete filter-chain interface used by [`Io`](crate::Io).
40///
41/// Most filters should implement [`FilterLayer`] and be installed with
42/// [`Io::add_filter`](crate::Io::add_filter). Implement this trait directly
43/// only when wrapping or replacing a complete chain.
44pub trait Filter: 'static {
45    /// Returns type-indexed information exposed by this chain.
46    fn query(&self, id: any::TypeId) -> Option<Box<dyn any::Any>>;
47
48    /// Processes incoming data from the transport toward the application.
49    fn process_read_buf(&self, ctx: &mut FilterCtx<'_>) -> io::Result<()>;
50
51    /// Processes outgoing data from the application toward the transport.
52    fn process_write_buf(&self, ctx: &mut FilterCtx<'_>) -> io::Result<()>;
53
54    /// Performs graceful shutdown from the outermost layer toward the
55    /// transport.
56    fn shutdown(&self, ctx: &mut FilterCtx<'_>) -> io::Result<Poll<()>>;
57
58    /// Checks whether the chain is ready to process more input.
59    ///
60    /// This is polled by the transport read task only, a chain that is not
61    /// ready pauses transport reads until it wakes the task given in `cx`. The
62    /// dispatcher is notified when the pause starts and when it ends, see
63    /// [`IoRef::is_filter_paused`](crate::IoRef::is_filter_paused). Once the
64    /// chain is ready again, input and output it holds are processed again
65    /// without waiting for new transport input. A chain that stops being ready
66    /// between polls is only observed by the next poll, it can wake the task
67    /// given to the previous one.
68    ///
69    /// Transport writes are not paused, output that reached the transport is
70    /// always delivered. A filter that is not ready to produce output keeps it
71    /// in its own buffers instead, see
72    /// [`FilterLayer::process_write_buf`]. A filter that waits for input from
73    /// the peer, for example during a TLS handshake, must not report `Pending`
74    /// here, that input would never be read.
75    ///
76    /// Graceful shutdown and its deadline do not depend on the chain being
77    /// ready. An error ends the connection like any filter error: the chain
78    /// is not called again and its shutdown is skipped, output that reached
79    /// the transport is still delivered within the shutdown deadline.
80    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
81}
82
83/// Transport read readiness as decided by the io state, without the filter
84/// chain.
85pub(crate) fn read_readiness(st: &IoState) -> Poll<Readiness> {
86    if st.flags.is_force_closing() {
87        // Only an explicit `IoRef::terminate()` aborts the connection. A
88        // transport failure or an expired shutdown deadline end the
89        // connection too, but the transport still closes it gracefully.
90        Poll::Ready(Readiness::Terminate)
91    } else if st.flags.is_aborted() {
92        // The connection ended because of a failure, so no further input
93        // can be used; the transport closes it gracefully.
94        Poll::Ready(Readiness::Close)
95    } else if st.flags.is_read_eof() {
96        // The transport read side is closed, no further input can
97        // arrive. This outranks filter shutdown below: a filter that
98        // waits for input would otherwise keep the transport polling a
99        // closed read side.
100        Poll::Pending
101    } else if st.flags.is_stopping() {
102        // Transport shutdown phase. The filters are done, so no further
103        // input can be used and the read task pauses. The receive queue
104        // is drained by the transport itself, just before it closes the
105        // connection.
106        Poll::Pending
107    } else if st.flags.is_stopping_filters() {
108        // A filter may still need input to complete its shutdown, so
109        // keep reading even though the application paused reads.
110        Poll::Ready(Readiness::Ready)
111    } else if st.flags.is_read_paused_or_backpressure() || st.flags.is_read_wr_backpressure() {
112        // read buffer is full or is not processed by dispatcher yet,
113        // or output produced by reading has not drained
114        Poll::Pending
115    } else {
116        Poll::Ready(Readiness::Ready)
117    }
118}
119
120/// Transport write readiness as decided by the io state, without the filter
121/// chain.
122pub(crate) fn write_readiness(st: &IoState) -> Poll<Readiness> {
123    if st.flags.is_force_closing() {
124        // see `read_readiness`
125        Poll::Ready(Readiness::Terminate)
126    } else if st.flags.is_aborted() {
127        // The connection ended because of a failure, so there is nothing
128        // left to drain; the transport closes it gracefully.
129        Poll::Ready(Readiness::Close)
130    } else if st.flags.is_stopping() {
131        // Transport shutdown phase. Buffered output is drained into the
132        // transport first; `Readiness::Close` is reported only once
133        // nothing is left to write. Output a filter holds back pauses the
134        // write task, it waits for the shutdown deadline then.
135        if st.buffer.write_dst_size() != 0
136            || (st.buffer.write_buf_size() != 0 && !st.flags.is_write_paused())
137        {
138            Poll::Ready(Readiness::Ready)
139        } else if st.buffer.write_buf_size() != 0 || st.wr_inflight.get() != 0 {
140            // the transport still holds output that has not reached
141            // the peer, its completion wakes the write task
142            Poll::Pending
143        } else {
144            Poll::Ready(Readiness::Close)
145        }
146    } else if st.flags.is_write_paused() {
147        Poll::Pending
148    } else {
149        Poll::Ready(Readiness::Ready)
150    }
151}
152
153impl Filter for Base {
154    fn query(&self, id: any::TypeId) -> Option<Box<dyn any::Any>> {
155        if let Some(hnd) = self.0.0.handle.take() {
156            let res = hnd.query(id);
157            self.0.restore_handle(hnd);
158            res
159        } else {
160            None
161        }
162    }
163
164    #[inline]
165    fn poll_ready(&self, _: &mut Context<'_>) -> Poll<io::Result<()>> {
166        Poll::Ready(Ok(()))
167    }
168
169    #[inline]
170    fn process_read_buf(&self, _: &mut FilterCtx<'_>) -> io::Result<()> {
171        Ok(())
172    }
173
174    #[inline]
175    fn process_write_buf(&self, _: &mut FilterCtx<'_>) -> io::Result<()> {
176        Ok(())
177    }
178
179    #[inline]
180    fn shutdown(&self, _: &mut FilterCtx<'_>) -> io::Result<Poll<()>> {
181        Ok(Poll::Ready(()))
182    }
183}
184
185impl<F, L> Filter for Layer<F, L>
186where
187    F: FilterLayer,
188    L: Filter,
189{
190    #[inline]
191    fn query(&self, id: any::TypeId) -> Option<Box<dyn any::Any>> {
192        self.0.query(id).or_else(|| self.1.query(id))
193    }
194
195    #[inline]
196    fn shutdown(&self, ctx: &mut FilterCtx<'_>) -> io::Result<Poll<()>> {
197        if !self.2.get() {
198            if ctx.with_buffer(|buf| self.0.shutdown(buf))?.is_ready() {
199                self.process_write_buf(ctx)?;
200                self.2.set(true);
201
202                // The layer is done and its write buffer won't be processed
203                // again, retained output would be lost silently.
204                let lost = ctx.clear_write_buf();
205                if lost != 0 {
206                    return Err(io::Error::other(format!(
207                        "filter layer retained {lost} unwritten bytes at shutdown"
208                    )));
209                }
210            } else {
211                // Output produced by this filter's shutdown sits in the buffer
212                // of the inner filter, which only runs its write processing
213                // here, so move it towards the transport while waiting.
214                ctx.with_next(|ctx| self.1.process_write_buf(ctx))?;
215                return Ok(Poll::Pending);
216            }
217        }
218        ctx.with_next(|ctx| self.1.shutdown(ctx))
219    }
220
221    #[inline]
222    fn process_read_buf(&self, ctx: &mut FilterCtx<'_>) -> io::Result<()> {
223        ctx.with_next(|ctx| self.1.process_read_buf(ctx))?;
224        if self.2.get() {
225            Ok(())
226        } else {
227            ctx.with_buffer(|buf| self.0.process_read_buf(buf))
228        }
229    }
230
231    #[inline]
232    fn process_write_buf(&self, ctx: &mut FilterCtx<'_>) -> io::Result<()> {
233        if !self.2.get() {
234            ctx.with_buffer(|buf| self.0.process_write_buf(buf))?;
235        }
236        ctx.with_next(|ctx| self.1.process_write_buf(ctx))
237    }
238
239    #[inline]
240    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
241        self.1.poll_ready(cx)
242    }
243}
244
245impl Filter for NullFilter {
246    #[inline]
247    fn query(&self, _: any::TypeId) -> Option<Box<dyn any::Any>> {
248        None
249    }
250
251    // The filter chain is gone once `Io` has been dropped, `IoContext`
252    // reports the connection closed then and does not poll the chain.
253    #[inline]
254    fn poll_ready(&self, _: &mut Context<'_>) -> Poll<io::Result<()>> {
255        Poll::Ready(Ok(()))
256    }
257
258    #[inline]
259    fn process_read_buf(&self, _: &mut FilterCtx<'_>) -> io::Result<()> {
260        Ok(())
261    }
262
263    #[inline]
264    fn process_write_buf(&self, _: &mut FilterCtx<'_>) -> io::Result<()> {
265        Ok(())
266    }
267
268    #[inline]
269    fn shutdown(&self, _: &mut FilterCtx<'_>) -> io::Result<Poll<()>> {
270        Ok(Poll::Ready(()))
271    }
272}