[][src]Trait tower::Service

pub trait Service<Request> where
    <Self::Future as Future>::Output == Result<Self::Response, Self::Error>, 
{ type Response; type Error; type Future: Future; fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>>;
fn call(&mut self, req: Request) -> Self::Future; }

An asynchronous function from a Request to a Response.

The Service trait is a simplified interface making it easy to write network applications in a modular and reusable way, decoupled from the underlying protocol. It is one of Tower's fundamental abstractions.

Functional

A Service is a function of a Request. It immediately returns a Future representing the eventual completion of processing the request. The actual request processing may happen at any time in the future, on any thread or executor. The processing may depend on calling other services. At some point in the future, the processing will complete, and the Future will resolve to a response or error.

At a high level, the Service::call function represents an RPC request. The Service value can be a server or a client.

Server

An RPC server implements the Service trait. Requests received by the server over the network are deserialized and then passed as an argument to the server value. The returned response is sent back over the network.

As an example, here is how an HTTP request is processed by a server:

use http::{Request, Response, StatusCode};

struct HelloWorld;

impl Service<Request<Vec<u8>>> for HelloWorld {
    type Response = Response<Vec<u8>>;
    type Error = http::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: Request<Vec<u8>>) -> Self::Future {
        // create the body
        let body: Vec<u8> = "hello, world!\n"
            .as_bytes()
            .to_owned();
        // Create the HTTP response
        let resp = Response::builder()
            .status(StatusCode::OK)
            .body(body)
            .expect("Unable to create `http::Response`");
         
        // create a response in a future.
        let fut = async {
            Ok(resp)
        };

        // Return the response as an immediate future
        Box::pin(fut)
    }
}

Client

A client consumes a service by using a Service value. The client may issue requests by invoking call and passing the request as an argument. It then receives the response by waiting for the returned future.

As an example, here is how a Redis request would be issued:

This example is not tested
let client = redis::Client::new()
    .connect("127.0.0.1:6379".parse().unwrap())
    .unwrap();

let resp = client.call(Cmd::set("foo", "this is the value of foo")).await?;

// Wait for the future to resolve
println!("Redis response: {:?}", resp);

Middleware / Layer

More often than not, all the pieces needed for writing robust, scalable network applications are the same no matter the underlying protocol. By unifying the API for both clients and servers in a protocol agnostic way, it is possible to write middleware that provide these pieces in a reusable way.

Take timeouts as an example:

This example is not tested
use tower_service::Service;
use tower_layer::Layer;
use futures::FutureExt;
use std::future::Future;
use std::task::{Context, Poll};
use std::time::Duration;
use std::pin::Pin;


pub struct Timeout<T> {
    inner: T,
    timeout: Duration,
}

pub struct TimeoutLayer(Duration);

pub struct Expired;

impl<T> Timeout<T> {
    pub fn new(inner: T, timeout: Duration) -> Timeout<T> {
        Timeout {
            inner,
            timeout
        }
    }
}

impl<T, Request> Service<Request> for Timeout<T>
where
    T: Service<Request>,
    T::Future: 'static,
    T::Error: From<Expired> + 'static,
    T::Response: 'static
{
    type Response = T::Response;
    type Error = T::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
       self.inner.poll_ready(cx).map_err(Into::into)
    }

    fn call(&mut self, req: Request) -> Self::Future {
        let timeout = tokio_timer::delay_for(self.timeout)
            .map(|_| Err(Self::Error::from(Expired)));

        let fut = Box::pin(self.inner.call(req));
        let f = futures::select(fut, timeout)
            .map(|either| either.factor_first().0);

        Box::pin(f)
    }
}

impl TimeoutLayer {
    pub fn new(delay: Duration) -> Self {
        TimeoutLayer(delay)
    }
}

impl<S> Layer<S> for TimeoutLayer
{
    type Service = Timeout<S>;

    fn layer(&self, service: S) -> Timeout<S> {
        Timeout::new(service, self.0)
    }
}

The above timeout implementation is decoupled from the underlying protocol and is also decoupled from client or server concerns. In other words, the same timeout middleware could be used in either a client or a server.

Backpressure

Calling a Service which is at capacity (i.e., it is temporarily unable to process a request) should result in an error. The caller is responsible for ensuring that the service is ready to receive the request before calling it.

Service provides a mechanism by which the caller is able to coordinate readiness. Service::poll_ready returns Ready if the service expects that it is able to process a request.

Associated Types

type Response

Responses given by the service.

type Error

Errors produced by the service.

type Future: Future

The future response value.

Loading content...

Required methods

fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>>

Returns Poll::Ready(Ok(())) when the service is able to process requests.

If the service is at capacity, then Poll::Pending is returned and the task is notified when the service becomes ready again. This function is expected to be called while on a task. Generally, this can be done with a simple futures::future::poll_fn call.

If Poll::Ready(Err(_)) is returned, the service is no longer able to service requests and the caller should discard the service instance.

Once poll_ready returns Poll::Ready(Ok(())), a request may be dispatched to the service using call. Until a request is dispatched, repeated calls to poll_ready must return either Poll::Ready(Ok(())) or Poll::Ready(Err(_)).

fn call(&mut self, req: Request) -> Self::Future

Process the request and return the response asynchronously.

This function is expected to be callable off task. As such, implementations should take care to not call poll_ready.

Before dispatching a request, poll_ready must be called and return Poll::Ready(Ok(())).

Panics

Implementations are permitted to panic if call is invoked without obtaining Poll::Ready(Ok(())) from poll_ready.

Loading content...

Implementations on Foreign Types

impl<'a, S, Request> Service<Request> for &'a mut S where
    S: Service<Request> + 'a, 
[src]

type Response = <S as Service<Request>>::Response

type Error = <S as Service<Request>>::Error

type Future = <S as Service<Request>>::Future

impl<S, Request> Service<Request> for Box<S> where
    S: Service<Request> + ?Sized
[src]

type Response = <S as Service<Request>>::Response

type Error = <S as Service<Request>>::Error

type Future = <S as Service<Request>>::Future

impl<T, F, Request, R, E> Service<Request> for ServiceFn<T> where
    F: Future<Output = Result<R, E>>,
    T: FnMut(Request) -> F, 
[src]

type Response = R

type Error = E

type Future = F

Loading content...

Implementors

impl<A, B, Request> Service<Request> for Either<A, B> where
    A: Service<Request>,
    B: Service<Request, Response = <A as Service<Request>>::Response>,
    <A as Service<Request>>::Error: Into<Box<dyn Error + 'static + Sync + Send>>,
    <B as Service<Request>>::Error: Into<Box<dyn Error + 'static + Sync + Send>>, 
[src]

type Response = <A as Service<Request>>::Response

type Error = Box<dyn Error + 'static + Sync + Send>

type Future = Either<<A as Service<Request>>::Future, <B as Service<Request>>::Future>

impl<P, S, Request> Service<Request> for Retry<P, S> where
    P: Policy<Request, <S as Service<Request>>::Response, <S as Service<Request>>::Error> + Clone,
    S: Service<Request> + Clone
[src]

type Response = <S as Service<Request>>::Response

type Error = <S as Service<Request>>::Error

type Future = ResponseFuture<P, S, Request>

impl<S, Req> Service<Req> for LoadShed<S> where
    S: Service<Req>,
    <S as Service<Req>>::Error: Into<Box<dyn Error + 'static + Sync + Send>>, 
[src]

type Response = <S as Service<Req>>::Response

type Error = Box<dyn Error + 'static + Sync + Send>

type Future = ResponseFuture<<S as Service<Req>>::Future>

impl<S, Request> Service<Request> for ConcurrencyLimit<S> where
    S: Service<Request>, 
[src]

type Response = <S as Service<Request>>::Response

type Error = <S as Service<Request>>::Error

type Future = ResponseFuture<<S as Service<Request>>::Future>

impl<S, Request> Service<Request> for RateLimit<S> where
    S: Service<Request>, 
[src]

type Response = <S as Service<Request>>::Response

type Error = <S as Service<Request>>::Error

type Future = <S as Service<Request>>::Future

impl<S, Request> Service<Request> for Timeout<S> where
    S: Service<Request>,
    <S as Service<Request>>::Error: Into<Box<dyn Error + 'static + Sync + Send>>, 
[src]

type Response = <S as Service<Request>>::Response

type Error = Box<dyn Error + 'static + Sync + Send>

type Future = ResponseFuture<<S as Service<Request>>::Future>

impl<T, Request> Service<Request> for Buffer<T, Request> where
    T: Service<Request>,
    <T as Service<Request>>::Error: Into<Box<dyn Error + 'static + Sync + Send>>, 
[src]

type Response = <T as Service<Request>>::Response

type Error = Box<dyn Error + 'static + Sync + Send>

type Future = ResponseFuture<<T as Service<Request>>::Future>

impl<T, Request> Service<Request> for Optional<T> where
    T: Service<Request>,
    <T as Service<Request>>::Error: Into<Box<dyn Error + 'static + Sync + Send>>, 
[src]

type Response = <T as Service<Request>>::Response

type Error = Box<dyn Error + 'static + Sync + Send>

type Future = ResponseFuture<<T as Service<Request>>::Future>

impl<T, U, E> Service<T> for BoxService<T, U, E>[src]

type Response = U

type Error = E

type Future = Pin<Box<dyn Future<Output = Result<U, E>> + 'static + Send>>

impl<T, U, E> Service<T> for UnsyncBoxService<T, U, E>[src]

type Response = U

type Error = E

type Future = Pin<Box<dyn Future<Output = Result<U, E>> + 'static>>

Loading content...