tower_make/
make_service.rs

1use crate::sealed::Sealed;
2use std::future::Future;
3use std::task::{Context, Poll};
4use tower_service::Service;
5
6/// Creates new `Service` values.
7///
8/// Acts as a service factory. This is useful for cases where new `Service`
9/// values must be produced. One case is a TCP server listener. The listener
10/// accepts new TCP streams, obtains a new `Service` value using the
11/// `MakeService` trait, and uses that new `Service` value to process inbound
12/// requests on that new TCP stream.
13///
14/// This is essentially a trait alias for a `Service` of `Service`s.
15pub trait MakeService<Target, Request>: Sealed<(Target, Request)> {
16    /// Responses given by the service
17    type Response;
18
19    /// Errors produced by the service
20    type Error;
21
22    /// The `Service` value created by this factory
23    type Service: Service<Request, Response = Self::Response, Error = Self::Error>;
24
25    /// Errors produced while building a service.
26    type MakeError;
27
28    /// The future of the `Service` instance.
29    type Future: Future<Output = Result<Self::Service, Self::MakeError>>;
30
31    /// Returns `Ready` when the factory is able to create more services.
32    ///
33    /// If the service is at capacity, then `Poll::Pending` is returned and the task
34    /// is notified when the service becomes ready again. This function is
35    /// expected to be called while on a task.
36    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::MakeError>>;
37
38    /// Create and return a new service value asynchronously.
39    fn make_service(&mut self, target: Target) -> Self::Future;
40}
41
42impl<M, S, Target, Request> Sealed<(Target, Request)> for M
43where
44    M: Service<Target, Response = S>,
45    S: Service<Request>,
46{
47}
48
49impl<M, S, Target, Request> MakeService<Target, Request> for M
50where
51    M: Service<Target, Response = S>,
52    S: Service<Request>,
53{
54    type Response = S::Response;
55    type Error = S::Error;
56    type Service = S;
57    type MakeError = M::Error;
58    type Future = M::Future;
59
60    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::MakeError>> {
61        Service::poll_ready(self, cx)
62    }
63
64    fn make_service(&mut self, target: Target) -> Self::Future {
65        Service::call(self, target)
66    }
67}