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