Skip to main content

Middleware

Trait Middleware 

Source
pub trait Middleware<S, St> {
    type Service;

    // Required method
    fn create(&self, st: &St, service: S) -> Self::Service;

    // Provided method
    fn apply_to<Sf, Req>(
        self,
        factory: Sf,
    ) -> ServiceChainFactory<ApplyMiddleware<Self, Sf>, St, Req>
       where Sf: ServiceFactory<St, Req, Service = S>,
             Self: Sized,
             Self::Service: Service<St, Req> { ... }
}
Expand description

Wraps an inner service during service construction.

Self::create takes ownership of an already-created service and returns a wrapper synchronously and infallibly. The wrapper can run work before and after inner calls, transform requests, responses, or errors, or avoid calling the inner service.

Use apply(), Self::apply_to, or ServiceChainFactory::apply to install middleware on a factory. These require the wrapper to implement Service for the factory’s state and request types. Direct use of Self::create can also construct wrappers with a different request type.

The state reference is available during construction. A service wrapper can access the current state on each call through crate::Ctx::st. Rc middleware shares one middleware value across its clones, and Stack composes multiple wrappers.

§Lifecycle forwarding

Middleware must arrange the resulting service’s lifecycle behavior. Wrappers retaining an inner service should forward Service::bind so its readiness notifications reach the enclosing pipeline, and forward or deliberately replace its readiness and shutdown behavior. These methods are not forwarded automatically by implementing this trait.

§Example

For example, timeout middleware:

use ntex_service::{Ctx, Service};
use ntex::{time::sleep, util::Either, util::select};

pub struct Timeout<S> {
    service: S,
    timeout: std::time::Duration,
}

pub enum TimeoutError<E> {
   Service(E),
   Timeout,
}

impl<S, R> Service<(), R> for Timeout<S>
where
    S: Service<(), R>,
{
    type Res = S::Res;
    type Error = TimeoutError<S::Error>;

    ntex_service::forward_bind!((), service);
    ntex_service::forward_shutdown!((), service);

    async fn ready(&self, ctx: Ctx<'_, Self>) -> Result<(), Self::Error> {
        ctx.ready(&self.service).await.map_err(TimeoutError::Service)
    }

    async fn call(&self, req: R, ctx: Ctx<'_, Self>) -> Result<Self::Res, Self::Error> {
        match select(sleep(self.timeout), ctx.call(&self.service, req)).await {
            Either::Left(_) => Err(TimeoutError::Timeout),
            Either::Right(res) => res.map_err(TimeoutError::Service),
        }
    }
}

The timeout service is independent of the wrapped service implementation and can be applied to any compatible service.

Middleware that constructs Timeout could look like this:

pub struct TimeoutMiddleware {
    timeout: std::time::Duration,
}

impl<S> Middleware<S, ()> for TimeoutMiddleware
{
    type Service = Timeout<S>;

    fn create(&self, _: &(), service: S) -> Self::Service {
        Timeout {
            service,
            timeout: self.timeout,
        }
    }
}

Required Associated Types§

Source

type Service

Wrapper returned by Self::create.

Factory application requires this type to implement Service for the factory’s state and request types. Its response and error types may differ from those of the inner service.

Required Methods§

Source

fn create(&self, st: &St, service: S) -> Self::Service

Wraps service using the supplied construction state.

This is synchronous and infallible. It does not bind or check readiness of the returned service; those steps belong to the enclosing pipeline.

Provided Methods§

Source

fn apply_to<Sf, Req>( self, factory: Sf, ) -> ServiceChainFactory<ApplyMiddleware<Self, Sf>, St, Req>
where Sf: ServiceFactory<St, Req, Service = S>, Self: Sized, Self::Service: Service<St, Req>,

Creates a service factory that instantiates a service and applies the current middleware to it.

This is equivalent to apply() with this middleware and factory. The factory is awaited before invoking Self::create with the same state reference. Initialization errors bypass the middleware.

The middleware and factory are shared when the returned builder is cloned; they do not need to implement Clone.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl<M, S, St> Middleware<S, St> for Rc<M>
where M: Middleware<S, St>,

Source§

type Service = <M as Middleware<S, St>>::Service

Source§

fn create(&self, st: &St, service: S) -> <M as Middleware<S, St>>::Service

Implementors§

Source§

impl<F, S, St, Req, In, Out, Err> Middleware<S, St> for FnMiddleware<F, S, St, Req, In, Out, Err>
where S: Service<St, Req>, F: AsyncFn(In, &ApplyCtx<'_, S, St, Req>) -> Result<Out, Err> + Clone, Err: From<<S as Service<St, Req>>::Error>,

Source§

type Service = Apply<S, St, Req, F, In, Out, Err>

Source§

impl<P, S, St> Middleware<S, St> for Retry<P>
where P: Clone,

Source§

impl<S, St, Inner, Outer> Middleware<S, St> for Stack<Inner, Outer>
where Inner: Middleware<S, St>, Outer: Middleware<<Inner as Middleware<S, St>>::Service, St>,

Source§

type Service = <Outer as Middleware<<Inner as Middleware<S, St>>::Service, St>>::Service

Source§

impl<S, St, Inner, Outer> Middleware<S, St> for WebStack<St, Inner, Outer>
where St: State, Inner: Middleware<S, St>, Outer: Middleware<Inner::Service, St>,

Source§

type Service = WebMiddleware<<Outer as Middleware<<Inner as Middleware<S, St>>::Service, St>>::Service, St>

Source§

impl<S, St, Req, Res, Err> Middleware<S, St> for Buffer<St, Req, Res, Err>
where S: Service<St, Req, Res = Res, Error = Err> + 'static, St: Clone + 'static, Req: 'static, Res: 'static, Err: 'static,

Source§

type Service = BufferService<St, Req, Res, Err>

Source§

impl<S, St> Middleware<S, St> for Compress

Source§

type Service = CompressMiddleware<S>

Source§

impl<S, St> Middleware<S, St> for DefaultHeaders

Source§

type Service = DefaultHeadersMiddleware<S>

Source§

impl<S, St> Middleware<S, St> for Identity

Source§

impl<S, St> Middleware<S, St> for InFlight

Source§

impl<S, St> Middleware<S, St> for Logger

Source§

type Service = LoggerMiddleware<S>

Source§

impl<S, St> Middleware<S, St> for OneRequest

Source§

impl<S, St> Middleware<S, St> for ReadyBindingMiddleware

Source§

impl<S, St> Middleware<S, St> for Timeout<St>