[][src]Trait tower_grpc::codegen::server::tower::Service

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

An asynchronous function from 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 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 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:

This example is not tested
impl Service<http::Request> for HelloWorld {
    type Response = http::Response;
    type Error = http::Error;
    type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;

    fn poll_ready(&mut self) -> Poll<(), Self::Error> {
        Ok(Async::Ready(()))
    }

    fn call(&mut self, req: http::Request) -> Self::Future {
        // Create the HTTP response
        let resp = http::Response::ok()
            .with_body(b"hello world\n");

        // Return the response as an immediate future
        futures::finished(resp).boxed()
    }
}

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"));

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

Middleware

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 futures::Future;
use std::time::Duration;

use tokio_timer::Timer;

pub struct Timeout<T> {
    inner: T,
    delay: Duration,
    timer: Timer,
}

pub struct Expired;

impl<T> Timeout<T> {
    pub fn new(inner: T, delay: Duration) -> Timeout<T> {
        Timeout {
            inner: inner,
            delay: delay,
            timer: Timer::default(),
        }
    }
}

impl<T, Request> Service<Request> for Timeout<T>
where
    T: Service<Request>,
    T::Error: From<Expired>,
{
    type Response = T::Response;
    type Error = T::Error;
    type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;

    fn poll_ready(&mut self) -> Poll<(), Self::Error> {
        Ok(Async::Ready(()))
    }

    fn call(&mut self, req: Request) -> Self::Future {
        let timeout = self.timer.sleep(self.delay)
            .and_then(|_| Err(Self::Error::from(Expired)));

        self.inner.call(req)
            .select(timeout)
            .map(|(v, _)| v)
            .map_err(|(e, _)| e)
            .boxed()
    }
}

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 an at capacity Service (i.e., it 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) -> Result<Async<()>, Self::Error>

Returns Ready when the service is able to process requests.

If the service is at capacity, then NotReady is returned and the task is notified when the service becomes ready again. This function is expected to be called while on a task.

This is a best effort implementation. False positives are permitted. It is permitted for the service to return Ready from a poll_ready call and the next invocation of call results in an error.

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. If the service is at capacity and the request is unable to be handled, the returned Future should resolve to an error.

Calling call without calling poll_ready is permitted. The implementation must be resilient to this fact.

Loading content...

Implementations on Foreign Types

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

type Response = U

type Error = E

type Future = Box<dyn Future<Item = U, Error = E> + 'static>

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 + Send + Sync>>,
    <B as Service<Request>>::Error: Into<Box<dyn Error + 'static + Send + Sync>>, 
[src]

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

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

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

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

type Response = U

type Error = E

type Future = Box<dyn Future<Item = U, Error = E> + 'static + Send>

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

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

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

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

impl<T, F, Request> Service<Request> for ServiceFn<T> where
    F: IntoFuture,
    T: FnMut(Request) -> F, 
[src]

type Response = <F as IntoFuture>::Item

type Error = <F as IntoFuture>::Error

type Future = <F as IntoFuture>::Future

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<C, B> Service<Request<B>> for Client<C, B> where
    B: Body + Send + 'static,
    C: Connect + Sync + 'static,
    <C as Connect>::Transport: 'static,
    <C as Connect>::Future: 'static,
    <B as Body>::Data: Send,
    <B as Body>::Error: Into<Box<dyn Error + 'static + Send + Sync>>, 
[src]

type Response = Response<Body>

type Error = Error

type Future = ResponseFuture<ResponseFuture>

fn poll_ready(
    &mut self
) -> Result<Async<()>, <Client<C, B> as Service<Request<B>>>::Error>
[src]

Poll to see if the service is ready, since hyper::Client already handles this internally this will always return ready

fn call(
    &mut self,
    req: Request<B>
) -> <Client<C, B> as Service<Request<B>>>::Future
[src]

Send the sepcficied request to the inner hyper::Client

impl<B> Service<Request<B>> for Connection<B> where
    B: Body + Send + 'static,
    <B as Body>::Data: Send,
    <B as Body>::Error: Into<Box<dyn Error + 'static + Send + Sync>>, 
[src]

type Response = Response<Body>

type Error = Error

type Future = ResponseFuture<ResponseFuture>

impl<C> Service<Destination> for Connector<C> where
    C: Connect
[src]

type Response = <C as Connect>::Transport

type Error = <C as Connect>::Error

type Future = ConnectorFuture<C>

impl<A, B, C, E> Service<A> for Connect<A, B, C, E> where
    B: Body + Send + 'static,
    C: HttpMakeConnection<A> + 'static,
    E: ConnectExecutor<<C as HttpMakeConnection<A>>::Connection, B> + Clone,
    <B as Body>::Data: Send,
    <B as Body>::Error: Into<Box<dyn Error + 'static + Send + Sync>>,
    <C as HttpMakeConnection<A>>::Connection: Send,
    <C as HttpMakeConnection<A>>::Connection: 'static, 
[src]

type Response = Connection<B>

type Error = ConnectError<<C as HttpMakeConnection<A>>::Error>

type Future = ConnectFuture<A, B, C, E>

fn poll_ready(
    &mut self
) -> Result<Async<()>, <Connect<A, B, C, E> as Service<A>>::Error>
[src]

Check if the MakeConnection is ready for a new connection.

fn call(&mut self, target: A) -> <Connect<A, B, C, E> as Service<A>>::Future[src]

Obtains a Connection on a single plaintext h2 connection to a remote.

impl<'a, T, ReqBody> Service<Request<ReqBody>> for AsService<'a, T> where
    T: HttpService<ReqBody>, 
[src]

type Response = Response<<T as HttpService<ReqBody>>::ResponseBody>

type Error = <T as HttpService<ReqBody>>::Error

type Future = <T as HttpService<ReqBody>>::Future

impl<T, ReqBody> Service<Request<ReqBody>> for IntoService<T> where
    T: HttpService<ReqBody>, 
[src]

type Response = Response<<T as HttpService<ReqBody>>::ResponseBody>

type Error = <T as HttpService<ReqBody>>::Error

type Future = <T as HttpService<ReqBody>>::Future

Loading content...

Implementors

impl<'a, T, ReqBody> Service<Request<ReqBody>> for tower_grpc::generic::client::AsService<'a, T> where
    T: GrpcService<ReqBody> + 'a, 
[src]

type Response = Response<T::ResponseBody>

type Future = T::Future

type Error = T::Error

impl<T, ReqBody> Service<Request<ReqBody>> for tower_grpc::generic::client::IntoService<T> where
    T: GrpcService<ReqBody>, 
[src]

type Response = Response<T::ResponseBody>

type Future = T::Future

type Error = T::Error

Loading content...