Trait ServiceExt
pub trait ServiceExt<Request>: Service<Request>
An extension trait for Services that provides a variety of convenient
adapters
Provided Methods
fn ready(&mut self) -> Ready<'_, Self, Request> where Self: Sized,Yields a mutable reference to the service when it is ready to accept a request.
fn ready_oneshot(self) -> ReadyOneshot<Self, Request> where Self: Sized,Yields the service when it is ready to accept a request.
fn oneshot(self, req: Request) -> Oneshot<Self, Request> where Self: Sized,Consume this
Service, calling it with the provided request once it is ready.fn call_all<S>(self, reqs: S) -> CallAll<Self, S> where Self: Sized, S: Stream<Item = Request>,Process all requests from the given
Stream, and produce aStreamof their responses.This is essentially
Stream<Item = Request>+Self=>Stream<Item = Response>. See the documentation forCallAllfor details.fn and_then<F>(self, f: F) -> AndThen<Self, F> where Self: Sized, F: Clone,Executes a new future after this service's future resolves. This does not alter the behaviour of the
poll_readymethod.This method can be used to change the
Responsetype of the service into a different type. You can use this method to chain along a computation once the service's response has been resolved.Example
# use std::task::{Poll, Context}; # use tower::{Service, ServiceExt}; # # struct DatabaseService; # impl DatabaseService { # fn new(address: &str) -> Self { # DatabaseService # } # } # # struct Record { # pub name: String, # pub age: u16 # } # # impl Service<u32> for DatabaseService { # type Response = Record; # type Error = u8; # type Future = std::future::Ready<Result<Record, u8>>; # # fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { # Poll::Ready(Ok(())) # } # # fn call(&mut self, request: u32) -> Self::Future { # std::future::ready(Ok(Record { name: "Jack".into(), age: 32 })) # } # } # # async fn avatar_lookup(name: String) -> Result<Vec<u8>, u8> { Ok(vec![]) } # # fn main() { # async { // A service returning Result<Record, _> let service = DatabaseService::new("127.0.0.1:8080"); // Map the response into a new response let mut new_service = service.and_then(|record: Record| async move { let name = record.name; avatar_lookup(name).await }); // Call the new service let id = 13; let avatar = new_service.call(id).await.unwrap(); # }; # }fn map_response<F, Response>(self, f: F) -> MapResponse<Self, F> where Self: Sized, F: FnOnce(Self::Response) -> Response + Clone,Maps this service's response value to a different value. This does not alter the behaviour of the
poll_readymethod.This method can be used to change the
Responsetype of the service into a different type. It is similar to theResult::mapmethod. You can use this method to chain along a computation once the service's response has been resolved.Example
# use std::task::{Poll, Context}; # use tower::{Service, ServiceExt}; # # struct DatabaseService; # impl DatabaseService { # fn new(address: &str) -> Self { # DatabaseService # } # } # # struct Record { # pub name: String, # pub age: u16 # } # # impl Service<u32> for DatabaseService { # type Response = Record; # type Error = u8; # type Future = std::future::Ready<Result<Record, u8>>; # # fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { # Poll::Ready(Ok(())) # } # # fn call(&mut self, request: u32) -> Self::Future { # std::future::ready(Ok(Record { name: "Jack".into(), age: 32 })) # } # } # # fn main() { # async { // A service returning Result<Record, _> let service = DatabaseService::new("127.0.0.1:8080"); // Map the response into a new response let mut new_service = service.map_response(|record| record.name); // Call the new service let id = 13; let name = new_service .ready() .await? .call(id) .await?; # Ok::<(), u8>(()) # }; # }fn map_err<F, Error>(self, f: F) -> MapErr<Self, F> where Self: Sized, F: FnOnce(Self::Error) -> Error + Clone,Maps this service's error value to a different value. This does not alter the behaviour of the
poll_readymethod.This method can be used to change the
Errortype of the service into a different type. It is similar to theResult::map_errmethod.Example
# use std::task::{Poll, Context}; # use tower::{Service, ServiceExt}; # # struct DatabaseService; # impl DatabaseService { # fn new(address: &str) -> Self { # DatabaseService # } # } # # struct Error { # pub code: u32, # pub message: String # } # # impl Service<u32> for DatabaseService { # type Response = String; # type Error = Error; # type Future = std::future::Ready<Result<String, Error>>; # # fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { # Poll::Ready(Ok(())) # } # # fn call(&mut self, request: u32) -> Self::Future { # std::future::ready(Ok(String::new())) # } # } # # fn main() { # async { // A service returning Result<_, Error> let service = DatabaseService::new("127.0.0.1:8080"); // Map the error to a new error let mut new_service = service.map_err(|err| err.code); // Call the new service let id = 13; let code = new_service .ready() .await? .call(id) .await .unwrap_err(); # Ok::<(), u32>(()) # }; # }fn map_result<F, Response, Error>(self, f: F) -> MapResult<Self, F> where Self: Sized, Error: From<Self::Error>, F: FnOnce(Result<Self::Response, Self::Error>) -> Result<Response, Error> + Clone,Maps this service's result type (
Result<Self::Response, Self::Error>) to a different value, regardless of whether the future succeeds or fails.This is similar to the
map_responseandmap_errcombinators, except that the same function is invoked when the service's future completes, whether it completes successfully or fails. This function takes theResultreturned by the service's future, and returns aResult.Like the standard library's
Result::and_then, this method can be used to implement control flow based onResultvalues. For example, it may be used to implement error recovery, by turning someErrresponses from the service intoOkresponses. Similarly, some successful responses from the service could be rejected, by returning anErrconditionally, depending on the value inside theOk. Finally, this method can also be used to implement behaviors that must run when a service's future completes, regardless of whether it succeeded or failed.This method can be used to change the
Responsetype of the service into a different type. It can also be used to change theErrortype of the service. However, because themap_resultfunction is not applied to the errors returned by the service'spoll_readymethod, it must be possible to convert the service'sErrortype into the error type returned by themap_resultfunction. This is trivial when the function returns the same error type as the service, but in other cases, it can be useful to useBoxErrorto erase differing error types.Examples
Recovering from certain errors:
# use std::task::{Poll, Context}; # use tower::{Service, ServiceExt}; # # struct DatabaseService; # impl DatabaseService { # fn new(address: &str) -> Self { # DatabaseService # } # } # # struct Record { # pub name: String, # pub age: u16 # } # #[derive(Debug)] # enum DbError { # Parse(std::num::ParseIntError), # NoRecordsFound, # } # # impl Service<u32> for DatabaseService { # type Response = Vec<Record>; # type Error = DbError; # type Future = std::future::Ready<Result<Vec<Record>, DbError>>; # # fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { # Poll::Ready(Ok(())) # } # # fn call(&mut self, request: u32) -> Self::Future { # std::future::ready(Ok(vec![Record { name: "Jack".into(), age: 32 }])) # } # } # # fn main() { # async { // A service returning Result<Vec<Record>, DbError> let service = DatabaseService::new("127.0.0.1:8080"); // If the database returns no records for the query, we just want an empty `Vec`. let mut new_service = service.map_result(|result| match result { // If the error indicates that no records matched the query, return an empty // `Vec` instead. Err(DbError::NoRecordsFound) => Ok(Vec::new()), // Propagate all other responses (`Ok` and `Err`) unchanged x => x, }); // Call the new service let id = 13; let name = new_service .ready() .await? .call(id) .await?; # Ok::<(), DbError>(()) # }; # }Rejecting some
Okresponses:# use std::task::{Poll, Context}; # use tower::{Service, ServiceExt}; # # struct DatabaseService; # impl DatabaseService { # fn new(address: &str) -> Self { # DatabaseService # } # } # # struct Record { # pub name: String, # pub age: u16 # } # type DbError = String; # type AppError = String; # # impl Service<u32> for DatabaseService { # type Response = Record; # type Error = DbError; # type Future = std::future::Ready<Result<Record, DbError>>; # # fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { # Poll::Ready(Ok(())) # } # # fn call(&mut self, request: u32) -> Self::Future { # std::future::ready(Ok(Record { name: "Jack".into(), age: 32 })) # } # } # # fn main() { # async { use tower::BoxError; // A service returning Result<Record, DbError> let service = DatabaseService::new("127.0.0.1:8080"); // If the user is zero years old, return an error. let mut new_service = service.map_result(|result| { let record = result?; if record.age == 0 { // Users must have been born to use our app! let app_error = AppError::from("users cannot be 0 years old!"); // Box the error to erase its type (as it can be an `AppError` // *or* the inner service's `DbError`). return Err(BoxError::from(app_error)); } // Otherwise, return the record. Ok(record) }); // Call the new service let id = 13; let record = new_service .ready() .await? .call(id) .await?; # Ok::<(), BoxError>(()) # }; # }Performing an action that must be run for both successes and failures:
# use std::convert::TryFrom; # use std::task::{Poll, Context}; # use tower::{Service, ServiceExt}; # # struct DatabaseService; # impl DatabaseService { # fn new(address: &str) -> Self { # DatabaseService # } # } # # impl Service<u32> for DatabaseService { # type Response = String; # type Error = u8; # type Future = std::future::Ready<Result<String, u8>>; # # fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { # Poll::Ready(Ok(())) # } # # fn call(&mut self, request: u32) -> Self::Future { # std::future::ready(Ok(String::new())) # } # } # # fn main() { # async { // A service returning Result<Record, DbError> let service = DatabaseService::new("127.0.0.1:8080"); // Print a message whenever a query completes. let mut new_service = service.map_result(|result| { println!("query completed; success={}", result.is_ok()); result }); // Call the new service let id = 13; let response = new_service .ready() .await? .call(id) .await; # response # }; # }fn map_request<F, NewRequest>(self, f: F) -> MapRequest<Self, F> where Self: Sized, F: FnMut(NewRequest) -> Request,Composes a function in front of the service.
This adapter produces a new service that passes each value through the given function
fbefore sending it toself.Example
# use std::convert::TryFrom; # use std::task::{Poll, Context}; # use tower::{Service, ServiceExt}; # # struct DatabaseService; # impl DatabaseService { # fn new(address: &str) -> Self { # DatabaseService # } # } # # impl Service<String> for DatabaseService { # type Response = String; # type Error = u8; # type Future = std::future::Ready<Result<String, u8>>; # # fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { # Poll::Ready(Ok(())) # } # # fn call(&mut self, request: String) -> Self::Future { # std::future::ready(Ok(String::new())) # } # } # # fn main() { # async { // A service taking a String as a request let service = DatabaseService::new("127.0.0.1:8080"); // Map the request to a new request let mut new_service = service.map_request(|id: u32| id.to_string()); // Call the new service let id = 13; let response = new_service .ready() .await? .call(id) .await; # response # }; # }fn filter<F, NewRequest>(self, filter: F) -> Filter<Self, F> where Self: Sized, F: Predicate<NewRequest>,Composes this service with a
Filterthat conditionally accepts or rejects requests based on a predicate.This adapter produces a new service that passes each value through the given function
predicatebefore sending it toself.Example
# use std::convert::TryFrom; # use std::task::{Poll, Context}; # use tower::{Service, ServiceExt}; # # struct DatabaseService; # impl DatabaseService { # fn new(address: &str) -> Self { # DatabaseService # } # } # # #[derive(Debug)] enum DbError { # Parse(std::num::ParseIntError) # } # # impl std::fmt::Display for DbError { # fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { std::fmt::Debug::fmt(self, f) } # } # impl std::error::Error for DbError {} # impl Service<u32> for DatabaseService { # type Response = String; # type Error = DbError; # type Future = std::future::Ready<Result<String, DbError>>; # # fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { # Poll::Ready(Ok(())) # } # # fn call(&mut self, request: u32) -> Self::Future { # std::future::ready(Ok(String::new())) # } # } # # fn main() { # async { // A service taking a u32 as a request and returning Result<_, DbError> let service = DatabaseService::new("127.0.0.1:8080"); // Fallibly map the request to a new request let mut new_service = service .filter(|id_str: &str| id_str.parse().map_err(DbError::Parse)); // Call the new service let id = "13"; let response = new_service .ready() .await? .call(id) .await; # response # }; # }fn filter_async<F, NewRequest>(self, filter: F) -> AsyncFilter<Self, F> where Self: Sized, F: AsyncPredicate<NewRequest>,Composes this service with an
AsyncFilterthat conditionally accepts or rejects requests based on an [async predicate].This adapter produces a new service that passes each value through the given function
predicatebefore sending it toself.Example
# use std::convert::TryFrom; # use std::task::{Poll, Context}; # use tower::{Service, ServiceExt}; # # #[derive(Clone)] struct DatabaseService; # impl DatabaseService { # fn new(address: &str) -> Self { # DatabaseService # } # } # #[derive(Debug)] # enum DbError { # Rejected # } # impl std::fmt::Display for DbError { # fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { std::fmt::Debug::fmt(self, f) } # } # impl std::error::Error for DbError {} # # impl Service<u32> for DatabaseService { # type Response = String; # type Error = DbError; # type Future = std::future::Ready<Result<String, DbError>>; # # fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { # Poll::Ready(Ok(())) # } # # fn call(&mut self, request: u32) -> Self::Future { # std::future::ready(Ok(String::new())) # } # } # # fn main() { # async { // A service taking a u32 as a request and returning Result<_, DbError> let service = DatabaseService::new("127.0.0.1:8080"); /// Returns `true` if we should query the database for an ID. async fn should_query(id: u32) -> bool { // ... # true } // Filter requests based on `should_query`. let mut new_service = service .filter_async(|id: u32| async move { if should_query(id).await { return Ok(id); } Err(DbError::Rejected) }); // Call the new service let id = 13; # let id: u32 = id; let response = new_service .ready() .await? .call(id) .await; # response # }; # }fn then<F, Response, Error, Fut>(self, f: F) -> Then<Self, F> where Self: Sized, Error: From<Self::Error>, F: FnOnce(Result<Self::Response, Self::Error>) -> Fut + Clone, Fut: Future<Output = Result<Response, Error>>,Composes an asynchronous function after this service.
This takes a function or closure returning a future, and returns a new
Servicethat chains that function after this service'sFuture. The newService's future will consist of this service's future, followed by the future returned by calling the chained function with the future'sOutputtype. The chained function is called regardless of whether this service's future completes with a successful response or with an error.This method can be thought of as an equivalent to the
futurescrate'sFutureExt::thencombinator, but acting onServices that return futures, rather than on an individual future. Similarly to that combinator,ServiceExt::thencan be used to implement asynchronous error recovery, by calling some asynchronous function with errors returned by this service. Alternatively, it may also be used to call a fallible async function with the successful response of this service.This method can be used to change the
Responsetype of the service into a different type. It can also be used to change theErrortype of the service. However, because thethenfunction is not applied to the errors returned by the service'spoll_readymethod, it must be possible to convert the service'sErrortype into the error type returned by thethenfuture. This is trivial when the function returns the same error type as the service, but in other cases, it can be useful to useBoxErrorto erase differing error types.Examples
# use std::task::{Poll, Context}; # use tower::{Service, ServiceExt}; # # struct DatabaseService; # impl DatabaseService { # fn new(address: &str) -> Self { # DatabaseService # } # } # # type Record = (); # type DbError = (); # # impl Service<u32> for DatabaseService { # type Response = Record; # type Error = DbError; # type Future = std::future::Ready<Result<Record, DbError>>; # # fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { # Poll::Ready(Ok(())) # } # # fn call(&mut self, request: u32) -> Self::Future { # std::future::ready(Ok(())) # } # } # # fn main() { // A service returning Result<Record, DbError> let service = DatabaseService::new("127.0.0.1:8080"); // An async function that attempts to recover from errors returned by the // database. async fn recover_from_error(error: DbError) -> Result<Record, DbError> { // ... # Ok(()) } # async { // If the database service returns an error, attempt to recover by // calling `recover_from_error`. Otherwise, return the successful response. let mut new_service = service.then(|result| async move { match result { Ok(record) => Ok(record), Err(e) => recover_from_error(e).await, } }); // Call the new service let id = 13; let record = new_service .ready() .await? .call(id) .await?; # Ok::<(), DbError>(()) # }; # }fn map_future<F, Fut, Response, Error>(self, f: F) -> MapFuture<Self, F> where Self: Sized, F: FnMut(Self::Future) -> Fut, Error: From<Self::Error>, Fut: Future<Output = Result<Response, Error>>,Composes a function that transforms futures produced by the service.
This takes a function or closure returning a future computed from the future returned by the service's
callmethod, as opposed to the responses produced by the future.Examples
# use std::task::{Poll, Context}; # use tower::{Service, ServiceExt, BoxError}; # # struct DatabaseService; # impl DatabaseService { # fn new(address: &str) -> Self { # DatabaseService # } # } # # type Record = (); # type DbError = crate::BoxError; # # impl Service<u32> for DatabaseService { # type Response = Record; # type Error = DbError; # type Future = std::future::Ready<Result<Record, DbError>>; # # fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { # Poll::Ready(Ok(())) # } # # fn call(&mut self, request: u32) -> Self::Future { # std::future::ready(Ok(())) # } # } # # fn main() { use std::time::Duration; use tokio::time::timeout; // A service returning Result<Record, DbError> let service = DatabaseService::new("127.0.0.1:8080"); # async { let mut new_service = service.map_future(|future| async move { let res = timeout(Duration::from_secs(1), future).await?; Ok::<_, BoxError>(res) }); // Call the new service let id = 13; let record = new_service .ready() .await? .call(id) .await?; # Ok::<(), BoxError>(()) # }; # }Note that normally you wouldn't implement timeouts like this and instead use
Timeout.fn boxed(self) -> BoxService<Request, Self::Response, Self::Error> where Self: Sized + Send + 'static, Self::Future: Send + 'static,Convert the service into a
Service+Sendtrait object.See
BoxServicefor more details.If
Selfimplements theClonetrait, theboxed_clonemethod can be used instead, to produce a boxed service which will also implementClone.Example
use tower::{Service, ServiceExt, BoxError, service_fn, util::BoxService}; # # struct Request; # struct Response; # impl Response { # fn new() -> Self { Self } # } let service = service_fn(|req: Request| async { Ok::<_, BoxError>(Response::new()) }); let service: BoxService<Request, Response, BoxError> = service .map_request(|req| { println!("received request"); req }) .map_response(|res| { println!("response produced"); res }) .boxed(); # let service = assert_service(service); # fn assert_service<S, R>(svc: S) -> S # where S: Service<R> { svc }fn boxed_clone(self) -> BoxCloneService<Request, Self::Response, Self::Error> where Self: Clone + Sized + Send + 'static, Self::Future: Send + 'static,Convert the service into a
Service+Clone+Sendtrait object.This is similar to the
boxedmethod, but it requires thatSelfimplementClone, and the returned boxed service implementsClone. SeeBoxCloneServicefor more details.Example
use tower::{Service, ServiceExt, BoxError, service_fn, util::BoxCloneService}; # # struct Request; # struct Response; # impl Response { # fn new() -> Self { Self } # } let service = service_fn(|req: Request| async { Ok::<_, BoxError>(Response::new()) }); let service: BoxCloneService<Request, Response, BoxError> = service .map_request(|req| { println!("received request"); req }) .map_response(|res| { println!("response produced"); res }) .boxed_clone(); // The boxed service can still be cloned. service.clone(); # let service = assert_service(service); # fn assert_service<S, R>(svc: S) -> S # where S: Service<R> { svc }
Implementors
impl<T, Request> ServiceExt<Request> for AndThen<S, F> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for AsService<'a, M, Request> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for AsyncFilter<T, U> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for Balance<D, Req> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for BoxCloneService<T, U, E> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for BoxCloneSyncService<T, U, E> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for BoxService<T, U, E> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for Buffer<Req, F> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for ConcurrencyLimit<T> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for Constant<T, M> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for Either<A, B> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for Filter<T, U> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for FutureService<F, S> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for Hedge<S, P> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for IntoService<M, Request> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for LoadShed<S> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for MakeBalance<S, Req> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for MapErr<S, F> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for MapFuture<S, F> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for MapRequest<S, F> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for MapResponse<S, F> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for MapResult<S, F> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for Optional<T> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for PeakEwma<S, C> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for PendingRequests<S, C> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for RateLimit<T> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for Reconnect<M, Target> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for Retry<P, S> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for ServiceFn<T> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for Shared<S> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for SpawnReady<S> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for Steer<S, F, Req> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for T where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for Then<S, F> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for Timeout<T> where T: Service<Request> + ?Sized,impl<T, Request> ServiceExt<Request> for UnsyncBoxService<T, U, E> where T: Service<Request> + ?Sized,