tower_async/util/
then.rs

1use std::{fmt, future::Future};
2
3use tower_async_layer::Layer;
4use tower_async_service::Service;
5
6/// [`Service`] returned by the [`then`] combinator.
7///
8/// [`then`]: crate::util::ServiceExt::then
9#[derive(Clone)]
10pub struct Then<S, F> {
11    inner: S,
12    f: F,
13}
14
15impl<S, F> fmt::Debug for Then<S, F>
16where
17    S: fmt::Debug,
18{
19    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20        f.debug_struct("Then")
21            .field("inner", &self.inner)
22            .field("f", &format_args!("{}", std::any::type_name::<F>()))
23            .finish()
24    }
25}
26
27/// A [`Layer`] that produces a [`Then`] service.
28///
29/// [`Layer`]: tower_async_layer::Layer
30#[derive(Debug, Clone)]
31pub struct ThenLayer<F> {
32    f: F,
33}
34
35impl<S, F> Then<S, F> {
36    /// Creates a new `Then` service.
37    pub fn new(inner: S, f: F) -> Self {
38        Then { f, inner }
39    }
40
41    /// Returns a new [`Layer`] that produces [`Then`] services.
42    ///
43    /// This is a convenience function that simply calls [`ThenLayer::new`].
44    ///
45    /// [`Layer`]: tower_async_layer::Layer
46    pub fn layer(f: F) -> ThenLayer<F> {
47        ThenLayer { f }
48    }
49}
50
51impl<S, F, Request, Response, Error, Fut> Service<Request> for Then<S, F>
52where
53    S: Service<Request>,
54    S::Error: Into<Error>,
55    F: Fn(Result<S::Response, S::Error>) -> Fut,
56    Fut: Future<Output = Result<Response, Error>>,
57{
58    type Response = Response;
59    type Error = Error;
60
61    #[inline]
62    async fn call(&self, request: Request) -> Result<Self::Response, Self::Error> {
63        let result = self.inner.call(request).await;
64        (self.f)(result).await
65    }
66}
67
68impl<F> ThenLayer<F> {
69    /// Creates a new [`ThenLayer`] layer.
70    pub fn new(f: F) -> Self {
71        ThenLayer { f }
72    }
73}
74
75impl<S, F> Layer<S> for ThenLayer<F>
76where
77    F: Clone,
78{
79    type Service = Then<S, F>;
80
81    fn layer(&self, inner: S) -> Self::Service {
82        Then {
83            f: self.f.clone(),
84            inner,
85        }
86    }
87}