tower_service/
lib.rs

1#![warn(
2    missing_debug_implementations,
3    missing_docs,
4    rust_2018_idioms,
5    unreachable_pub
6)]
7#![forbid(unsafe_code)]
8// `rustdoc::broken_intra_doc_links` is checked on CI
9
10//! Definition of the core `Service` trait to Tower
11//!
12//! The [`Service`] trait provides the necessary abstractions for defining
13//! request / response clients and servers. It is simple but powerful and is
14//! used as the foundation for the rest of Tower.
15
16#![no_std]
17
18extern crate alloc;
19
20use alloc::boxed::Box;
21
22use core::future::Future;
23use core::marker::Sized;
24use core::result::Result;
25use core::task::{Context, Poll};
26
27/// An asynchronous function from a `Request` to a `Response`.
28///
29/// The `Service` trait is a simplified interface making it easy to write
30/// network applications in a modular and reusable way, decoupled from the
31/// underlying protocol. It is one of Tower's fundamental abstractions.
32///
33/// # Functional
34///
35/// A `Service` is a function of a `Request`. It immediately returns a
36/// `Future` representing the eventual completion of processing the
37/// request. The actual request processing may happen at any time in the
38/// future, on any thread or executor. The processing may depend on calling
39/// other services. At some point in the future, the processing will complete,
40/// and the `Future` will resolve to a response or error.
41///
42/// At a high level, the `Service::call` function represents an RPC request. The
43/// `Service` value can be a server or a client.
44///
45/// # Server
46///
47/// An RPC server *implements* the `Service` trait. Requests received by the
48/// server over the network are deserialized and then passed as an argument to the
49/// server value. The returned response is sent back over the network.
50///
51/// As an example, here is how an HTTP request is processed by a server:
52///
53/// ```rust
54/// # use std::pin::Pin;
55/// # use std::task::{Poll, Context};
56/// # use std::future::Future;
57/// # use tower_service::Service;
58/// use http::{Request, Response, StatusCode};
59///
60/// struct HelloWorld;
61///
62/// impl Service<Request<Vec<u8>>> for HelloWorld {
63///     type Response = Response<Vec<u8>>;
64///     type Error = http::Error;
65///     type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
66///
67///     fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
68///         Poll::Ready(Ok(()))
69///     }
70///
71///     fn call(&mut self, req: Request<Vec<u8>>) -> Self::Future {
72///         // create the body
73///         let body: Vec<u8> = "hello, world!\n"
74///             .as_bytes()
75///             .to_owned();
76///         // Create the HTTP response
77///         let resp = Response::builder()
78///             .status(StatusCode::OK)
79///             .body(body)
80///             .expect("Unable to create `http::Response`");
81///
82///         // create a response in a future.
83///         let fut = async {
84///             Ok(resp)
85///         };
86///
87///         // Return the response as an immediate future
88///         Box::pin(fut)
89///     }
90/// }
91/// ```
92///
93/// # Client
94///
95/// A client consumes a service by using a `Service` value. The client may
96/// issue requests by invoking `call` and passing the request as an argument.
97/// It then receives the response by waiting for the returned future.
98///
99/// As an example, here is how a Redis request would be issued:
100///
101/// ```rust,ignore
102/// let client = redis::Client::new()
103///     .connect("127.0.0.1:6379".parse().unwrap())
104///     .unwrap();
105///
106/// let resp = client.call(Cmd::set("foo", "this is the value of foo")).await?;
107///
108/// // Wait for the future to resolve
109/// println!("Redis response: {:?}", resp);
110/// ```
111///
112/// # Middleware / Layer
113///
114/// More often than not, all the pieces needed for writing robust, scalable
115/// network applications are the same no matter the underlying protocol. By
116/// unifying the API for both clients and servers in a protocol agnostic way,
117/// it is possible to write middleware that provide these pieces in a
118/// reusable way.
119///
120/// Take timeouts as an example:
121///
122/// ```rust
123/// use tower_service::Service;
124/// use tower_layer::Layer;
125/// use futures::FutureExt;
126/// use std::future::Future;
127/// use std::task::{Context, Poll};
128/// use std::time::Duration;
129/// use std::pin::Pin;
130/// use std::fmt;
131/// use std::error::Error;
132///
133/// // Our timeout service, which wraps another service and
134/// // adds a timeout to its response future.
135/// pub struct Timeout<T> {
136///     inner: T,
137///     timeout: Duration,
138/// }
139///
140/// impl<T> Timeout<T> {
141///     pub const fn new(inner: T, timeout: Duration) -> Timeout<T> {
142///         Timeout {
143///             inner,
144///             timeout
145///         }
146///     }
147/// }
148///
149/// // The error returned if processing a request timed out
150/// #[derive(Debug)]
151/// pub struct Expired;
152///
153/// impl fmt::Display for Expired {
154///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155///         write!(f, "expired")
156///     }
157/// }
158///
159/// impl Error for Expired {}
160///
161/// // We can implement `Service` for `Timeout<T>` if `T` is a `Service`
162/// impl<T, Request> Service<Request> for Timeout<T>
163/// where
164///     T: Service<Request>,
165///     T::Future: 'static,
166///     T::Error: Into<Box<dyn Error + Send + Sync>> + 'static,
167///     T::Response: 'static,
168/// {
169///     // `Timeout` doesn't modify the response type, so we use `T`'s response type
170///     type Response = T::Response;
171///     // Errors may be either `Expired` if the timeout expired, or the inner service's
172///     // `Error` type. Therefore, we return a boxed `dyn Error + Send + Sync` trait object to erase
173///     // the error's type.
174///     type Error = Box<dyn Error + Send + Sync>;
175///     type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
176///
177///     fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
178///         // Our timeout service is ready if the inner service is ready.
179///         // This is how backpressure can be propagated through a tree of nested services.
180///        self.inner.poll_ready(cx).map_err(Into::into)
181///     }
182///
183///     fn call(&mut self, req: Request) -> Self::Future {
184///         // Create a future that completes after `self.timeout`
185///         let timeout = tokio::time::sleep(self.timeout);
186///
187///         // Call the inner service and get a future that resolves to the response
188///         let fut = self.inner.call(req);
189///
190///         // Wrap those two futures in another future that completes when either one completes
191///         //
192///         // If the inner service is too slow the `sleep` future will complete first
193///         // And an error will be returned and `fut` will be dropped and not polled again
194///         //
195///         // We have to box the errors so the types match
196///         let f = async move {
197///             tokio::select! {
198///                 res = fut => {
199///                     res.map_err(|err| err.into())
200///                 },
201///                 _ = timeout => {
202///                     Err(Box::new(Expired) as Box<dyn Error + Send + Sync>)
203///                 },
204///             }
205///         };
206///
207///         Box::pin(f)
208///     }
209/// }
210///
211/// // A layer for wrapping services in `Timeout`
212/// pub struct TimeoutLayer(Duration);
213///
214/// impl TimeoutLayer {
215///     pub const fn new(delay: Duration) -> Self {
216///         TimeoutLayer(delay)
217///     }
218/// }
219///
220/// impl<S> Layer<S> for TimeoutLayer {
221///     type Service = Timeout<S>;
222///
223///     fn layer(&self, service: S) -> Timeout<S> {
224///         Timeout::new(service, self.0)
225///     }
226/// }
227/// ```
228///
229/// The above timeout implementation is decoupled from the underlying protocol
230/// and is also decoupled from client or server concerns. In other words, the
231/// same timeout middleware could be used in either a client or a server.
232///
233/// # Backpressure
234///
235/// Calling a `Service` which is at capacity (i.e., it is temporarily unable to process a
236/// request) should result in an error. The caller is responsible for ensuring
237/// that the service is ready to receive the request before calling it.
238///
239/// `Service` provides a mechanism by which the caller is able to coordinate
240/// readiness. `Service::poll_ready` returns `Ready` if the service expects that
241/// it is able to process a request.
242///
243/// # Be careful when cloning inner services
244///
245/// Services are permitted to panic if `call` is invoked without obtaining `Poll::Ready(Ok(()))`
246/// from `poll_ready`. You should therefore be careful when cloning services for example to move
247/// them into boxed futures. Even though the original service is ready, the clone might not be.
248///
249/// Therefore this kind of code is wrong and might panic:
250///
251/// ```rust
252/// # use std::pin::Pin;
253/// # use std::task::{Poll, Context};
254/// # use std::future::Future;
255/// # use tower_service::Service;
256/// #
257/// struct Wrapper<S> {
258///     inner: S,
259/// }
260///
261/// impl<R, S> Service<R> for Wrapper<S>
262/// where
263///     S: Service<R> + Clone + 'static,
264///     R: 'static,
265/// {
266///     type Response = S::Response;
267///     type Error = S::Error;
268///     type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
269///
270///     fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
271///         self.inner.poll_ready(cx)
272///     }
273///
274///     fn call(&mut self, req: R) -> Self::Future {
275///         let mut inner = self.inner.clone();
276///         Box::pin(async move {
277///             // `inner` might not be ready since its a clone
278///             inner.call(req).await
279///         })
280///     }
281/// }
282/// ```
283///
284/// You should instead use [`core::mem::replace`] to take the service that was ready:
285///
286/// ```rust
287/// # use std::pin::Pin;
288/// # use std::task::{Poll, Context};
289/// # use std::future::Future;
290/// # use tower_service::Service;
291/// #
292/// struct Wrapper<S> {
293///     inner: S,
294/// }
295///
296/// impl<R, S> Service<R> for Wrapper<S>
297/// where
298///     S: Service<R> + Clone + 'static,
299///     R: 'static,
300/// {
301///     type Response = S::Response;
302///     type Error = S::Error;
303///     type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
304///
305///     fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
306///         self.inner.poll_ready(cx)
307///     }
308///
309///     fn call(&mut self, req: R) -> Self::Future {
310///         let clone = self.inner.clone();
311///         // take the service that was ready
312///         let mut inner = std::mem::replace(&mut self.inner, clone);
313///         Box::pin(async move {
314///             inner.call(req).await
315///         })
316///     }
317/// }
318/// ```
319pub trait Service<Request> {
320    /// Responses given by the service.
321    type Response;
322
323    /// Errors produced by the service.
324    type Error;
325
326    /// The future response value.
327    type Future: Future<Output = Result<Self::Response, Self::Error>>;
328
329    /// Returns `Poll::Ready(Ok(()))` when the service is able to process requests.
330    ///
331    /// If the service is at capacity, then `Poll::Pending` is returned and the task
332    /// is notified when the service becomes ready again. This function is
333    /// expected to be called while on a task. Generally, this can be done with
334    /// a simple `futures::future::poll_fn` call.
335    ///
336    /// If `Poll::Ready(Err(_))` is returned, the service is no longer able to service requests
337    /// and the caller should discard the service instance.
338    ///
339    /// Once `poll_ready` returns `Poll::Ready(Ok(()))`, a request may be dispatched to the
340    /// service using `call`. Until a request is dispatched, repeated calls to
341    /// `poll_ready` must return either `Poll::Ready(Ok(()))` or `Poll::Ready(Err(_))`.
342    ///
343    /// Note that `poll_ready` may reserve shared resources that are consumed in a subsequent
344    /// invocation of `call`. Thus, it is critical for implementations to not assume that `call`
345    /// will always be invoked and to ensure that such resources are released if the service is
346    /// dropped before `call` is invoked or the future returned by `call` is dropped before it
347    /// is polled.
348    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
349
350    /// Process the request and return the response asynchronously.
351    ///
352    /// This function is expected to be callable off task. As such,
353    /// implementations should take care to not call `poll_ready`.
354    ///
355    /// Before dispatching a request, `poll_ready` must be called and return
356    /// `Poll::Ready(Ok(()))`.
357    ///
358    /// # Panics
359    ///
360    /// Implementations are permitted to panic if `call` is invoked without
361    /// obtaining `Poll::Ready(Ok(()))` from `poll_ready`.
362    #[must_use = "futures do nothing unless you `.await` or poll them"]
363    fn call(&mut self, req: Request) -> Self::Future;
364}
365
366impl<'a, S, Request> Service<Request> for &'a mut S
367where
368    S: Service<Request> + 'a,
369{
370    type Response = S::Response;
371    type Error = S::Error;
372    type Future = S::Future;
373
374    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), S::Error>> {
375        (**self).poll_ready(cx)
376    }
377
378    fn call(&mut self, request: Request) -> S::Future {
379        (**self).call(request)
380    }
381}
382
383impl<S, Request> Service<Request> for Box<S>
384where
385    S: Service<Request> + ?Sized,
386{
387    type Response = S::Response;
388    type Error = S::Error;
389    type Future = S::Future;
390
391    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), S::Error>> {
392        (**self).poll_ready(cx)
393    }
394
395    fn call(&mut self, request: Request) -> S::Future {
396        (**self).call(request)
397    }
398}