Skip to main content

ntex_dispatcher/
lib.rs

1//! Service dispatcher for framed I/O transports.
2//!
3//! [`Dispatcher`] combines an [`ntex_io`] transport, a codec implementing
4//! [`Decoder`] and [`Encoder`], and a [`Pipeline`]. Decoded frames reach the
5//! service as [`DispatchItem::Item`]. A successful service call returns either
6//! `Some(response)`, which the codec encodes into the transport's write buffer,
7//! or `None`, which produces no output.
8//!
9//! The same service handles write-backpressure [`Control`] events and
10//! [`DispatchItem::Stop`] notifications carrying a [`Reason`]. Transport,
11//! codec, and timeout failures are reported through these events rather than
12//! the dispatcher's `Result` error type; only service errors can be returned
13//! as `Err`.
14//!
15//! # Example
16//!
17//! An echo service can ignore control and stop events while returning each
18//! decoded byte buffer as its response. Run this future on the runtime owning
19//! the transport.
20//!
21//! ```
22//! use std::convert::Infallible;
23//!
24//! use ntex_codec::BytesCodec;
25//! use ntex_dispatcher::{DispatchItem, Dispatcher};
26//! use ntex_io::IoBoxed;
27//! use ntex_service::{Pipeline, fn_service};
28//!
29//! async fn echo(io: IoBoxed) -> Result<(), Infallible> {
30//!     let service = fn_service(async |event: DispatchItem<BytesCodec>| {
31//!         let response = match event {
32//!             DispatchItem::Item(bytes) => Some(bytes),
33//!             DispatchItem::Control(_) | DispatchItem::Stop(_) => None,
34//!         };
35//!         Ok::<_, Infallible>(response)
36//!     });
37//!
38//!     Dispatcher::new(io, BytesCodec, Pipeline::new((), service))
39//!         .max_inflight(16)
40//!         .await
41//! }
42//! ```
43//!
44//! # Termination outcome
45//!
46//! `Ok(())` therefore does not mean the connection ended cleanly: a service
47//! that returns `Ok(None)` for every [`DispatchItem::Stop`] also completes with
48//! `Ok(())` after a decoder, encoder, I/O, or timeout failure. To distinguish
49//! these outcomes, keep an [`IoRef`](ntex_io::IoRef) from
50//! [`Io::get_ref`](ntex_io::Io::get_ref) (also available on [`IoBoxed`])
51//! before constructing the dispatcher, then inspect
52//! [`IoRef::close_reason`](ntex_io::IoRef::close_reason) after awaiting it:
53//!
54//! | Stop reason | Recorded [`CloseReason`] | Typical meaning |
55//! |-------------|--------------------------|-----------------|
56//! | [`Reason::Service`] | [`CloseReason::Service`] | service failure or service-initiated stop |
57//! | [`Reason::Io`] with `None` | [`CloseReason::PeerGone`] | clean peer disconnect |
58//! | [`Reason::Io`] with `Some` | [`CloseReason::Io`] | transport failure or truncated frame |
59//! | [`Reason::Encoder`] | [`CloseReason::Encoder`] | encoding failure |
60//! | [`Reason::Decoder`] | [`CloseReason::Decoder`] | malformed peer input |
61//! | [`Reason::KeepAlive`] | [`CloseReason::KeepAlive`] | idle timeout |
62//! | [`Reason::ReadTimeout`] | [`CloseReason::ReadTimeout`] | frame read too slow |
63//! | [`Reason::WriteTimeout`] | [`CloseReason::WriteTimeout`] | output not drained in time |
64//!
65//! Only the first reported close reason is kept, so a reason set earlier by the
66//! application, a filter, or the transport (for example
67//! [`CloseReason::Shutdown`]) is not overwritten by the dispatcher.
68//!
69//! ```
70//! use std::convert::Infallible;
71//!
72//! use ntex_codec::BytesCodec;
73//! use ntex_dispatcher::{DispatchItem, Dispatcher};
74//! use ntex_io::{CloseReason, IoBoxed};
75//! use ntex_service::{Pipeline, fn_service};
76//!
77//! async fn run(io: IoBoxed) -> Result<(), &'static str> {
78//!     let service = fn_service(async |event: DispatchItem<BytesCodec>| {
79//!         Ok::<_, Infallible>(match event {
80//!             DispatchItem::Item(bytes) => Some(bytes),
81//!             _ => None,
82//!         })
83//!     });
84//!
85//!     let io_ref = io.get_ref();
86//!     Dispatcher::new(io, BytesCodec, Pipeline::new((), service))
87//!         .await
88//!         .map_err(|_| "service error")?;
89//!
90//!     match io_ref.close_reason() {
91//!         Some(CloseReason::Decoder) => Err("malformed input"),
92//!         Some(CloseReason::Encoder | CloseReason::Io) => Err("transport failure"),
93//!         Some(CloseReason::ReadTimeout | CloseReason::WriteTimeout) => Err("timeout"),
94//!         _ => Ok(()),
95//!     }
96//! }
97//! ```
98//!
99//! # Configuration
100//!
101//! Configure the transport with [`ntex_io::IoConfig`] before constructing the
102//! dispatcher:
103//!
104//! - [`set_keepalive_timeout`](ntex_io::IoConfig::set_keepalive_timeout)
105//!   bounds idle periods, not partial-frame reads or active service calls.
106//!   [`Dispatcher::keepalive_timeout`] overrides it for one dispatcher.
107//! - [`set_frame_read_rate`](ntex_io::IoConfig::set_frame_read_rate) bounds
108//!   progress on an incomplete frame, including the first frame before any
109//!   bytes arrive. Bytes consumed by the codec without producing a frame
110//!   still count as progress. [`Dispatcher::skip_first_frame_timeout`] lets
111//!   the peer stay silent until it starts the first frame.
112//! - [`set_write_backpressure`](ntex_io::IoConfig::set_write_backpressure)
113//!   sets the output watermark that pauses normal frame dispatch.
114//!   [`set_write_timeout`](ntex_io::IoConfig::set_write_timeout) limits how
115//!   long each backpressure period may last, not how long an individual
116//!   response may take.
117//! - [`set_shutdown_timeout`](ntex_io::IoConfig::set_shutdown_timeout) bounds
118//!   transport shutdown and, separately, the dispatcher's wait for readiness
119//!   during stop delivery. It is not a general deadline for service calls or
120//!   service shutdown; see [`Dispatcher`].
121//!
122//! Keep-alive, frame-read, and write timeouts are disabled by default.
123//! [`Dispatcher::max_inflight`] separately limits normal frame admission;
124//! it does not limit buffer sizes.
125
126#![forbid(unsafe_code)]
127#![deny(clippy::pedantic)]
128#![allow(clippy::cast_possible_truncation)]
129use std::task::{Context, Poll, ready};
130use std::time::Instant;
131use std::{cell::Cell, fmt, future::Future, future::poll_fn, io, mem, pin::Pin, rc::Rc};
132
133use ntex_codec::{Decoder, Encoder};
134use ntex_io::{CloseReason, Decoded, IoBoxed, IoStatusUpdate, RecvError};
135use ntex_service::pipeline::{Pipeline, PipelineCall};
136use ntex_util::{spawn_detached, time::Seconds, time::Sleep, time::sleep};
137
138mod timer;
139
140use self::timer::{Timer, Timers};
141
142type Response<U> = <U as Encoder>::Item;
143
144/// Event delivered to the dispatcher service.
145///
146/// The codec's [`Decoder::Item`] is the request payload, while its
147/// [`Encoder::Item`] is the response payload; these types need not match.
148/// Every variant is passed through the same pipeline and may produce a
149/// response, no response, or a service error.
150///
151/// Event calls can overlap. In particular, receiving [`Self::Stop`] does not
152/// mean earlier item calls have finished. See [`Dispatcher`] for readiness,
153/// response ordering, and shutdown behavior.
154pub enum DispatchItem<U: Encoder + Decoder> {
155    /// A frame decoded from the transport.
156    ///
157    /// Produced only when [`Decoder::decode`] returns `Some(item)`. The
158    /// decoder determines frame boundaries; a transport read need not
159    /// correspond to one service call.
160    Item(<U as Decoder>::Item),
161    /// A transport flow-control notification.
162    ///
163    /// These describe write-buffer pressure, not an incoming protocol frame.
164    Control(Control),
165    /// The dispatcher is stopping for the specified reason.
166    ///
167    /// The dispatcher attempts to deliver this through the pipeline before
168    /// shutting down the service. Delivery waits for service readiness and
169    /// may be handed to a background task if that wait exceeds the shutdown
170    /// timeout. A readiness error can prevent the service from receiving it.
171    Stop(Reason<U>),
172}
173
174#[derive(Copy, Clone, Debug, PartialEq, Eq)]
175/// Write-side flow-control notification.
176///
177/// Delivered as [`DispatchItem::Control`] through the regular service pipeline.
178/// Thresholds come from
179/// [`IoConfig::set_write_backpressure`](ntex_io::IoConfig::set_write_backpressure).
180/// These notifications do not themselves acknowledge delivery of a response
181/// to the peer.
182pub enum Control {
183    /// Write backpressure has been enabled.
184    ///
185    /// Normal frame decoding pauses while outstanding output is above the
186    /// transport's release threshold. Already-started service calls continue
187    /// and can produce additional output.
188    WBackPressureEnabled,
189    /// Write backpressure has been disabled.
190    ///
191    /// Enough output has drained to resume normal frame processing. Some
192    /// bytes may still be buffered; this is not a full-flush notification.
193    WBackPressureDisabled,
194}
195
196/// Reason a dispatcher is stopping.
197///
198/// Carried by [`DispatchItem::Stop`], rather than returned as the dispatcher's
199/// error type. The dispatcher also reports the corresponding
200/// [`ntex_io::CloseReason`] to the transport. An already-recorded transport
201/// close reason is not overwritten.
202///
203/// A stop caused by I/O, codec, or timeout failure can still yield `Ok(())`
204/// from the dispatcher if no service error is recorded. Inspect the stop
205/// event, or [`IoRef::close_reason`](ntex_io::IoRef::close_reason) after the
206/// dispatcher completes, when the application needs to distinguish those
207/// outcomes; see the [crate-level docs](crate#termination-outcome).
208pub enum Reason<U: Encoder + Decoder> {
209    /// A service readiness check or event call failed.
210    ///
211    /// The service error is retained for the dispatcher's result; this
212    /// notification does not contain or clone it.
213    Service,
214    /// The transport closed or failed.
215    ///
216    /// `None` indicates closure without an underlying I/O error, including
217    /// clean peer EOF. `Some(error)` contains a transport error or an
218    /// [`io::ErrorKind::UnexpectedEof`] synthesized when peer EOF leaves
219    /// undecodable bytes in the read buffer.
220    Io(Option<io::Error>),
221    /// A service response could not be encoded.
222    ///
223    /// Contains the error returned by [`Encoder::encode`].
224    Encoder(<U as Encoder>::Error),
225    /// Incoming bytes could not be decoded.
226    ///
227    /// Contains the error returned by [`Decoder::decode`].
228    Decoder(<U as Decoder>::Error),
229    /// The connection's idle timeout expired.
230    ///
231    /// Usually caused by the configured keep-alive timeout. An external
232    /// [`ntex_io::IoRef::notify_timeout`] notification can also produce this
233    /// reason when no service call is in flight, even if keep-alive is disabled.
234    KeepAlive,
235    /// Frame-read progress was insufficient or its cumulative budget expired.
236    ///
237    /// Controlled by
238    /// [`IoConfig::set_frame_read_rate`](ntex_io::IoConfig::set_frame_read_rate).
239    /// Completing a frame ends its read-rate tracking; subsequent idle time
240    /// is governed by keep-alive instead.
241    ReadTimeout,
242    /// Write backpressure stayed enabled for longer than the configured
243    /// write timeout.
244    ///
245    /// Small writes do not extend the deadline unless they release
246    /// backpressure. Once pressure is released, the timeout ends even if
247    /// some output remains buffered. See
248    /// [`IoConfig::set_write_timeout`](ntex_io::IoConfig::set_write_timeout).
249    WriteTimeout,
250}
251
252/// Future that dispatches decoded transport frames to a service.
253///
254/// Owns the transport, codec, and service pipeline supplied to [`Self::new`].
255/// The pipeline accepts [`DispatchItem<U>`] and returns
256/// `Option<<U as Encoder>::Item>`. Successful responses are encoded into the
257/// transport's write buffer; `None` produces no response.
258///
259/// Poll or await this local, non-`Send` future on the runtime owning the
260/// transport. Its output is `Result<(), Err>`; construction alone does not
261/// dispatch service events.
262///
263/// # Readiness and concurrency
264///
265/// Normal frame dispatch waits for pipeline readiness and space below the
266/// [`Self::max_inflight`] threshold. Service calls may overlap, and responses
267/// are encoded as calls complete rather than being reordered into request
268/// order. Use `max_inflight(1)` to serialize normal frame handling.
269///
270/// Write backpressure pauses frame decoding and produces
271/// [`Control::WBackPressureEnabled`]. When enough output drains, the dispatcher
272/// produces [`Control::WBackPressureDisabled`] and resumes normal processing.
273/// Pending calls continue during backpressure and may add more output.
274/// Control and stop events use the same readiness-aware pipeline as frames,
275/// but are not constrained by the normal frame-admission limit.
276///
277/// Pauses for service readiness or in-flight capacity suspend keep-alive and
278/// frame-read timers and reset the frame-read budget. A write-backpressure
279/// timeout continues running during these pauses. A paused transport filter
280/// suspends read-side and write timeouts instead, so filter delays are not
281/// charged to the peer.
282///
283/// # Stopping and shutdown
284///
285/// On a stop condition, the dispatcher attempts a [`DispatchItem::Stop`] call.
286/// That call can overlap earlier requests. Normally, after the stop call
287/// completes, the dispatcher drains all remaining service calls, waits for
288/// service shutdown, and then finishes transport shutdown. This drain also
289/// applies to transport failures; it has no general service-call deadline.
290///
291/// If pending stop delivery is blocked by readiness beyond the transport's
292/// [`shutdown_timeout`](ntex_io::IoConfig::shutdown_timeout), stop delivery,
293/// draining, and service shutdown continue in a background task while the
294/// dispatcher finishes transport shutdown. At this handoff, the response
295/// future held by the dispatcher is cancelled; already-detached calls
296/// continue to drain. The dispatcher may therefore complete before service
297/// shutdown, and errors reported after handoff are not returned by it.
298///
299/// Only service errors are returned as `Err`; other stop reasons are reported
300/// as events, so `Ok(())` may follow a codec, I/O, or timeout failure. Keep an
301/// [`IoRef`](ntex_io::IoRef) and inspect
302/// [`IoRef::close_reason`](ntex_io::IoRef::close_reason) after completion to
303/// classify the termination; see the [crate-level docs](crate#termination-outcome).
304/// A service error recorded before stop delivery takes precedence
305/// over a later stop-handler error. If none was recorded, a stop-handler error
306/// is returned when that call completes before handoff.
307///
308/// Dropping the dispatcher cancels the call futures it owns, but does not
309/// perform the normal stop-and-shutdown sequence or cancel already-detached
310/// calls. Drive the future to completion when orderly shutdown is required.
311pub struct Dispatcher<U, Err>
312where
313    U: Encoder + Decoder + 'static,
314    Err: 'static,
315{
316    inner: DispatcherInner<U, Err>,
317}
318
319// The dispatcher never pins its fields, all futures it polls are `Unpin`.
320impl<U: Encoder + Decoder, Err> Unpin for Dispatcher<U, Err> {}
321
322impl<U: Encoder + Decoder, Err> fmt::Debug for Dispatcher<U, Err> {
323    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
324        f.debug_struct("Dispatcher").finish_non_exhaustive()
325    }
326}
327
328type Service<U, Err> = Pipeline<DispatchItem<U>, Option<Response<U>>, Err>;
329
330struct Call<U: Encoder + Decoder, Err> {
331    // Drop the service future before releasing its count and waking shutdown.
332    fut: PipelineCall<DispatchItem<U>, Option<Response<U>>, Err>,
333    guard: CallGuard<U, Err>,
334}
335
336struct CallGuard<U: Encoder + Decoder, Err> {
337    shared: Rc<DispatcherShared<U, Err>>,
338    wake: bool,
339}
340
341impl<U: Encoder + Decoder, Err> Drop for CallGuard<U, Err> {
342    fn drop(&mut self) {
343        self.shared.inflight.set(self.shared.inflight.get() - 1);
344        if self.wake {
345            self.shared.io.notify_dispatcher();
346        }
347    }
348}
349
350impl<U: Encoder + Decoder, Err> fmt::Debug for Call<U, Err> {
351    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352        self.fut.fmt(f)
353    }
354}
355
356impl<U: Encoder + Decoder + 'static, Err: 'static> Future for Call<U, Err> {
357    type Output = ();
358
359    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
360        let this = self.get_mut();
361        let result = ready!(Pin::new(&mut this.fut).poll(cx));
362        this.guard.shared.handle_result(result);
363        this.guard.wake = false;
364        Poll::Ready(())
365    }
366}
367
368struct DispatcherInner<U, Err>
369where
370    U: Encoder + Decoder + 'static,
371{
372    st: DispatcherState<U, Err>,
373    error: Option<Err>,
374    shared: Rc<DispatcherShared<U, Err>>,
375    response: Option<Call<U, Err>>,
376    timers: Timers,
377    max_inflight: u32,
378    keepalive: Seconds,
379}
380
381pub(crate) struct DispatcherShared<U, Err>
382where
383    U: Encoder + Decoder,
384{
385    io: IoBoxed,
386    codec: U,
387    service: Service<U, Err>,
388    error: Cell<Option<DispatcherError<Err, <U as Encoder>::Error>>>,
389    inflight: Cell<u32>,
390}
391
392#[derive(Debug)]
393enum DispatcherState<U: Encoder + Decoder, Err> {
394    Processing,
395    Backpressure,
396    Stop(StopCall<U, Err>),
397    Shutdown,
398    ShutdownIo,
399}
400
401#[derive(Debug)]
402struct StopCall<U: Encoder + Decoder, Err> {
403    fut: Call<U, Err>,
404    // started while the stop call waits for service readiness
405    timeout: Option<Sleep>,
406}
407
408#[derive(Debug)]
409enum DispatcherError<S, U> {
410    Encoder(U),
411    Service(S),
412}
413
414enum PollService {
415    /// Write backpressure is enabled while the service is not ready.
416    Backpressure,
417    Continue,
418    Ready,
419}
420
421impl<U, Err> Dispatcher<U, Err>
422where
423    U: Decoder + Encoder + 'static,
424    Err: 'static,
425{
426    /// Creates a dispatcher for an I/O transport, codec, and service pipeline.
427    ///
428    /// Accepts any transport convertible to [`IoBoxed`], including an
429    /// [`ntex_io::Io`]. The codec must decode incoming frames and encode service
430    /// responses, which may have different item types.
431    ///
432    /// The pipeline must accept [`DispatchItem<U>`] and return
433    /// `Result<Option<<U as Encoder>::Item>, Err>`. It already owns its service
434    /// state and binding; this constructor does not bind the service again or
435    /// invoke it.
436    ///
437    /// Timeout and buffer policies come from the transport's
438    /// [`ntex_io::IoConfig`]. Construction clears any previous dispatcher timer
439    /// and starts first-frame read-rate monitoring immediately when configured,
440    /// before this future is first polled. Construct it on the runtime owning
441    /// the transport, then poll or await it to drive dispatch.
442    ///
443    /// [`Self::keepalive_timeout`] overrides the keep-alive timeout and
444    /// [`Self::skip_first_frame_timeout`] cancels first-frame monitoring for
445    /// this dispatcher only.
446    ///
447    /// The default in-flight threshold is [`u32::MAX`]. Use
448    /// [`Self::max_inflight`] to restrict normal frame admission.
449    pub fn new<Io>(io: Io, codec: U, service: Service<U, Err>) -> Dispatcher<U, Err>
450    where
451        IoBoxed: From<Io>,
452    {
453        let io = IoBoxed::from(io);
454        let keepalive = io.cfg().keepalive_timeout();
455        let shared = Rc::new(DispatcherShared {
456            io,
457            codec,
458            service,
459            error: Cell::new(None),
460            inflight: Cell::new(0),
461        });
462
463        Dispatcher {
464            inner: DispatcherInner {
465                timers: Timers::new(&shared.io),
466                shared,
467                response: None,
468                error: None,
469                st: DispatcherState::Processing,
470                max_inflight: u32::MAX,
471                keepalive,
472            },
473        }
474    }
475
476    #[must_use]
477    /// Limits normal frame admission by the number of in-flight service calls.
478    ///
479    /// While at least `max` calls are pending, the dispatcher pauses normal
480    /// frame dispatch. It resumes when the count falls below `max` and the
481    /// service is ready. Set this to `1` to serialize normal frame handling.
482    ///
483    /// Pending control and stop calls contribute to the count, but their
484    /// delivery can exceed this threshold so that shutdown and flow-control
485    /// processing can proceed. This is not a strict cap on all event calls or
486    /// on the transport's input and output buffers.
487    ///
488    /// The default is [`u32::MAX`], imposing no practical dispatcher-level
489    /// concurrency limit.
490    ///
491    /// # Panics
492    ///
493    /// Panics if `max` is zero.
494    pub fn max_inflight(mut self, max: u32) -> Self {
495        assert!(max > 0, "max_inflight must be greater than zero");
496        self.inner.max_inflight = max;
497        self
498    }
499
500    #[must_use]
501    /// Overrides the keep-alive timeout for this dispatcher.
502    ///
503    /// The default is the transport's
504    /// [`keepalive_timeout`](ntex_io::IoConfig::keepalive_timeout).
505    /// [`Seconds::ZERO`] disables keep-alive. The transport configuration
506    /// returned by [`IoRef::cfg`](ntex_io::IoRef::cfg) is not changed.
507    ///
508    /// Call this before the dispatcher is first polled.
509    pub fn keepalive_timeout(mut self, timeout: Seconds) -> Self {
510        self.inner.keepalive = timeout;
511        // keep-alive is armed again on the next poll
512        if matches!(
513            self.inner.timers.active,
514            Timer::KeepAlive | Timer::Suspended
515        ) {
516            self.inner.shared.io.stop_timer();
517            self.inner.timers.active = Timer::Stopped;
518            self.inner.timers.keepalive = None;
519        }
520        self
521    }
522
523    #[must_use]
524    /// Cancels the first-frame read-rate timer.
525    ///
526    /// With a configured
527    /// [`frame_read_rate`](ntex_io::IoConfig::frame_read_rate), a new
528    /// dispatcher requires the peer to start sending its first frame in time.
529    /// This option lets the peer stay silent after connection setup, for
530    /// example on a server-push protocol. The keep-alive timeout still applies
531    /// while the connection is idle, and the frame read rate applies once data
532    /// arrives.
533    ///
534    /// Has no effect when no frame read rate is configured. Call this before
535    /// the dispatcher is first polled.
536    pub fn skip_first_frame_timeout(mut self) -> Self {
537        self.inner.timers.skip_first_frame(&self.inner.shared.io);
538        self
539    }
540}
541
542impl<U, Err> DispatcherShared<U, Err>
543where
544    U: Encoder + Decoder + 'static,
545    Err: 'static,
546{
547    fn call(self: &Rc<Self>, item: DispatchItem<U>) -> Call<U, Err> {
548        self.inflight.set(self.inflight.get() + 1);
549        let guard = CallGuard {
550            shared: self.clone(),
551            wake: true,
552        };
553        Call {
554            fut: self.service.call_static(item),
555            guard,
556        }
557    }
558
559    fn handle_result(&self, item: Result<Option<Response<U>>, Err>) {
560        match item {
561            Ok(Some(val)) => {
562                if let Err(err) = self.io.encode(val, &self.codec) {
563                    self.error.set(Some(DispatcherError::Encoder(err)));
564                }
565            }
566            Err(err) => self.error.set(Some(DispatcherError::Service(err))),
567            Ok(None) => (),
568        }
569    }
570}
571
572impl<U, Err> Future for Dispatcher<U, Err>
573where
574    U: Decoder + Encoder + 'static,
575    Err: 'static,
576{
577    type Output = Result<(), Err>;
578
579    #[allow(clippy::too_many_lines)]
580    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
581        let inner = &mut self.get_mut().inner;
582
583        // handle service response future
584        if let Some(fut) = inner.response.as_mut()
585            && Pin::new(fut).poll(cx).is_ready()
586        {
587            inner.response = None;
588        }
589
590        loop {
591            match inner.st {
592                DispatcherState::Processing => {
593                    let item = match ready!(inner.poll_service(cx)) {
594                        PollService::Ready => {
595                            // decode incoming bytes if buffer is ready
596                            match inner.shared.io.poll_recv_decode(&inner.shared.codec, cx) {
597                                Ok(decoded) => {
598                                    inner.update_timer(&decoded);
599                                    if let Some(el) = decoded.item {
600                                        DispatchItem::Item(el)
601                                    } else {
602                                        return Poll::Pending;
603                                    }
604                                }
605                                Err(RecvError::Timeout) if inner.timers.active != Timer::Write => {
606                                    // input received together with a read timer wins over
607                                    // its expiry, the buffered input is decoded first
608                                    match inner.shared.io.decode_item(&inner.shared.codec) {
609                                        Ok(decoded) => {
610                                            let timer = inner.timers.active;
611                                            inner.update_timer(&decoded);
612                                            if let Some(el) = decoded.item {
613                                                DispatchItem::Item(el)
614                                            } else {
615                                                // a timer armed for the received input has
616                                                // not expired
617                                                if inner.timers.active == timer
618                                                    && let Err(ctl) = inner.handle_timeout()
619                                                {
620                                                    inner.st = inner.stop(ctl);
621                                                }
622                                                continue;
623                                            }
624                                        }
625                                        Err(err) => {
626                                            log::trace!(
627                                                "{}: Decoder error, stopping dispatcher: {:?}",
628                                                inner.shared.io.tag(),
629                                                err
630                                            );
631                                            inner.st = inner.stop(Reason::Decoder(err));
632                                            continue;
633                                        }
634                                    }
635                                }
636                                Err(RecvError::Timeout) => {
637                                    if let Err(ctl) = inner.handle_timeout() {
638                                        inner.st = inner.stop(ctl);
639                                    }
640                                    continue;
641                                }
642                                Err(RecvError::WriteBackpressure) => {
643                                    // instruct write task to notify dispatcher when data is flushed
644                                    inner.start_write_timer();
645                                    inner.st = DispatcherState::Backpressure;
646                                    DispatchItem::Control(Control::WBackPressureEnabled)
647                                }
648                                Err(RecvError::Decoder(err)) => {
649                                    log::trace!(
650                                        "{}: Decoder error, stopping dispatcher: {:?}",
651                                        inner.shared.io.tag(),
652                                        err
653                                    );
654                                    inner.st = inner.stop(Reason::Decoder(err));
655                                    continue;
656                                }
657                                Err(RecvError::PeerGone(err)) => {
658                                    log::trace!(
659                                        "{}: Peer is gone, stopping dispatcher: {:?}",
660                                        inner.shared.io.tag(),
661                                        err
662                                    );
663                                    inner.st = inner.stop(Reason::Io(err));
664                                    continue;
665                                }
666                            }
667                        }
668                        PollService::Backpressure => {
669                            DispatchItem::Control(Control::WBackPressureEnabled)
670                        }
671                        PollService::Continue => continue,
672                    };
673
674                    inner.call_service(cx, item);
675                }
676                // handle write back-pressure
677                DispatcherState::Backpressure => {
678                    match ready!(inner.poll_service(cx)) {
679                        PollService::Ready | PollService::Backpressure => {}
680                        PollService::Continue => continue,
681                    }
682
683                    // check write timeout
684                    if let Poll::Ready(IoStatusUpdate::Timeout) =
685                        inner.shared.io.poll_status_update(cx)
686                        && let Err(reason) = inner.handle_timeout()
687                    {
688                        inner.st = inner.stop(reason);
689                        continue;
690                    }
691                    // suspends or resumes the write timeout on a filter pause
692                    inner.start_write_timer();
693
694                    let item = if let Err(err) = ready!(inner.shared.io.poll_flush(cx, false)) {
695                        inner.st = inner.stop(Reason::Io(Some(err)));
696                        continue;
697                    } else {
698                        // Stops the write timeout when write backpressure is disabled.
699                        inner.stop_timer();
700                        inner.st = DispatcherState::Processing;
701                        DispatchItem::Control(Control::WBackPressureDisabled)
702                    };
703                    inner.call_service(cx, item);
704                }
705                // deliver stop to service
706                DispatcherState::Stop(ref mut stop) => {
707                    // service may relay on poll_ready for response results
708                    let ready = inner.shared.service.poll_ready(cx);
709
710                    if Pin::new(&mut stop.fut).poll(cx).is_ready() {
711                        // the dispatcher returns a service error from the stop call,
712                        // unless it is stopping because of an earlier one
713                        if let Some(DispatcherError::Service(err)) = inner.shared.error.take()
714                            && inner.error.is_none()
715                        {
716                            inner.error = Some(err);
717                        }
718                        inner.shared.io.stop_timer();
719                        inner.st = DispatcherState::Shutdown;
720                        continue;
721                    }
722                    if ready.is_ready() {
723                        return Poll::Pending;
724                    }
725
726                    // the stop item waits for service readiness, it is delivered
727                    // in the background and io is closed without waiting for it
728                    let timeout = stop
729                        .timeout
730                        .get_or_insert_with(|| sleep(inner.shared.io.cfg().shutdown_timeout()));
731                    ready!(timeout.poll_elapsed(cx));
732                    log::trace!(
733                        "{}: Service is not ready for stop, shutdown io",
734                        inner.shared.io.tag()
735                    );
736
737                    let DispatcherState::Stop(stop) =
738                        mem::replace(&mut inner.st, DispatcherState::ShutdownIo)
739                    else {
740                        unreachable!()
741                    };
742                    inner.shared.io.stop_timer();
743                    inner.response = None;
744
745                    // the task owns the readiness check from now on
746                    let shared = inner.shared.clone();
747                    let mut fut = Some(stop.fut);
748                    spawn_detached(poll_fn(move |cx| {
749                        let _ = shared.service.poll_ready(cx);
750                        if let Some(f) = fut.as_mut() {
751                            ready!(Pin::new(f).poll(cx));
752                            fut = None;
753                        }
754                        if shared.inflight.get() != 0 {
755                            shared.io.register_dispatch(cx);
756                            return Poll::Pending;
757                        }
758                        shared.service.poll_shutdown(cx)
759                    }));
760                }
761                // drain service responses and shutdown service
762                DispatcherState::Shutdown => {
763                    // service may relay on poll_ready for response results
764                    let _ = inner.shared.service.poll_ready(cx);
765
766                    if inner.shared.inflight.get() != 0 {
767                        inner.shared.io.register_dispatch(cx);
768                        return Poll::Pending;
769                    }
770
771                    ready!(inner.shared.service.poll_shutdown(cx));
772                    log::trace!(
773                        "{}: Service shutdown is completed, stop",
774                        inner.shared.io.tag()
775                    );
776                    inner.st = DispatcherState::ShutdownIo;
777                }
778                // shutdown io
779                DispatcherState::ShutdownIo => {
780                    let _ = ready!(inner.shared.io.poll_shutdown(cx));
781
782                    return Poll::Ready(if let Some(err) = inner.error.take() {
783                        Err(err)
784                    } else {
785                        Ok(())
786                    });
787                }
788            }
789        }
790    }
791}
792
793impl<U, Err> DispatcherInner<U, Err>
794where
795    U: Decoder + Encoder + 'static,
796    Err: 'static,
797{
798    fn stop(&self, reason: Reason<U>) -> DispatcherState<U, Err> {
799        self.shared.io.set_close_reason(match reason {
800            Reason::Service => CloseReason::Service,
801            Reason::Io(None) => CloseReason::PeerGone,
802            Reason::Io(Some(_)) => CloseReason::Io,
803            Reason::Encoder(_) => CloseReason::Encoder,
804            Reason::Decoder(_) => CloseReason::Decoder,
805            Reason::KeepAlive => CloseReason::KeepAlive,
806            Reason::ReadTimeout => CloseReason::ReadTimeout,
807            Reason::WriteTimeout => CloseReason::WriteTimeout,
808        });
809        DispatcherState::Stop(StopCall {
810            fut: self.shared.call(DispatchItem::Stop(reason)),
811            timeout: None,
812        })
813    }
814
815    fn call_service(&mut self, cx: &mut Context<'_>, item: DispatchItem<U>) {
816        let mut fut = self.shared.call(item);
817
818        // the first poll consumes the pipeline readiness checked by `poll_service()`
819        if Pin::new(&mut fut).poll(cx).is_ready() {
820            drop(fut);
821        } else if self.response.is_none() {
822            self.response = Some(fut);
823        } else {
824            let shared = self.shared.clone();
825            spawn_detached(async move {
826                fut.await;
827                shared.io.notify_dispatcher();
828            });
829        }
830    }
831
832    fn check_error(&mut self) -> PollService {
833        // check for errors
834        if let Some(err) = self.shared.error.take() {
835            log::trace!(
836                "{}: Error occurred, stopping dispatcher",
837                self.shared.io.tag()
838            );
839            match err {
840                DispatcherError::Encoder(err) => {
841                    self.st = self.stop(Reason::Encoder(err));
842                }
843                DispatcherError::Service(err) => {
844                    self.error = Some(err);
845                    self.st = self.stop(Reason::Service);
846                }
847            }
848            PollService::Continue
849        } else {
850            PollService::Ready
851        }
852    }
853
854    fn poll_service(&mut self, cx: &mut Context<'_>) -> Poll<PollService> {
855        // wait until an in-flight call completes and the service becomes ready
856        let ready = if self.shared.inflight.get() >= self.max_inflight {
857            Poll::Pending
858        } else {
859            self.shared.service.poll_ready(cx)
860        };
861        match ready {
862            Poll::Ready(Ok(())) => Poll::Ready(self.check_error()),
863            // pause io read task
864            Poll::Pending => {
865                log::trace!(
866                    "{}: Service is not ready, register dispatcher",
867                    self.shared.io.tag()
868                );
869
870                // the write timeout keeps running while the service is paused
871                if self.timers.active != Timer::Write {
872                    self.stop_timer();
873                }
874                self.timers.reset_read(self.shared.io.cfg());
875
876                match ready!(self.shared.io.poll_read_pause(cx)) {
877                    IoStatusUpdate::Timeout => {
878                        if let Err(reason) = self.handle_timeout() {
879                            log::trace!(
880                                "{}: Timeout during pause, stopping dispatcher: {:?}",
881                                self.shared.io.tag(),
882                                reason
883                            );
884                            self.st = self.stop(reason);
885                        }
886                        Poll::Ready(PollService::Continue)
887                    }
888                    // frames that were already received are dispatched once
889                    // the service is ready, as in the processing state
890                    IoStatusUpdate::PeerGone(_) if self.shared.io.read_dst_size() != 0 => {
891                        log::trace!(
892                            "{}: Peer is gone during pause, wait for service",
893                            self.shared.io.tag()
894                        );
895                        Poll::Pending
896                    }
897                    IoStatusUpdate::PeerGone(err) => {
898                        log::trace!(
899                            "{}: Peer is gone during pause, stopping dispatcher: {:?}",
900                            self.shared.io.tag(),
901                            err
902                        );
903                        self.st = self.stop(Reason::Io(err));
904                        Poll::Ready(PollService::Continue)
905                    }
906                    IoStatusUpdate::WriteBackpressure => {
907                        if !matches!(self.st, DispatcherState::Backpressure) {
908                            self.start_write_timer();
909                        }
910                        self.st = DispatcherState::Backpressure;
911                        Poll::Ready(PollService::Backpressure)
912                    }
913                }
914            }
915            // handle service readiness error
916            Poll::Ready(Err(err)) => {
917                log::trace!(
918                    "{}: Service readiness check failed, stopping",
919                    self.shared.io.tag()
920                );
921                self.st = self.stop(Reason::Service);
922                self.error = Some(err);
923                Poll::Ready(PollService::Continue)
924            }
925        }
926    }
927
928    /// Starts the write timeout when write backpressure is enabled.
929    ///
930    /// Frames are not decoded during backpressure, so read-side timers are
931    /// stopped when no write timeout is configured. The timeout does not run
932    /// while the filter chain is paused, it holds output back and the peer is
933    /// not charged for it. The timeout starts over once the chain resumes.
934    fn start_write_timer(&mut self) {
935        let timeout = self.shared.io.cfg().write_timeout();
936        if timeout.is_zero() || self.shared.io.is_filter_paused() {
937            self.stop_timer();
938        } else if self.timers.active != Timer::Write {
939            self.timers.active = Timer::Write;
940            self.shared.io.start_timer(timeout);
941        }
942    }
943
944    fn update_timer(&mut self, decoded: &Decoded<<U as Decoder>::Item>) {
945        let item = decoded.item.is_some();
946        self.timers.update_read(
947            self.shared.io.cfg(),
948            item,
949            decoded.remains as u32,
950            decoded.consumed as u32,
951        );
952
953        // the filter chain pauses reading, the peer is not charged for it
954        if !item && self.shared.io.is_filter_paused() {
955            if self.timers.active != Timer::Write {
956                self.stop_timer();
957            }
958            self.timers.reset_read(self.shared.io.cfg());
959            return;
960        }
961
962        // keep-alive and frame read timers do not apply while a frame is handled
963        let handling = item || self.shared.inflight.get() != 0;
964        let timer = self
965            .timers
966            .select(self.shared.io.cfg(), !self.keepalive.is_zero(), handling);
967        self.set_timer(timer);
968    }
969
970    /// Stops the dispatcher timer, if it is armed.
971    fn stop_timer(&mut self) {
972        if self.timers.active != Timer::Stopped {
973            self.timers.active = Timer::Stopped;
974            self.shared.io.stop_timer();
975        }
976    }
977
978    /// Arms the dispatcher timer for a read-side purpose, an armed timer
979    /// with the same purpose keeps running.
980    ///
981    /// The keep-alive timer is suspended instead of stopped, re-arming it is
982    /// cheaper than registering it again.
983    fn set_timer(&mut self, timer: Timer) {
984        if self.timers.active == timer {
985            return;
986        }
987        let keepalive = self.keepalive;
988        let io = &self.shared.io;
989        self.timers.active = match (self.timers.active, timer) {
990            (Timer::KeepAlive | Timer::Suspended, Timer::Stopped) => Timer::Suspended,
991            (_, Timer::KeepAlive) => {
992                log::trace!("{}: Start keep-alive timer {:?}", io.tag(), keepalive);
993                let hnd = io.start_timer(keepalive);
994                self.timers.keepalive = Some(hnd.instant());
995                Timer::KeepAlive
996            }
997            (_, Timer::FrameRead) if let Some(params) = io.cfg().frame_read_rate() => {
998                io.start_timer(params.timeout);
999                Timer::FrameRead
1000            }
1001            _ => {
1002                io.stop_timer();
1003                Timer::Stopped
1004            }
1005        };
1006    }
1007
1008    fn handle_timeout(&mut self) -> Result<(), Reason<U>> {
1009        match self.timers.active {
1010            Timer::FrameRead => {
1011                let (Some(params), Some(p)) = (
1012                    self.shared.io.cfg().frame_read_rate(),
1013                    self.timers.read.progress(),
1014                ) else {
1015                    self.timers.active = Timer::Stopped;
1016                    return Ok(());
1017                };
1018
1019                // read rate, start timer for next period
1020                if p.consumed > params.rate {
1021                    let total = p.consumed;
1022                    p.consumed = 0;
1023
1024                    if !params.max_timeout.is_zero() {
1025                        p.max_timeout = Seconds(p.max_timeout.0.saturating_sub(params.timeout.0));
1026                    }
1027
1028                    if params.max_timeout.is_zero() || !p.max_timeout.is_zero() {
1029                        log::trace!(
1030                            "{}: Frame read rate {:?}, extend timer",
1031                            self.shared.io.tag(),
1032                            total
1033                        );
1034                        self.shared.io.start_timer(params.timeout);
1035                        return Ok(());
1036                    }
1037                    log::trace!(
1038                        "{}: Max payload timeout has been reached",
1039                        self.shared.io.tag()
1040                    );
1041                }
1042                Err(Reason::ReadTimeout)
1043            }
1044            // backpressure can be released unnoticed while the service is paused
1045            Timer::Write if !self.shared.io.is_wr_backpressure() => {
1046                self.timers.active = Timer::Stopped;
1047                Ok(())
1048            }
1049            // the filter chain paused before the dispatcher noticed
1050            Timer::Write if self.shared.io.is_filter_paused() => {
1051                self.stop_timer();
1052                Ok(())
1053            }
1054            Timer::Write => {
1055                log::trace!(
1056                    "{}: Write backpressure timeout, stopping dispatcher",
1057                    self.shared.io.tag()
1058                );
1059                Err(Reason::WriteTimeout)
1060            }
1061            Timer::KeepAlive => {
1062                log::trace!(
1063                    "{}: Keep-alive error, stopping dispatcher",
1064                    self.shared.io.tag()
1065                );
1066                Err(Reason::KeepAlive)
1067            }
1068            // the suspended keep-alive timer has expired, a timeout before its
1069            // expiry is external
1070            Timer::Suspended
1071                if self
1072                    .timers
1073                    .keepalive
1074                    .is_none_or(|expiry| Instant::now() >= expiry) =>
1075            {
1076                self.timers.active = Timer::Stopped;
1077                Ok(())
1078            }
1079            // external timeout, applies to idle connection
1080            Timer::Stopped | Timer::Suspended if self.shared.inflight.get() == 0 => {
1081                log::trace!(
1082                    "{}: Idle timeout, stopping dispatcher",
1083                    self.shared.io.tag()
1084                );
1085                Err(Reason::KeepAlive)
1086            }
1087            Timer::Stopped | Timer::Suspended => Ok(()),
1088        }
1089    }
1090}
1091
1092impl<U> fmt::Debug for DispatchItem<U>
1093where
1094    U: Encoder + Decoder,
1095    <U as Decoder>::Item: fmt::Debug,
1096{
1097    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1098        match self {
1099            DispatchItem::Item(item) => f.debug_tuple("DispatchItem::Item").field(item).finish(),
1100            DispatchItem::Control(e) => f.debug_tuple("DispatchItem::Control").field(e).finish(),
1101            DispatchItem::Stop(e) => f.debug_tuple("DispatchItem::Stop").field(e).finish(),
1102        }
1103    }
1104}
1105
1106impl<U> fmt::Debug for Reason<U>
1107where
1108    U: Encoder + Decoder,
1109    <U as Encoder>::Error: fmt::Debug,
1110    <U as Decoder>::Error: fmt::Debug,
1111{
1112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1113        match self {
1114            Reason::Service => f.write_str("Reason::Service"),
1115            Reason::Io(err) => f.debug_tuple("Reason::Io").field(err).finish(),
1116            Reason::Encoder(err) => f.debug_tuple("Reason::Encoder").field(err).finish(),
1117            Reason::Decoder(err) => f.debug_tuple("Reason::Decoder").field(err).finish(),
1118            Reason::KeepAlive => f.write_str("Reason::KeepAlive"),
1119            Reason::ReadTimeout => f.write_str("Reason::ReadTimeout"),
1120            Reason::WriteTimeout => f.write_str("Reason::WriteTimeout"),
1121        }
1122    }
1123}
1124
1125#[cfg(test)]
1126#[allow(clippy::unused_async_trait_impl)]
1127#[path = "../tests/unit/dispatcher.rs"]
1128mod tests;