1use futures_core::TryFuture;
2use futures_util::{future, TryFutureExt};
3use std::fmt;
4use std::future::Future;
5use std::pin::Pin;
6use std::task::{Context, Poll};
7use tower_layer::Layer;
8use tower_service::Service;
9
10#[derive(Clone)]
14pub struct AndThen<S, F> {
15 inner: S,
16 f: F,
17}
18
19impl<S, F> fmt::Debug for AndThen<S, F>
20where
21 S: fmt::Debug,
22{
23 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24 f.debug_struct("AndThen")
25 .field("inner", &self.inner)
26 .field("f", &format_args!("{}", std::any::type_name::<F>()))
27 .finish()
28 }
29}
30
31pin_project_lite::pin_project! {
32 pub struct AndThenFuture<F1, F2: TryFuture, N> {
36 #[pin]
37 inner: future::AndThen<future::ErrInto<F1, F2::Error>, F2, N>,
38 }
39}
40
41impl<F1, F2: TryFuture, N> AndThenFuture<F1, F2, N> {
42 pub(crate) fn new(inner: future::AndThen<future::ErrInto<F1, F2::Error>, F2, N>) -> Self {
43 Self { inner }
44 }
45}
46
47impl<F1, F2: TryFuture, N> std::fmt::Debug for AndThenFuture<F1, F2, N> {
48 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49 f.debug_tuple("AndThenFuture")
50 .field(&format_args!("..."))
51 .finish()
52 }
53}
54
55impl<F1, F2: TryFuture, N> Future for AndThenFuture<F1, F2, N>
56where
57 future::AndThen<future::ErrInto<F1, F2::Error>, F2, N>: Future,
58{
59 type Output = <future::AndThen<future::ErrInto<F1, F2::Error>, F2, N> as Future>::Output;
60
61 #[inline]
62 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
63 self.project().inner.poll(cx)
64 }
65}
66
67#[derive(Clone, Debug)]
71pub struct AndThenLayer<F> {
72 f: F,
73}
74
75impl<S, F> AndThen<S, F> {
76 pub const fn new(inner: S, f: F) -> Self {
78 AndThen { f, inner }
79 }
80
81 pub fn layer(f: F) -> AndThenLayer<F> {
87 AndThenLayer { f }
88 }
89}
90
91impl<S, F, Request, Fut> Service<Request> for AndThen<S, F>
92where
93 S: Service<Request>,
94 S::Error: Into<Fut::Error>,
95 F: FnOnce(S::Response) -> Fut + Clone,
96 Fut: TryFuture,
97{
98 type Response = Fut::Ok;
99 type Error = Fut::Error;
100 type Future = AndThenFuture<S::Future, Fut, F>;
101
102 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
103 self.inner.poll_ready(cx).map_err(Into::into)
104 }
105
106 fn call(&mut self, request: Request) -> Self::Future {
107 AndThenFuture::new(self.inner.call(request).err_into().and_then(self.f.clone()))
108 }
109}
110
111impl<F> AndThenLayer<F> {
112 pub const fn new(f: F) -> Self {
114 AndThenLayer { f }
115 }
116}
117
118impl<S, F> Layer<S> for AndThenLayer<F>
119where
120 F: Clone,
121{
122 type Service = AndThen<S, F>;
123
124 fn layer(&self, inner: S) -> Self::Service {
125 AndThen {
126 f: self.f.clone(),
127 inner,
128 }
129 }
130}