Skip to main content

Crate ntex_dispatcher

Crate ntex_dispatcher 

Source
Expand description

Service dispatcher for framed I/O transports.

Dispatcher combines an [ntex_io] transport, a codec implementing [Decoder] and [Encoder], and a [Pipeline]. Decoded frames reach the service as DispatchItem::Item. A successful service call returns either Some(response), which the codec encodes into the transport’s write buffer, or None, which produces no output.

The same service handles write-backpressure Control events and DispatchItem::Stop notifications carrying a Reason. Transport, codec, and timeout failures are reported through these events rather than the dispatcher’s Result error type; only service errors can be returned as Err.

§Example

An echo service can ignore control and stop events while returning each decoded byte buffer as its response. Run this future on the runtime owning the transport.

use std::convert::Infallible;

use ntex_codec::BytesCodec;
use ntex_dispatcher::{DispatchItem, Dispatcher};
use ntex_io::IoBoxed;
use ntex_service::{Pipeline, fn_service};

async fn echo(io: IoBoxed) -> Result<(), Infallible> {
    let service = fn_service(async |event: DispatchItem<BytesCodec>| {
        let response = match event {
            DispatchItem::Item(bytes) => Some(bytes),
            DispatchItem::Control(_) | DispatchItem::Stop(_) => None,
        };
        Ok::<_, Infallible>(response)
    });

    Dispatcher::new(io, BytesCodec, Pipeline::new((), service))
        .max_inflight(16)
        .await
}

§Termination outcome

Ok(()) therefore does not mean the connection ended cleanly: a service that returns Ok(None) for every DispatchItem::Stop also completes with Ok(()) after a decoder, encoder, I/O, or timeout failure. To distinguish these outcomes, keep an IoRef from Io::get_ref (also available on [IoBoxed]) before constructing the dispatcher, then inspect IoRef::close_reason after awaiting it:

Stop reasonRecorded [CloseReason]Typical meaning
Reason::Service[CloseReason::Service]service failure or service-initiated stop
Reason::Io with None[CloseReason::PeerGone]clean peer disconnect
Reason::Io with Some[CloseReason::Io]transport failure or truncated frame
Reason::Encoder[CloseReason::Encoder]encoding failure
Reason::Decoder[CloseReason::Decoder]malformed peer input
Reason::KeepAlive[CloseReason::KeepAlive]idle timeout
Reason::ReadTimeout[CloseReason::ReadTimeout]frame read too slow
Reason::WriteTimeout[CloseReason::WriteTimeout]output not drained in time

Only the first reported close reason is kept, so a reason set earlier by the application, a filter, or the transport (for example [CloseReason::Shutdown]) is not overwritten by the dispatcher.

use std::convert::Infallible;

use ntex_codec::BytesCodec;
use ntex_dispatcher::{DispatchItem, Dispatcher};
use ntex_io::{CloseReason, IoBoxed};
use ntex_service::{Pipeline, fn_service};

async fn run(io: IoBoxed) -> Result<(), &'static str> {
    let service = fn_service(async |event: DispatchItem<BytesCodec>| {
        Ok::<_, Infallible>(match event {
            DispatchItem::Item(bytes) => Some(bytes),
            _ => None,
        })
    });

    let io_ref = io.get_ref();
    Dispatcher::new(io, BytesCodec, Pipeline::new((), service))
        .await
        .map_err(|_| "service error")?;

    match io_ref.close_reason() {
        Some(CloseReason::Decoder) => Err("malformed input"),
        Some(CloseReason::Encoder | CloseReason::Io) => Err("transport failure"),
        Some(CloseReason::ReadTimeout | CloseReason::WriteTimeout) => Err("timeout"),
        _ => Ok(()),
    }
}

§Configuration

Configure the transport with [ntex_io::IoConfig] before constructing the dispatcher:

Keep-alive, frame-read, and write timeouts are disabled by default. Dispatcher::max_inflight separately limits normal frame admission; it does not limit buffer sizes.

Structs§

Dispatcher
Future that dispatches decoded transport frames to a service.

Enums§

Control
Write-side flow-control notification.
DispatchItem
Event delivered to the dispatcher service.
Reason
Reason a dispatcher is stopping.