Skip to main content

ntex_io/
ctx.rs

1use std::{fmt, io, task::Context, task::Poll};
2
3use ntex_bytes::{BytePages, BytesMut};
4use ntex_util::time::{Seconds, sleep};
5
6use crate::filter::{read_readiness, write_readiness};
7use crate::{Flags, Id, IoRef, IoTaskStatus, Readiness, io::IoState};
8
9/// Connection context shared with transport read and write tasks.
10///
11/// Transport implementations obtain buffers from this context, perform
12/// nonblocking I/O, and return completion through
13/// [`release_read_buf`](Self::release_read_buf) and
14/// [`update_write_status`](Self::update_write_status). Their return value tells
15/// the task whether to continue, pause until notified, or stop.
16///
17/// # Shutdown
18///
19/// A transport task runs until [`poll_read_ready`](Self::poll_read_ready) or
20/// [`poll_write_ready`](Self::poll_write_ready) reports [`Readiness::Close`] or
21/// [`Readiness::Terminate`], or until a status update returns
22/// [`IoTaskStatus::Stop`]. All of those imply that the connection is already
23/// closing or closed.
24///
25/// Graceful shutdown runs in two phases. In the first the filters shut down
26/// while both directions stay open. In the second, buffered output is drained
27/// into the transport while the read side is paused;
28/// [`Readiness::Close`] is reported only once nothing is left to write. A
29/// single shutdown timeout bounds both phases. If it elapses during filter
30/// shutdown, that phase is skipped and transport shutdown begins. If it
31/// elapses during transport shutdown, the connection closes and any remaining
32/// output is discarded.
33///
34/// So by the time the loop exits there is nothing left to drain, whether the
35/// connection was shut down gracefully or terminated. A task must never attempt
36/// a final flush on the way out; it should release the transport immediately
37/// and report the outcome through [`stopped`](Self::stopped). The two variants
38/// differ only in how the transport is released: [`Readiness::Close`] closes
39/// both directions gracefully, while [`Readiness::Terminate`] skips the
40/// graceful close so that an aborted connection stays distinguishable from one
41/// that ended normally. `Terminate` is reported for an explicit
42/// [`IoRef::terminate`](crate::IoRef::terminate), and when [`Io`](crate::Io) is
43/// dropped while output it accepted has not reached the transport, because the
44/// filter chain goes away with it and that output can never be delivered. Every
45/// other way a connection can end, an expired shutdown timeout included,
46/// reports `Close`.
47// `repr(transparent)` is required by `IoContext::from_ref`.
48#[repr(transparent)]
49pub struct IoContext(IoRef);
50
51impl IoContext {
52    pub(crate) fn new(io: IoRef) -> Self {
53        Self(io)
54    }
55
56    /// Views an `IoRef` as an `IoContext` without cloning it.
57    pub(crate) fn from_ref(io: &IoRef) -> &Self {
58        // SAFETY: `IoContext` is `repr(transparent)` over `IoRef`
59        unsafe { &*std::ptr::from_ref(io).cast::<IoContext>() }
60    }
61
62    fn st(&self) -> &IoState {
63        &self.0.0
64    }
65
66    #[inline]
67    /// Gets the ID.
68    pub fn id(&self) -> Id {
69        self.0.id()
70    }
71
72    #[inline]
73    /// Gets the I/O tag.
74    pub fn tag(&self) -> &'static str {
75        self.0.tag()
76    }
77
78    /// Returns the tracker charged with the read buffers of the connection.
79    ///
80    /// Read buffers a transport allocates itself should be charged to it
81    /// with [`BytesMut::set_tracker`]. Returns `None` if
82    /// [`BufTracker::Disabled`](crate::BufTracker) is configured.
83    #[cfg(feature = "tracker")]
84    #[cfg_attr(docsrs, doc(cfg(feature = "tracker")))]
85    #[must_use]
86    pub fn buf_tracker(&self) -> Option<&ntex_bytes::BytesTracker> {
87        self.st().buf_tracker()
88    }
89
90    #[doc(hidden)]
91    /// Gets the state flags. (for debug purpose only)
92    pub fn flags(&self) -> Flags {
93        self.0.flags()
94    }
95
96    #[inline]
97    /// Gets the configured shutdown timeout.
98    ///
99    /// A backend whose own teardown can stall, such as one waiting for
100    /// cancelled operations to complete, can bound it with this, as the
101    /// graceful shutdown before it is bounded.
102    pub fn shutdown_timeout(&self) -> Seconds {
103        self.0.cfg().shutdown_timeout()
104    }
105
106    #[inline]
107    /// Checks readiness for read operations.
108    ///
109    /// Resolves to [`Readiness::Ready`], [`Readiness::Close`] or
110    /// [`Readiness::Terminate`], or stays `Pending`. Reads continue through the
111    /// filter shutdown phase so that filters can complete theirs, and are
112    /// paused for the transport shutdown phase, so `Close` is resolved here
113    /// only once the connection is terminated.
114    ///
115    /// The read task drives the filter chain readiness, see
116    /// [`Filter::poll_ready`](crate::Filter::poll_ready). A chain that is not
117    /// ready pauses reads, see [`IoRef::is_filter_paused`]. The task must keep
118    /// polling this until it reports `Close` or `Terminate`, also while reads
119    /// are paused, so that the end of a pause is observed.
120    pub fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<Readiness> {
121        let st = self.st();
122        if st.flags.is_force_closing() {
123            // The filter chain is removed when `Io` is dropped, so the
124            // force-close decision is made here rather than in the chain: it
125            // has to survive that removal.
126            return Poll::Ready(Readiness::Terminate);
127        }
128        self.poll_filters_shutdown(cx);
129        if st.is_io_dropped() {
130            // The filter chain is gone, nothing is left that could process
131            // buffered data, the transport closes the connection gracefully.
132            // Output that never reached the peer forced a close above.
133            return Poll::Ready(Readiness::Close);
134        }
135
136        let res = read_readiness(st);
137        if matches!(res, Poll::Ready(Readiness::Close | Readiness::Terminate)) {
138            return res;
139        }
140        st.read_task.register(cx.waker());
141
142        // The filters are done in the transport shutdown phase
143        if st.flags.is_stopping() {
144            return res;
145        }
146
147        let ready = {
148            let _borrow = st.buffer.borrow();
149            self.0.filter().poll_ready(cx)
150        };
151        match ready {
152            Poll::Ready(Ok(())) => {
153                if st.flags.is_filter_paused() {
154                    log::trace!("{}: Filter is ready, resume", st.tag());
155                    st.flags.unset_filter_paused();
156                    st.wake_dispatch_task();
157                    self.resume_filters();
158                    return read_readiness(st);
159                }
160                res
161            }
162            Poll::Ready(Err(err)) => {
163                self.0.fail_filters(err);
164                read_readiness(st)
165            }
166            Poll::Pending => {
167                if !st.flags.is_filter_paused() {
168                    log::trace!("{}: Filter is not ready, pause", st.tag());
169                    st.flags.set_filter_paused();
170                    st.wake_dispatch_task();
171                }
172                Poll::Pending
173            }
174        }
175    }
176
177    /// Processes input and output the filter chain holds, once it is ready
178    /// again after a pause.
179    ///
180    /// The chain may hold either in any layer, including intermediate ones
181    /// whose buffers are not visible here, so both directions are processed
182    /// once without waiting for new transport input.
183    fn resume_filters(&self) {
184        let st = self.st();
185        let orig = st.buffer.read_dst_size();
186        let result = self.process_read_input(orig).and_then(|()| {
187            st.buffer.process_write_buf_force(&self.0)?;
188            self.0.consolidate_write_state(false)
189        });
190        let _ = self.read_task_status(result);
191    }
192
193    #[inline]
194    /// Checks readiness for write operations.
195    ///
196    /// Resolves to [`Readiness::Ready`], [`Readiness::Close`] or
197    /// [`Readiness::Terminate`], or stays `Pending`. Unlike the read path this
198    /// reports `Close` at the end of a graceful shutdown as well, once buffered
199    /// output has been drained, so the task must not flush again.
200    ///
201    /// Writes do not depend on the filter chain readiness, output that reached
202    /// the transport is always delivered.
203    pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<Readiness> {
204        let st = self.st();
205        if st.flags.is_force_closing() {
206            // see `poll_read_ready`
207            return Poll::Ready(Readiness::Terminate);
208        }
209        self.poll_shutdown_deadline(cx);
210        if st.is_io_dropped() {
211            // see `poll_read_ready`
212            return Poll::Ready(Readiness::Close);
213        }
214
215        let res = write_readiness(st);
216        if !matches!(res, Poll::Ready(Readiness::Close | Readiness::Terminate)) {
217            st.write_task.register(cx.waker());
218        }
219        res
220    }
221
222    /// Stops I/O processing without graceful filter shutdown.
223    ///
224    /// Pending application work is not drained. Unlike
225    /// [`IoRef::terminate`](crate::IoRef::terminate), this does not request an
226    /// aborted transport release: the transport observes
227    /// [`Readiness::Close`] and closes both directions gracefully. Call
228    /// [`stopped`](Self::stopped) afterwards, once transport teardown has
229    /// actually finished.
230    pub fn stop(&self, e: Option<io::Error>) {
231        self.st().terminate_connection(e);
232    }
233
234    /// Marks backend transport teardown as complete.
235    ///
236    /// Output that did not reach the transport is discarded, buffered input
237    /// stays readable.
238    pub fn stopped(&self, e: Option<io::Error>) {
239        self.st().stop_connection(e);
240    }
241
242    /// Returns the size of the input that the buffer from
243    /// [`take_read_buf`](Self::take_read_buf) already holds.
244    ///
245    /// This is unconsumed transport input that waits for more data, such as
246    /// a partial frame. A read into that buffer extends it in place. Any other
247    /// buffer released through [`release_read_buf`](Self::release_read_buf)
248    /// is appended to this input. Zero if there is no such input or the
249    /// dispatcher has not consumed the input yet, `take_read_buf` hands out
250    /// a buffer of its own then.
251    pub fn read_buf_size(&self) -> usize {
252        let st = self.st();
253        if st.flags.is_read_ready() {
254            0
255        } else {
256            st.buffer.read_src_size()
257        }
258    }
259
260    /// Takes a buffer for the next transport read.
261    ///
262    /// The returned buffer must be released exactly once through
263    /// [`release_read_buf`](Self::release_read_buf), even when the read
264    /// fails or would otherwise stop the task.
265    ///
266    /// This hands out a buffer of its own while the dispatcher still has input
267    /// to consume, because the read buffer is moved out of the io state until
268    /// it is released and the dispatcher would not find it. A transport whose
269    /// read completes without suspending can avoid that with
270    /// [`with_read_buf`](Self::with_read_buf).
271    pub fn take_read_buf(&self) -> BytesMut {
272        let st = self.st();
273
274        if st.flags.is_read_ready() {
275            // The dispatcher has not consumed the read buffer yet, so it must
276            // stay in place and the read goes to a buffer of its own.
277            st.get_read_buf()
278        } else if let Some(mut buf) = st.buffer.get_read_buf() {
279            buf.reserve_more();
280            buf
281        } else {
282            st.get_read_buf()
283        }
284    }
285
286    /// Releases a transport read buffer and reports the read result.
287    ///
288    /// This is the counterpart of [`take_read_buf`](Self::take_read_buf); every
289    /// buffer it hands out must come back here exactly once.
290    ///
291    /// `Poll::Ready(Ok(n))` reports that `n` bytes were appended to `buf`.
292    /// Zero marks the transport read side as closed and invokes the read filter
293    /// chain once with no new bytes. This lets filters emit final buffered data
294    /// or report truncated input. Further transport reads are parked, but
295    /// buffered input remains decodable and the write side remains usable until
296    /// graceful shutdown. `Poll::Ready(Err(_))` terminates the connection.
297    /// `Poll::Pending` returns the buffer after a nonblocking operation made no
298    /// progress or a submitted operation was canceled for reissue.
299    ///
300    /// The returned [`IoTaskStatus`] instructs the read task to continue
301    /// immediately, pause until notified, or stop.
302    pub fn release_read_buf(&self, buf: BytesMut, status: Poll<io::Result<usize>>) -> IoTaskStatus {
303        let st = self.st();
304        let orig = st.buffer.read_dst_size();
305
306        #[cfg(feature = "trace")]
307        log::trace!(
308            "{}: read-status == {status:?} orig:{orig:?} flags:{:?}",
309            st.tag(),
310            st.flags
311        );
312
313        // Transport shutdown phase, the filters are shut down and the
314        // connection is about to be closed. The read task is paused, but a read
315        // issued before the transition can still complete here; its input is
316        // discarded because nothing can consume it anymore.
317        if st.flags.is_stopping() {
318            let mut buf = buf;
319            buf.clear();
320            st.buffer.set_read_buf(buf);
321            stopping_read_status(st, &status)
322        } else {
323            let mut buf = buf;
324            track_read(st, &buf, &status);
325            if st.is_io_dropped() {
326                // the `Io` is gone, nothing can consume this input anymore
327                buf.clear();
328            }
329            // release read buffer
330            st.buffer.set_read_buf(buf);
331
332            self.process_read_status(orig, status)
333        }
334    }
335
336    /// Reads into the read buffer in place and reports the read result.
337    ///
338    /// This is the counterpart of [`take_read_buf`](Self::take_read_buf) and
339    /// [`release_read_buf`](Self::release_read_buf) for a transport whose
340    /// read completes without suspending. `f` reads into the buffer it is
341    /// given and reports the same status `release_read_buf` takes, with the
342    /// same meaning.
343    ///
344    /// The buffer is not moved out of the io state for the duration of the
345    /// call, so no temporary buffer is taken from the pool and no append is
346    /// needed to put the result back. A transport that keeps the buffer across
347    /// a suspension point cannot use this: the buffer would be missing while
348    /// the dispatcher looks for input, so it must take one of its own through
349    /// `take_read_buf` instead.
350    ///
351    /// `f` must not read from this io again. Nested read access is unsupported
352    /// and may terminate the connection or lose nested buffer changes.
353    pub fn with_read_buf<F>(&self, f: F) -> IoTaskStatus
354    where
355        F: FnOnce(&mut BytesMut) -> Poll<io::Result<usize>>,
356    {
357        let st = self.st();
358        let orig = st.buffer.read_dst_size();
359        let stopping = st.flags.is_stopping();
360        let discard = stopping || st.is_io_dropped();
361
362        let status = st.buffer.with_read_src(&self.0, |buf| {
363            buf.reserve_more();
364            let status = f(buf);
365            if !stopping {
366                track_read(st, buf, &status);
367            }
368            if discard {
369                // the filters are done or the `Io` is gone, nothing can
370                // consume this input anymore
371                buf.clear();
372            }
373            status
374        });
375
376        #[cfg(feature = "trace")]
377        log::trace!(
378            "{}: rd-status = {status:?} orig:{orig:?} flags:{:?}",
379            st.tag(),
380            st.flags
381        );
382
383        if stopping {
384            stopping_read_status(st, &status)
385        } else {
386            self.process_read_status(orig, status)
387        }
388    }
389
390    /// Processes input that reached the transport-facing read buffer.
391    ///
392    /// `orig` is the size of the destination read buffer before the read.
393    fn process_read_status(&self, orig: usize, status: Poll<io::Result<usize>>) -> IoTaskStatus {
394        let st = self.st();
395
396        // process read buf
397        let result = match status {
398            Poll::Pending => Ok(()),
399            Poll::Ready(Err(err)) => return self.read_failed(err),
400            Poll::Ready(Ok(nbytes)) => {
401                if nbytes == 0 && st.flags.is_read_eof() {
402                    // A clean eof is reported to the filter chain exactly
403                    // once, no matter how often the transport reports it.
404                    Ok(())
405                } else {
406                    if nbytes == 0 {
407                        st.flags.set_read_eof();
408                        st.wake_dispatch_task();
409                    }
410                    self.process_read_input(orig)
411                }
412            }
413        };
414        self.read_task_status(result)
415    }
416
417    /// Handles a transport read failure, returns the read task status.
418    fn read_failed(&self, err: io::Error) -> IoTaskStatus {
419        let st = self.st();
420        st.sync_read_buffered();
421
422        // A read failure while the filters are shutting down does not
423        // terminate the connection: the filter handshake cannot complete,
424        // but buffered output is still drained by the transport shutdown
425        // phase.
426        if st.flags.is_stopping_filters() {
427            // Output the filters produced before the failure, for example
428            // a close notification, may sit in an intermediate buffer that
429            // the transport shutdown phase does not drain.
430            if let Err(e) = st.buffer.process_write_buf_force(&self.0) {
431                self.0.fail_filters(e);
432            }
433            stop_filters(st, Some(err));
434            IoTaskStatus::Pause
435        } else {
436            st.terminate_connection(Some(err));
437            IoTaskStatus::Stop
438        }
439    }
440
441    /// Runs the read filter chain over buffered transport input.
442    fn process_read_input(&self, orig: usize) -> io::Result<()> {
443        let st = self.st();
444        st.buffer.process_read_buf(&self.0).and_then(|status| {
445            let size = st.buffer.read_dst_size();
446
447            // The destination read buffer has new data, wake up the dispatcher
448            if size > orig {
449                if st.is_rd_backpressure_needed(size) {
450                    log::trace!("{}: Read buf({size}), enable back-pressure", st.tag());
451                    st.set_read_ready_and_backpressure();
452                } else {
453                    st.flags.set_read_ready();
454                }
455                #[cfg(feature = "trace")]
456                log::trace!("{}: New {size} bytes available", st.tag());
457                st.wake_dispatch_task();
458            }
459
460            if st.flags.is_read_notify() {
461                // If the "notify" flag is set, we must wake the
462                // dispatcher task whenever data is read from the source.
463                st.wake_dispatch_task();
464                st.flags.set_read_notified();
465            }
466
467            // A filter may write data while processing reads, for
468            // example a TLS handshake record. Such output can land in
469            // an intermediate buffer that `write_buf_size()` does not
470            // account for, so the write chain is forced from the
471            // outermost layer to move it to the transport.
472            if status.wants_write {
473                st.buffer.process_write_buf_force(&self.0)?;
474                self.0.consolidate_write_state(false)?;
475
476                // Output produced by reading, for example replies to
477                // peer pings, must not grow without bound while the
478                // peer does not read. Reads pause until it drains or
479                // the dispatcher asks for more input.
480                if st.is_wr_backpressure_needed(st.transport_outstanding()) {
481                    log::trace!("{}: Write buf is full, pause reading", st.tag());
482                    st.flags.set_read_wr_backpressure();
483                }
484            } else if st.flags.is_write_paused() && st.buffer.is_write_held() {
485                // A filter holds output back, the input may be what it
486                // waits for. The write task paused on that output, so
487                // it is scheduled to let the filter retry.
488                self.0.consolidate_write_state(false)?;
489            }
490
491            // The input may be what a filter waits for to complete its
492            // shutdown, e.g. the peer's TLS close_notify, which is
493            // polled by the read task. Only actual input wakes it, a
494            // pending read would make the read task spin until the
495            // shutdown deadline.
496            if st.flags.is_shutting_down_filters() {
497                st.wake_read_task();
498            }
499            Ok(())
500        })
501    }
502
503    /// Completes read processing, returns the read task status.
504    ///
505    /// An error comes from the filter chain, see `IoRef::fail_filters`.
506    fn read_task_status(&self, result: io::Result<()>) -> IoTaskStatus {
507        let st = self.st();
508        st.sync_read_buffered();
509
510        if let Err(err) = result {
511            self.0.fail_filters(err);
512        }
513        if st.flags.is_aborted() {
514            IoTaskStatus::Stop
515        } else if st.flags.is_stopping()
516            || st.flags.is_read_eof()
517            || st.flags.is_read_paused_or_backpressure()
518            || st.flags.is_filter_paused()
519            || (st.flags.is_read_wr_backpressure() && !st.flags.is_stopping_filters())
520        {
521            IoTaskStatus::Pause
522        } else {
523            IoTaskStatus::Io
524        }
525    }
526
527    /// Provides mutable access to the transport-facing write destination.
528    ///
529    /// This holds the encoded bytes that are ready to be written out.
530    ///
531    /// Pending filter output is processed before `f` is invoked. The transport
532    /// may write bytes out directly, or take ownership of pages and write them
533    /// later; any page it removes is counted as in-flight output until it is
534    /// either returned to this buffer or reported as written through
535    /// [`update_write_status`](Self::update_write_status).
536    ///
537    /// # Panics
538    ///
539    /// Panics if the closure accesses the transport-facing write buffer again.
540    pub fn with_write_dst<F, R>(&self, f: F) -> R
541    where
542        F: FnOnce(&mut BytePages) -> R,
543    {
544        let st = self.st();
545
546        // Write buffer processing may be delayed
547        if let Err(e) = st.buffer.process_write_buf(&self.0) {
548            self.0.fail_filters(e);
549        }
550
551        let (result, before, after) = st.buffer.with_write_dst_sizes(&self.0, f);
552        if st.is_output_discarded() {
553            // `f` stopped or aborted the connection, pages it took are gone
554            st.wr_inflight.set(0);
555            st.sync_write_buffered();
556        } else {
557            st.track_wr_inflight(before, after);
558            st.sync_write_buffered_for(after + st.wr_inflight.get() as usize);
559        }
560
561        result
562    }
563
564    /// Updates the write status.
565    ///
566    /// `Ok(n)` reports that the write attempt completed without error and that
567    /// `n` bytes reached the peer; `n` is zero when the attempt moved nothing.
568    /// Any page the transport is still holding stays counted as outstanding
569    /// output, so it must either be returned to the write buffer or reported
570    /// here. An error terminates the connection. The returned
571    /// [`IoTaskStatus`] instructs the write task to continue, pause until
572    /// notified, or stop.
573    pub fn update_write_status(&self, status: io::Result<usize>) -> IoTaskStatus {
574        let st = &self.st();
575
576        #[cfg(feature = "trace")]
577        log::trace!(
578            "{}: write-status == {status:?} buf:{} inflight:{} flags:{:?}",
579            st.tag(),
580            st.buffer.write_buf_size(),
581            st.wr_inflight.get(),
582            st.flags
583        );
584
585        match status {
586            Ok(written) => {
587                st.wr_inflight_written(written);
588                st.metrics().written(written);
589
590                // Output queued while the transport was writing has not been
591                // through the filter chain yet. It is processed here, so that
592                // only output a filter holds back stays out of the
593                // transport-facing buffer.
594                if !st.flags.is_filter_skipped()
595                    && st.buffer.write_dst_size() == 0
596                    && let Err(e) = st.buffer.process_write_buf(&self.0)
597                {
598                    self.0.fail_filters(e);
599                }
600                // Filter processing, here or in `with_write_dst`, may have
601                // grown the output. It is checked once the write attempt is
602                // accounted for, an eager write may have drained it already.
603                let (mut len, mut dst) = st.buffer.write_sizes();
604                let mut outstanding = len + st.wr_inflight.get() as usize;
605                if st.enable_wr_backpressure_for(outstanding) {
606                    (len, dst) = st.buffer.write_sizes();
607                    outstanding = len + st.wr_inflight.get() as usize;
608                }
609                st.sync_write_buffered_for(outstanding);
610
611                // A full flush completes once all output, including in-flight
612                // pages, reaches the peer. Write backpressure is released once
613                // outstanding output is below the threshold. Both are checked,
614                // the flush flag stays set if a full flush is cancelled
615                if (st.flags.is_write_flush() && outstanding == 0)
616                    || (st.flags.is_wr_backpressure()
617                        && st.should_disable_wr_backpressure(outstanding))
618                {
619                    st.wake_dispatch_task();
620                }
621
622                // Producers waiting for the write back-pressure release, the
623                // flag itself is released by the dispatcher. Repeated calls
624                // until then are cheap, a notified waiter's waker is consumed.
625                if st.flags.is_wr_backpressure() && st.should_disable_wr_backpressure(outstanding) {
626                    st.wake_write_waiters();
627                }
628
629                // Reads paused by their own output resume once it drains
630                if st.flags.is_read_wr_backpressure()
631                    && st.should_disable_wr_backpressure(st.transport_outstanding())
632                {
633                    st.flags.unset_read_wr_backpressure();
634                    st.wake_read_task();
635                }
636
637                if st.flags.is_aborted() {
638                    IoTaskStatus::Stop
639                } else if len == 0 {
640                    // Nothing left to submit, pause the write task. In-flight
641                    // pages are not actionable here, their completion wakes
642                    // the task again.
643                    st.flags.set_write_paused();
644                    if st.flags.is_stopping_filters() {
645                        st.wake_read_task();
646                    }
647                    if st.flags.is_stopping() && outstanding == 0 {
648                        // The transport shutdown phase ends once buffered
649                        // output is drained, but only `poll_write_ready`
650                        // reports that, so the write task has to run once more
651                        // to observe it. A backend that drives both directions
652                        // from a single task is covered by the read wake above,
653                        // one that splits them is not.
654                        st.wake_write_task();
655                    }
656                    IoTaskStatus::Pause
657                } else if dst == 0 && st.buffer.write_dst_size() == 0 {
658                    // A filter holds the output back, for example application
659                    // data during a TLS handshake, so the transport has
660                    // nothing to write. The write task pauses until new output
661                    // is queued or input lets the filter make progress, see
662                    // `process_read_status`. A cached non-zero `dst` stays
663                    // valid, only the write task drains that buffer.
664                    st.flags.set_write_paused();
665                    IoTaskStatus::Pause
666                } else {
667                    st.flags.unset_write_paused();
668                    IoTaskStatus::Io
669                }
670            }
671            Err(err) => {
672                st.terminate_connection(Some(err));
673                IoTaskStatus::Stop
674            }
675        }
676    }
677
678    /// Drives the filter shutdown phase.
679    ///
680    /// This is polled from [`poll_read_ready`](Self::poll_read_ready), so the
681    /// read task advances the phase, and does nothing unless it is active.
682    /// Both directions stay open here: a filter may emit its closing data and
683    /// still read the peer's.
684    ///
685    /// The phase ends once every filter reports ready and its output has
686    /// reached the transport, and the transport shutdown phase begins. It is
687    /// also ended early when the filters cannot finish: after a clean read EOF,
688    /// because no further input can arrive, which is a normal close rather than
689    /// an error; when reads are paused or back-pressured, which is reported as
690    /// a blocked shutdown; and when the shutdown timeout elapses. A filter
691    /// error skips the remaining filter shutdown, output that reached the
692    /// transport is still delivered.
693    ///
694    /// The deadline is kept once it has expired so that
695    /// [`poll_shutdown_deadline`](Self::poll_shutdown_deadline) sees it
696    /// expired, which is what makes one `shutdown_timeout` bound both
697    /// phases.
698    fn poll_filters_shutdown(&self, cx: &mut Context<'_>) {
699        let st = &self.st();
700        if !st.flags.is_shutting_down_filters() {
701            return;
702        }
703
704        // process filter shutdown
705        let ready = match st.buffer.process_shutdown(&self.0) {
706            Ok(Poll::Ready(())) => true,
707            Ok(Poll::Pending) => false,
708            Err(err) => {
709                self.0.fail_filters(err);
710                return;
711            }
712        };
713        if self.0.consolidate_write_state(true).is_err() {
714            return;
715        }
716
717        // all pending output has reached the transport
718        let flushed = st.flags.is_write_paused() && !st.flags.is_wr_send_scheduled();
719
720        #[cfg(feature = "trace")]
721        log::trace!(
722            "{}: shutdown filters, done:{ready:?} flushed:{flushed:?} wr-buf:{:?}, flags:{:?}",
723            st.tag(),
724            st.buffer.write_buf_size(),
725            st.flags,
726        );
727
728        // filters are shutdown and write task is paused
729        if ready && flushed {
730            st.filters_stopped();
731            return;
732        }
733
734        // After a clean read EOF no further input can arrive, so a filter that
735        // is waiting for the peer can never finish. The peer closing first is
736        // a normal close, so this is not reported as an error.
737        let eof = !ready && st.flags.is_read_eof();
738
739        // If the read buffer is not consumed it is unlikely that the filter
740        // will ever complete its shutdown. Back-pressure counts on its own,
741        // even once the dispatcher has taken the buffered input: reads pause
742        // under it, so the transport would neither read the input the filter
743        // waits for nor arm read interest for it.
744        let blocked =
745            !ready && !eof && (st.flags.is_read_paused() || st.flags.is_rd_backpressure());
746
747        // The filter shutdown cannot complete. Move on to the transport
748        // shutdown phase, which drains whatever output has been produced so far
749        // and then closes the connection.
750        if eof || blocked {
751            if eof {
752                log::debug!("{}: Peer closed before filter shutdown completed", st.tag());
753            }
754            stop_filters(st, blocked.then(blocked_err));
755            return;
756        }
757
758        // filter shutdown timeout
759        let timeout = st
760            .shutdown_timeout
761            .take()
762            .unwrap_or_else(|| sleep(st.cfg().shutdown_timeout()));
763        if timeout.poll_elapsed(cx).is_ready() {
764            stop_filters(
765                st,
766                Some(io::Error::new(
767                    io::ErrorKind::TimedOut,
768                    "filter shutdown timed out",
769                )),
770            );
771        }
772        // the deadline is put back even once it has elapsed, so that the
773        // transport shutdown phase sees it expired instead of starting a
774        // second one
775        st.shutdown_timeout.set(Some(timeout));
776    }
777
778    /// Polls the shutdown deadline during the transport shutdown phase.
779    ///
780    /// The deadline is created when filter shutdown starts and is not reset
781    /// here, so a single `shutdown_timeout` bounds both shutdown phases. When
782    /// it elapses the connection is terminated and any output that has not
783    /// reached the transport is lost.
784    fn poll_shutdown_deadline(&self, cx: &mut Context<'_>) {
785        let st = &self.st();
786        if !st.flags.is_stopping() {
787            return;
788        }
789
790        // Nothing is left to drain, so the connection closes cleanly on the
791        // next readiness check and the deadline does not apply. Without this
792        // the shutdown would be reported as timed out whenever the filter
793        // phase happened to consume the whole deadline.
794        if st.write_outstanding() == 0 {
795            return;
796        }
797
798        let timeout = st
799            .shutdown_timeout
800            .take()
801            .unwrap_or_else(|| sleep(st.cfg().shutdown_timeout()));
802        if timeout.poll_elapsed(cx).is_ready() {
803            let len = st.write_outstanding();
804            if len != 0 {
805                log::warn!(
806                    "{}: Shutdown timed out, discarding {len} bytes of buffered output",
807                    st.tag()
808                );
809            }
810            st.terminate_connection(Some(io::Error::new(
811                io::ErrorKind::TimedOut,
812                "io shutdown timed out",
813            )));
814        } else {
815            st.shutdown_timeout.set(Some(timeout));
816        }
817    }
818}
819
820fn blocked_err() -> io::Error {
821    io::Error::other("filter shutdown blocked by unread buffered data")
822}
823
824/// Leaves the filter shutdown phase after an incomplete shutdown.
825///
826/// Output that has not reached the transport is not lost: the transport
827/// shutdown phase drains it before closing the connection.
828///
829/// The error is recorded here rather than when the failure is first
830/// detected: while an error is set, `IoRef::consolidate_write_state()`
831/// short-circuits, which would stop the write buffer from draining.
832fn stop_filters(st: &IoState, err: Option<io::Error>) {
833    if let Some(err) = err {
834        st.set_shutdown_error(err);
835    }
836    st.filters_stopped();
837}
838
839/// Adapts the connection's read page size to a transport read.
840fn track_read(st: &IoState, buf: &BytesMut, status: &Poll<io::Result<usize>>) {
841    match status {
842        Poll::Ready(Ok(n)) => {
843            st.metrics().read(*n);
844            st.track_read(*n, *n != 0 && buf.len() == buf.capacity());
845        }
846        Poll::Pending => st.track_read(0, false),
847        Poll::Ready(Err(_)) => {}
848    }
849}
850
851/// Reports a read that completed during the transport shutdown phase.
852///
853/// Neither a clean eof nor an error terminates the connection: the write
854/// side keeps draining until it completes or the shutdown deadline elapses.
855fn stopping_read_status(st: &IoState, status: &Poll<io::Result<usize>>) -> IoTaskStatus {
856    match status {
857        Poll::Ready(Ok(n)) if *n != 0 => IoTaskStatus::Io,
858        Poll::Ready(_) => {
859            st.flags.set_read_eof();
860            IoTaskStatus::Pause
861        }
862        Poll::Pending => IoTaskStatus::Pause,
863    }
864}
865
866impl Clone for IoContext {
867    fn clone(&self) -> Self {
868        Self(self.0.clone())
869    }
870}
871
872impl fmt::Debug for IoContext {
873    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
874        f.debug_struct("IoContext").field("io", &self.0).finish()
875    }
876}
877
878#[cfg(test)]
879mod tests {
880    use super::*;
881    use crate::{FilterBuf, FilterLayer, Io, testing::IoTest};
882    use ntex_util::future::lazy;
883
884    /// STATEMENT: An `IoContext` exposes an assigned connection ID and identifiable debug output.
885    ///
886    /// HOW:
887    /// - Build a context from a test connection, access its flags, and check its ID and formatting.
888    #[ntex::test]
889    async fn ctx_basics() {
890        let (_, server) = IoTest::create();
891
892        let state = Io::from(server);
893        let ctx = IoContext::new(state.get_ref());
894        let _ = ctx.flags();
895        assert_ne!(ctx.id(), Id::default());
896        assert!(format!("{ctx:?}").contains("IoContext"));
897    }
898
899    /// STATEMENT: A pending transport read does not signal EOF, unlike a successful zero-byte read.
900    ///
901    /// HOW:
902    /// - Release a read buffer with `Poll::Pending` and check the reader still waits.
903    /// - Release a zero-byte completion and verify paused transport reads and application EOF.
904    #[ntex::test]
905    async fn pending_read_completion_is_not_eof() {
906        let (_, server) = IoTest::create();
907        let state = Io::from(server);
908        let ctx = IoContext::new(state.get_ref());
909
910        assert!(lazy(|cx| state.poll_read_more(cx)).await.is_pending());
911        assert_ne!(
912            ctx.release_read_buf(ctx.take_read_buf(), Poll::Pending),
913            IoTaskStatus::Stop
914        );
915        assert!(lazy(|cx| state.poll_read_more(cx)).await.is_pending());
916
917        assert_eq!(
918            ctx.release_read_buf(ctx.take_read_buf(), Poll::Ready(Ok(0))),
919            IoTaskStatus::Pause
920        );
921        assert!(matches!(
922            lazy(|cx| state.poll_read_more(cx)).await,
923            Poll::Ready(Ok(None))
924        ));
925    }
926
927    #[derive(Debug)]
928    struct FinishOnEof;
929
930    impl FilterLayer for FinishOnEof {
931        fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
932            if buf.io().is_read_eof() {
933                buf.with_read_buffers(|_, dst| dst.extend_from_slice(b"final"));
934            }
935            Ok(())
936        }
937
938        fn process_write_buf(&self, _: &FilterBuf<'_>) -> io::Result<()> {
939            Ok(())
940        }
941    }
942
943    /// STATEMENT: EOF reports buffered input once without discarding unread bytes.
944    ///
945    /// HOW:
946    /// - Deliver five bytes followed by EOF and check the input-available notification.
947    /// - Access the buffer, verify subsequent EOF, and confirm the bytes remain available to decode.
948    #[ntex::test]
949    async fn eof_reports_available_input_once() {
950        let (_, server) = IoTest::create();
951        let state = Io::from(server);
952        let ctx = IoContext::new(state.get_ref());
953
954        // data arrives, then a clean eof
955        ctx.release_read_buf(BytesMut::copy_from_slice(b"12345"), Poll::Ready(Ok(5)));
956        ctx.release_read_buf(ctx.take_read_buf(), Poll::Ready(Ok(0)));
957
958        // the buffered input is reported once
959        assert!(matches!(
960            lazy(|cx| state.poll_read_more(cx)).await,
961            Poll::Ready(Ok(Some(())))
962        ));
963
964        // accessing the buffer marks the input as reported
965        assert_eq!(state.with_read_dst(|b| b.len()), 5);
966        assert!(matches!(
967            lazy(|cx| state.poll_read_more(cx)).await,
968            Poll::Ready(Ok(None))
969        ));
970
971        // "no further input" does not mean the read buffer is empty, the
972        // remaining bytes are still decodable
973        assert_eq!(state.with_read_dst(BytesMut::take), b"12345");
974    }
975
976    /// STATEMENT: Starting shutdown preserves unconsumed input and its readiness signal.
977    ///
978    /// HOW:
979    /// - Deliver bytes, begin shutdown, and check read readiness remains set.
980    /// - Verify the transport receives an empty buffer while application input stays intact.
981    #[ntex::test]
982    async fn shutdown_keeps_unconsumed_input_visible() {
983        let (_, server) = IoTest::create();
984        let state = Io::from(server);
985        let ctx = IoContext::new(state.get_ref());
986
987        // input arrives but the dispatcher has not consumed it yet
988        ctx.release_read_buf(BytesMut::copy_from_slice(b"12345"), Poll::Ready(Ok(5)));
989        assert!(ctx.flags().is_read_ready());
990
991        // starting a shutdown must not discard the "input available" signal
992        assert!(lazy(|cx| state.poll_shutdown(cx)).await.is_pending());
993        assert!(ctx.flags().is_read_ready());
994
995        // so the read task is handed a fresh buffer instead of the one the
996        // dispatcher still has to decode
997        assert!(ctx.take_read_buf().is_empty());
998        assert_eq!(state.with_read_dst(BytesMut::take), b"12345");
999    }
1000
1001    /// STATEMENT: Repeated clean EOF completions do not repeat filter EOF processing.
1002    ///
1003    /// HOW:
1004    /// - Report EOF three times through a filter that emits final bytes.
1005    /// - Check each completion pauses reads and the final bytes appear only once.
1006    #[ntex::test]
1007    async fn clean_eof_is_processed_by_filters_once() {
1008        let (_, server) = IoTest::create();
1009        let state = Io::from(server).add_filter(FinishOnEof);
1010        let ctx = IoContext::new(state.get_ref());
1011
1012        for _ in 0..3 {
1013            assert_eq!(
1014                ctx.release_read_buf(ctx.take_read_buf(), Poll::Ready(Ok(0))),
1015                IoTaskStatus::Pause
1016            );
1017            assert!(state.is_read_eof());
1018        }
1019        assert_eq!(state.with_read_dst(BytesMut::take), b"final");
1020    }
1021
1022    /// STATEMENT: Filters can emit final input at EOF before readers observe the terminal notification.
1023    ///
1024    /// HOW:
1025    /// - Register a read notification and report EOF through a filter that emits final bytes.
1026    /// - Check one input notification, subsequent EOF, and the final buffered data.
1027    #[ntex::test]
1028    async fn clean_eof_is_processed_by_filters() {
1029        let (_, server) = IoTest::create();
1030        let state = Io::from(server).add_filter(FinishOnEof);
1031        let ctx = IoContext::new(state.get_ref());
1032
1033        assert!(lazy(|cx| state.poll_read_notify(cx)).await.is_pending());
1034        assert_eq!(
1035            ctx.release_read_buf(ctx.take_read_buf(), Poll::Ready(Ok(0))),
1036            IoTaskStatus::Pause
1037        );
1038        assert!(state.is_read_eof());
1039        assert!(matches!(
1040            lazy(|cx| state.poll_read_notify(cx)).await,
1041            Poll::Ready(Ok(Some(())))
1042        ));
1043        assert!(matches!(
1044            lazy(|cx| state.poll_read_notify(cx)).await,
1045            Poll::Ready(Ok(None))
1046        ));
1047        assert_eq!(state.with_read_dst(BytesMut::take), b"final");
1048        assert!(matches!(
1049            lazy(|cx| state.poll_read_more(cx)).await,
1050            Poll::Ready(Ok(None))
1051        ));
1052    }
1053
1054    #[derive(Debug)]
1055    struct RejectEof;
1056
1057    impl FilterLayer for RejectEof {
1058        fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
1059            if buf.io().is_read_eof() {
1060                Err(io::Error::new(
1061                    io::ErrorKind::UnexpectedEof,
1062                    "truncated filtered stream",
1063                ))
1064            } else {
1065                Ok(())
1066            }
1067        }
1068
1069        fn process_write_buf(&self, _: &FilterBuf<'_>) -> io::Result<()> {
1070            Ok(())
1071        }
1072    }
1073
1074    /// STATEMENT: A filter error on clean EOF closes the connection and remains the shutdown error.
1075    ///
1076    /// HOW:
1077    /// - Report EOF through a rejecting filter and check inactive, non-terminating state.
1078    /// - Complete the requested transport close and verify the filter's error is returned.
1079    #[ntex::test]
1080    async fn clean_eof_filter_error_closes_connection() {
1081        let (_, server) = IoTest::create();
1082        let state = Io::from(server).add_filter(RejectEof);
1083        let ctx = IoContext::new(state.get_ref());
1084
1085        assert_eq!(
1086            ctx.release_read_buf(ctx.take_read_buf(), Poll::Ready(Ok(0))),
1087            IoTaskStatus::Pause
1088        );
1089        assert!(state.is_read_eof());
1090        assert!(!state.is_active());
1091        assert!(!state.flags().is_terminating());
1092
1093        // nothing to deliver, the transport closes the connection
1094        assert_eq!(
1095            lazy(|cx| ctx.poll_write_ready(cx)).await,
1096            Poll::Ready(Readiness::Close)
1097        );
1098        ctx.stopped(None);
1099        let err = state.shutdown().await.unwrap_err();
1100        assert_eq!(err.to_string(), "truncated filtered stream");
1101    }
1102
1103    /// STATEMENT: Graceful shutdown does not busy-poll a transport stalled on reads and writes.
1104    ///
1105    /// HOW:
1106    /// - Queue output on a counting stalled transport and request close.
1107    /// - Wait 100 milliseconds and assert fewer than ten additional transport polls.
1108    #[ntex::test]
1109    async fn filter_shutdown_does_not_spin_on_pending_read() {
1110        use crate::{Handle, IoStream};
1111        use std::{cell::Cell, future::poll_fn, rc::Rc};
1112
1113        // transport that never makes progress in either direction
1114        struct Stalled(Rc<Cell<usize>>);
1115
1116        impl IoStream for Stalled {
1117            fn start(self, ctx: IoContext) -> Box<dyn Handle> {
1118                let polls = self.0.clone();
1119                ntex_util::spawn(async move {
1120                    poll_fn(|cx| {
1121                        polls.set(polls.get() + 1);
1122                        if let Poll::Ready(Readiness::Ready) = ctx.poll_read_ready(cx) {
1123                            let _ = ctx.with_read_buf(|_| Poll::Pending);
1124                        }
1125                        match ctx.poll_write_ready(cx) {
1126                            Poll::Ready(Readiness::Ready) => {
1127                                let _ = ctx.update_write_status(Ok(0));
1128                                Poll::Pending
1129                            }
1130                            Poll::Ready(_) => Poll::Ready(()),
1131                            Poll::Pending => Poll::Pending,
1132                        }
1133                    })
1134                    .await;
1135                    ctx.stopped(None);
1136                });
1137                Box::new(Stalled(self.0))
1138            }
1139        }
1140
1141        impl Handle for Stalled {}
1142
1143        let polls = Rc::new(Cell::new(0));
1144        let io = Io::new(
1145            Stalled(polls.clone()),
1146            ntex_service::cfg::SharedCfg::default(),
1147        );
1148        io.encode_slice(b"data").unwrap();
1149        ntex_util::time::sleep(ntex_util::time::Millis(20)).await;
1150
1151        // graceful shutdown cannot flush the output, it waits for the deadline
1152        io.close();
1153        let start = polls.get();
1154        ntex_util::time::sleep(ntex_util::time::Millis(100)).await;
1155        assert!(
1156            polls.get() - start < 10,
1157            "io task polled {} times",
1158            polls.get() - start
1159        );
1160    }
1161
1162    /// Transport driven by the test through an `IoContext`.
1163    struct Manual;
1164
1165    impl crate::IoStream for Manual {
1166        fn start(self, _: IoContext) -> Box<dyn crate::Handle> {
1167            Box::new(Manual)
1168        }
1169    }
1170
1171    impl crate::Handle for Manual {}
1172
1173    /// STATEMENT: The transport reuses partially consumed read buffers and preserves their remaining bytes.
1174    ///
1175    /// HOW:
1176    /// - Deliver five bytes through a manual context and consume the first three.
1177    /// - Take the remaining buffer, reserve space, append another byte, and verify combined input.
1178    #[ntex::test]
1179    async fn take_read_buf_reuses_consumed_buffer() {
1180        let io = Io::new(Manual, ntex_service::cfg::SharedCfg::default());
1181        let ctx = IoContext::new(io.get_ref());
1182        assert_eq!(ctx.shutdown_timeout(), io.cfg().shutdown_timeout());
1183        assert!(io.query::<u32>().get().is_none());
1184
1185        let mut buf = ctx.take_read_buf();
1186        buf.extend_from_slice(b"12345");
1187        assert_eq!(
1188            ctx.release_read_buf(buf, Poll::Ready(Ok(5))),
1189            IoTaskStatus::Io
1190        );
1191        assert_eq!(io.with_read_dst(|b| b.split_to(3)), b"123");
1192
1193        // the dispatcher consumed the input, the partly filled buffer is
1194        // handed to the transport
1195        let mut buf = ctx.take_read_buf();
1196        assert_eq!(buf, b"45");
1197        buf.reserve_more();
1198        assert!(buf.capacity() - buf.len() >= io.get_ref().0.read_size().low());
1199        buf.extend_from_slice(b"6");
1200        assert_eq!(
1201            ctx.release_read_buf(buf, Poll::Ready(Ok(1))),
1202            IoTaskStatus::Io
1203        );
1204        assert_eq!(io.with_read_dst(BytesMut::take), b"456");
1205    }
1206
1207    /// STATEMENT: Transport shutdown discards input and treats read errors as EOF rather than termination.
1208    ///
1209    /// HOW:
1210    /// - Enter transport shutdown and deliver bytes through both read-buffer APIs.
1211    /// - Check no input reaches the application, pending reads pause, and an error marks EOF.
1212    /// - Complete the resulting close request and verify the connection is closed.
1213    #[ntex::test]
1214    async fn reads_are_discarded_in_transport_shutdown_phase() {
1215        let io = Io::new(Manual, ntex_service::cfg::SharedCfg::default());
1216        let ctx = IoContext::new(io.get_ref());
1217
1218        // no filter work and no output, the filter phase ends at once
1219        io.close();
1220        assert!(lazy(|cx| ctx.poll_read_ready(cx)).await.is_pending());
1221        assert!(ctx.flags().is_stopping());
1222
1223        // input is discarded, reads keep going until eof
1224        let mut buf = ctx.take_read_buf();
1225        buf.extend_from_slice(b"12345");
1226        assert_eq!(
1227            ctx.release_read_buf(buf, Poll::Ready(Ok(5))),
1228            IoTaskStatus::Io
1229        );
1230        assert_eq!(
1231            ctx.with_read_buf(|buf| {
1232                buf.extend_from_slice(b"678");
1233                Poll::Ready(Ok(3))
1234            }),
1235            IoTaskStatus::Io
1236        );
1237        assert_eq!(io.with_read_dst(|b| b.len()), 0);
1238
1239        assert_eq!(
1240            ctx.release_read_buf(ctx.take_read_buf(), Poll::Pending),
1241            IoTaskStatus::Pause
1242        );
1243        assert_eq!(ctx.with_read_buf(|_| Poll::Pending), IoTaskStatus::Pause);
1244        assert!(!io.is_read_eof());
1245
1246        // a read error does not terminate the connection
1247        assert_eq!(
1248            ctx.release_read_buf(
1249                ctx.take_read_buf(),
1250                Poll::Ready(Err(io::Error::other("err")))
1251            ),
1252            IoTaskStatus::Pause
1253        );
1254        assert!(io.is_read_eof());
1255        assert!(!ctx.flags().is_terminating());
1256
1257        assert_eq!(
1258            ctx.with_read_buf(|_| Poll::Ready(Ok(0))),
1259            IoTaskStatus::Pause
1260        );
1261
1262        // nothing left to drain, the transport closes the connection
1263        assert_eq!(
1264            lazy(|cx| ctx.poll_write_ready(cx)).await,
1265            Poll::Ready(Readiness::Close)
1266        );
1267        ctx.stopped(None);
1268        assert!(io.is_closed());
1269    }
1270
1271    #[derive(Debug)]
1272    struct FailShutdown;
1273
1274    impl FilterLayer for FailShutdown {
1275        fn process_read_buf(&self, _: &FilterBuf<'_>) -> io::Result<()> {
1276            Ok(())
1277        }
1278
1279        fn process_write_buf(&self, _: &FilterBuf<'_>) -> io::Result<()> {
1280            Ok(())
1281        }
1282
1283        fn shutdown(&self, _: &FilterBuf<'_>) -> io::Result<Poll<()>> {
1284            Err(io::Error::other("shutdown failed"))
1285        }
1286    }
1287
1288    /// STATEMENT: Filter shutdown failures proceed to transport close and retain the original error.
1289    ///
1290    /// HOW:
1291    /// - Close a manually driven connection whose filter rejects shutdown.
1292    /// - Check a non-terminating close request, report transport stop, and compare the shutdown error.
1293    #[ntex::test]
1294    async fn filter_shutdown_error_skips_to_transport_shutdown() {
1295        let io = Io::new(Manual, ntex_service::cfg::SharedCfg::default()).add_filter(FailShutdown);
1296        let ctx = IoContext::new(io.get_ref());
1297        // neither the layer nor the transport provide values
1298        assert!(io.query::<u32>().get().is_none());
1299
1300        io.close();
1301        let _ = lazy(|cx| ctx.poll_read_ready(cx)).await;
1302        assert!(!ctx.flags().is_terminating());
1303        assert_eq!(
1304            lazy(|cx| ctx.poll_write_ready(cx)).await,
1305            Poll::Ready(Readiness::Close)
1306        );
1307        ctx.stopped(None);
1308        let err = io.shutdown().await.unwrap_err();
1309        assert_eq!(err.to_string(), "shutdown failed");
1310    }
1311
1312    /// STATEMENT: Read completion through a cloned context stops after connection termination.
1313    ///
1314    /// HOW:
1315    /// - Clone a context, verify shared identity, stop it with an error, and release a successful read.
1316    /// - Check the cloned context returns `IoTaskStatus::Stop`.
1317    #[ntex::test]
1318    async fn read_after_termination_stops_read_task() {
1319        let io = Io::new(Manual, ntex_service::cfg::SharedCfg::default());
1320        let ctx = IoContext::new(io.get_ref());
1321        let ctx2 = ctx.clone();
1322        assert_eq!(ctx.id(), ctx2.id());
1323
1324        ctx.stop(Some(io::Error::other("failed")));
1325        let mut buf = ctx2.take_read_buf();
1326        buf.extend_from_slice(b"1");
1327        assert_eq!(
1328            ctx2.release_read_buf(buf, Poll::Ready(Ok(1))),
1329            IoTaskStatus::Stop
1330        );
1331    }
1332
1333    /// STATEMENT: A panic while starting the transport does not leak connection state.
1334    ///
1335    /// HOW:
1336    /// - Capture a weak state reference in a transport that panics during `start`.
1337    /// - Catch the panic and verify the weak reference can no longer be upgraded.
1338    #[test]
1339    fn start_panic_releases_state() {
1340        use std::{cell::RefCell, rc::Rc};
1341
1342        struct PanicStart(Rc<RefCell<Option<std::rc::Weak<crate::io::IoState>>>>);
1343
1344        impl crate::IoStream for PanicStart {
1345            fn start(self, ctx: IoContext) -> Box<dyn crate::Handle> {
1346                *self.0.borrow_mut() = Some(Rc::downgrade(&ctx.0.0));
1347                panic!("start failed");
1348            }
1349        }
1350
1351        let state = Rc::new(RefCell::new(None));
1352        let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1353            Io::from(PanicStart(state.clone()))
1354        }));
1355        assert!(res.is_err());
1356        let state = state.borrow_mut().take().unwrap();
1357        assert!(state.upgrade().is_none(), "state leaked");
1358    }
1359}