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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
use futures_util::ready;
use http::{header::HeaderName, HeaderValue, Request, Response};
use pin_project_lite::pin_project;
use std::future::Future;
use std::{
pin::Pin,
task::{Context, Poll},
};
use tower_layer::Layer;
use tower_service::Service;
#[derive(Clone, Debug)]
pub struct PropagateHeaderLayer {
header: HeaderName,
}
impl PropagateHeaderLayer {
pub fn new(header: HeaderName) -> Self {
Self { header }
}
}
impl<S> Layer<S> for PropagateHeaderLayer {
type Service = PropagateHeader<S>;
fn layer(&self, inner: S) -> Self::Service {
PropagateHeader {
inner,
header: self.header.clone(),
}
}
}
#[derive(Clone, Debug)]
pub struct PropagateHeader<S> {
inner: S,
header: HeaderName,
}
impl<S> PropagateHeader<S> {
pub fn new(inner: S, header: HeaderName) -> Self {
Self { inner, header }
}
define_inner_service_accessors!();
pub fn layer(header: HeaderName) -> PropagateHeaderLayer {
PropagateHeaderLayer::new(header)
}
}
impl<ReqBody, ResBody, S> Service<Request<ReqBody>> for PropagateHeader<S>
where
S: Service<Request<ReqBody>, Response = Response<ResBody>>,
{
type Response = S::Response;
type Error = S::Error;
type Future = ResponseFuture<S::Future>;
#[inline]
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
let value = req.headers().get(&self.header).cloned();
ResponseFuture {
future: self.inner.call(req),
header_and_value: Some(self.header.clone()).zip(value),
}
}
}
pin_project! {
#[derive(Debug)]
pub struct ResponseFuture<F> {
#[pin]
future: F,
header_and_value: Option<(HeaderName, HeaderValue)>,
}
}
impl<F, ResBody, E> Future for ResponseFuture<F>
where
F: Future<Output = Result<Response<ResBody>, E>>,
{
type Output = F::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let mut res = ready!(this.future.poll(cx)?);
if let Some((header, value)) = this.header_and_value.take() {
res.headers_mut().insert(header, value);
}
Poll::Ready(Ok(res))
}
}