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