tower_service/
lib.rs

1#![doc(html_root_url = "https://docs.rs/tower-service/0.3.0")]
2#![warn(
3    missing_debug_implementations,
4    missing_docs,
5    rust_2018_idioms,
6    unreachable_pub
7)]
8
9//! Definition of the core `Service` trait to Tower
10//!
11//! The [`Service`] trait provides the necessary abstractions for defining
12//! request / response clients and servers. It is simple but powerful and is
13//! used as the foundation for the rest of Tower.
14
15use std::future::Future;
16use std::task::{Context, Poll};
17
18/// An asynchronous function from a `Request` to a `Response`.
19///
20/// The `Service` trait is a simplified interface making it easy to write
21/// network applications in a modular and reusable way, decoupled from the
22/// underlying protocol. It is one of Tower's fundamental abstractions.
23///
24/// # Functional
25///
26/// A `Service` is a function of a `Request`. It immediately returns a
27/// `Future` representing the eventual completion of processing the
28/// request. The actual request processing may happen at any time in the
29/// future, on any thread or executor. The processing may depend on calling
30/// other services. At some point in the future, the processing will complete,
31/// and the `Future` will resolve to a response or error.
32///
33/// At a high level, the `Service::call` function represents an RPC request. The
34/// `Service` value can be a server or a client.
35///
36/// # Server
37///
38/// An RPC server *implements* the `Service` trait. Requests received by the
39/// server over the network are deserialized and then passed as an argument to the
40/// server value. The returned response is sent back over the network.
41///
42/// As an example, here is how an HTTP request is processed by a server:
43///
44/// ```rust
45/// # use std::pin::Pin;
46/// # use std::task::{Poll, Context};
47/// # use std::future::Future;
48/// # use tower_service::Service;
49///
50/// use http::{Request, Response, StatusCode};
51///
52/// struct HelloWorld;
53///
54/// impl Service<Request<Vec<u8>>> for HelloWorld {
55///     type Response = Response<Vec<u8>>;
56///     type Error = http::Error;
57///     type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
58///
59///     fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
60///         Poll::Ready(Ok(()))
61///     }
62///
63///     fn call(&mut self, req: Request<Vec<u8>>) -> Self::Future {
64///         // create the body
65///         let body: Vec<u8> = "hello, world!\n"
66///             .as_bytes()
67///             .to_owned();
68///         // Create the HTTP response
69///         let resp = Response::builder()
70///             .status(StatusCode::OK)
71///             .body(body)
72///             .expect("Unable to create `http::Response`");
73///         
74///         // create a response in a future.
75///         let fut = async {
76///             Ok(resp)
77///         };
78///
79///         // Return the response as an immediate future
80///         Box::pin(fut)
81///     }
82/// }
83/// ```
84///
85/// # Client
86///
87/// A client consumes a service by using a `Service` value. The client may
88/// issue requests by invoking `call` and passing the request as an argument.
89/// It then receives the response by waiting for the returned future.
90///
91/// As an example, here is how a Redis request would be issued:
92///
93/// ```rust,ignore
94/// let client = redis::Client::new()
95///     .connect("127.0.0.1:6379".parse().unwrap())
96///     .unwrap();
97///
98/// let resp = client.call(Cmd::set("foo", "this is the value of foo")).await?;
99///
100/// // Wait for the future to resolve
101/// println!("Redis response: {:?}", resp);
102/// ```
103///
104/// # Middleware / Layer
105///
106/// More often than not, all the pieces needed for writing robust, scalable
107/// network applications are the same no matter the underlying protocol. By
108/// unifying the API for both clients and servers in a protocol agnostic way,
109/// it is possible to write middleware that provide these pieces in a
110/// reusable way.
111///
112/// Take timeouts as an example:
113///
114/// ```rust,ignore
115/// use tower_service::Service;
116/// use tower_layer::Layer;
117/// use futures::FutureExt;
118/// use std::future::Future;
119/// use std::task::{Context, Poll};
120/// use std::time::Duration;
121/// use std::pin::Pin;
122///
123///
124/// pub struct Timeout<T> {
125///     inner: T,
126///     timeout: Duration,
127/// }
128///
129/// pub struct TimeoutLayer(Duration);
130///
131/// pub struct Expired;
132///
133/// impl<T> Timeout<T> {
134///     pub fn new(inner: T, timeout: Duration) -> Timeout<T> {
135///         Timeout {
136///             inner,
137///             timeout
138///         }
139///     }
140/// }
141///
142/// impl<T, Request> Service<Request> for Timeout<T>
143/// where
144///     T: Service<Request>,
145///     T::Future: 'static,
146///     T::Error: From<Expired> + 'static,
147///     T::Response: 'static
148/// {
149///     type Response = T::Response;
150///     type Error = T::Error;
151///     type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
152///
153///     fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
154///        self.inner.poll_ready(cx).map_err(Into::into)
155///     }
156///
157///     fn call(&mut self, req: Request) -> Self::Future {
158///         let timeout = tokio_timer::delay_for(self.timeout)
159///             .map(|_| Err(Self::Error::from(Expired)));
160///
161///         let fut = Box::pin(self.inner.call(req));
162///         let f = futures::select(fut, timeout)
163///             .map(|either| either.factor_first().0);
164///
165///         Box::pin(f)
166///     }
167/// }
168///
169/// impl TimeoutLayer {
170///     pub fn new(delay: Duration) -> Self {
171///         TimeoutLayer(delay)
172///     }
173/// }
174///
175/// impl<S> Layer<S> for TimeoutLayer
176/// {
177///     type Service = Timeout<S>;
178///
179///     fn layer(&self, service: S) -> Timeout<S> {
180///         Timeout::new(service, self.0)
181///     }
182/// }
183///
184/// ```
185///
186/// The above timeout implementation is decoupled from the underlying protocol
187/// and is also decoupled from client or server concerns. In other words, the
188/// same timeout middleware could be used in either a client or a server.
189///
190/// # Backpressure
191///
192/// Calling a `Service` which is at capacity (i.e., it is temporarily unable to process a
193/// request) should result in an error. The caller is responsible for ensuring
194/// that the service is ready to receive the request before calling it.
195///
196/// `Service` provides a mechanism by which the caller is able to coordinate
197/// readiness. `Service::poll_ready` returns `Ready` if the service expects that
198/// it is able to process a request.
199pub trait Service<Request> {
200    /// Responses given by the service.
201    type Response;
202
203    /// Errors produced by the service.
204    type Error;
205
206    /// The future response value.
207    type Future: Future<Output = Result<Self::Response, Self::Error>>;
208
209    /// Returns `Poll::Ready(Ok(()))` when the service is able to process requests.
210    ///
211    /// If the service is at capacity, then `Poll::Pending` is returned and the task
212    /// is notified when the service becomes ready again. This function is
213    /// expected to be called while on a task. Generally, this can be done with
214    /// a simple `futures::future::poll_fn` call.
215    ///
216    /// If `Poll::Ready(Err(_))` is returned, the service is no longer able to service requests
217    /// and the caller should discard the service instance.
218    ///
219    /// Once `poll_ready` returns `Poll::Ready(Ok(()))`, a request may be dispatched to the
220    /// service using `call`. Until a request is dispatched, repeated calls to
221    /// `poll_ready` must return either `Poll::Ready(Ok(()))` or `Poll::Ready(Err(_))`.
222    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
223
224    /// Process the request and return the response asynchronously.
225    ///
226    /// This function is expected to be callable off task. As such,
227    /// implementations should take care to not call `poll_ready`.
228    ///
229    /// Before dispatching a request, `poll_ready` must be called and return
230    /// `Poll::Ready(Ok(()))`.
231    ///
232    /// # Panics
233    ///
234    /// Implementations are permitted to panic if `call` is invoked without
235    /// obtaining `Poll::Ready(Ok(()))` from `poll_ready`.
236    fn call(&mut self, req: Request) -> Self::Future;
237}
238
239impl<'a, S, Request> Service<Request> for &'a mut S
240where
241    S: Service<Request> + 'a,
242{
243    type Response = S::Response;
244    type Error = S::Error;
245    type Future = S::Future;
246
247    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), S::Error>> {
248        (**self).poll_ready(cx)
249    }
250
251    fn call(&mut self, request: Request) -> S::Future {
252        (**self).call(request)
253    }
254}
255
256impl<S, Request> Service<Request> for Box<S>
257where
258    S: Service<Request> + ?Sized,
259{
260    type Response = S::Response;
261    type Error = S::Error;
262    type Future = S::Future;
263
264    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), S::Error>> {
265        (**self).poll_ready(cx)
266    }
267
268    fn call(&mut self, request: Request) -> S::Future {
269        (**self).call(request)
270    }
271}