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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
//! Tower middleware for collecting connection information after a handshake has been completed.
//!
//! This middleware applies to the request stack, but recieves the connection info from the acceptor stack.

use std::{fmt, task::Poll};

use hyper::{Request, Response};
use tower::{Layer, Service};

use crate::info::{ConnectionInfo, HasConnectionInfo};
use crate::service::ServiceRef;

/// A middleware which adds connection information to the request extensions.
///
/// This layer is meant to be applied to the "make service" part of the stack:
/// ```rust
/// # use std::convert::Infallible;
/// # use http::{Request, Response};
/// # use hyperdriver::Body;
/// # use hyperdriver::info::ConnectionInfo;
/// # use hyperdriver::server::conn::MakeServiceConnectionInfoLayer;
/// # use tower::Layer;
/// use hyperdriver::service::{make_service_fn, service_fn};
/// use tower::make::Shared;
///
/// # async fn make_service_with_layer() {
///
/// let service = service_fn(|req: Request<Body>| async move {
///    let info = req.extensions().get::<ConnectionInfo>().unwrap();
///    println!("Connection info: {:?}", info);
///    Ok::<_, Infallible>(Response::new(Body::from("Hello, World!")))
/// });
///
/// let make_service = MakeServiceConnectionInfoLayer::default().layer(Shared::new(service));
/// # }
///
///
#[derive(Clone, Default)]
pub struct MakeServiceConnectionInfoLayer {
    _priv: (),
}

impl MakeServiceConnectionInfoLayer {
    /// Create a new `MakeServiceConnectionInfoLayer`.
    pub fn new() -> Self {
        Self { _priv: () }
    }
}

impl fmt::Debug for MakeServiceConnectionInfoLayer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MakeServiceConnectionInfoLayer").finish()
    }
}

impl<S> Layer<S> for MakeServiceConnectionInfoLayer {
    type Service = MakeServiceConnectionInfoService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        MakeServiceConnectionInfoService::new(inner)
    }
}

/// A service which adds connection information to the request extensions.
///
/// This is applied to the "make service" part of the stack.
///
/// See [`MakeServiceConnectionInfoLayer`] for more details.
#[derive(Debug, Clone)]
pub struct MakeServiceConnectionInfoService<C> {
    inner: C,
}

impl<C> MakeServiceConnectionInfoService<C> {
    /// Create a new `StartConnectionInfoService` wrapping `inner` service,
    /// and applying `info` to the request extensions.
    pub fn new(inner: C) -> Self {
        Self { inner }
    }
}

impl<C, IO> Service<&IO> for MakeServiceConnectionInfoService<C>
where
    C: ServiceRef<IO> + Clone + Send + 'static,
    IO: HasConnectionInfo + Send + 'static,
    IO::Addr: Clone + Send + Sync + 'static,
{
    type Response = ConnectionWithInfo<C::Response, IO::Addr>;

    type Error = C::Error;

    type Future = future::MakeServiceConnectionInfoFuture<C, IO>;

    fn poll_ready(
        &mut self,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, stream: &IO) -> Self::Future {
        let mut inner = self.inner.clone();
        let info = stream.info();
        future::MakeServiceConnectionInfoFuture::new(inner.call(stream), info)
    }
}

mod future {

    use pin_project::pin_project;
    use std::future::Future;

    use crate::service::ServiceRef;

    use super::*;

    #[pin_project]
    #[derive(Debug)]
    pub struct MakeServiceConnectionInfoFuture<S, IO>
    where
        S: ServiceRef<IO>,
        IO: HasConnectionInfo,
    {
        #[pin]
        inner: S::Future,
        info: Option<ConnectionInfo<IO::Addr>>,
    }

    impl<S, IO> MakeServiceConnectionInfoFuture<S, IO>
    where
        S: ServiceRef<IO>,
        IO: HasConnectionInfo,
    {
        pub(super) fn new(inner: S::Future, info: ConnectionInfo<IO::Addr>) -> Self {
            Self {
                inner,
                info: Some(info),
            }
        }
    }

    impl<S, IO> Future for MakeServiceConnectionInfoFuture<S, IO>
    where
        S: ServiceRef<IO>,
        IO: HasConnectionInfo,
    {
        type Output = Result<ConnectionWithInfo<S::Response, IO::Addr>, S::Error>;

        fn poll(
            self: std::pin::Pin<&mut Self>,
            cx: &mut std::task::Context<'_>,
        ) -> Poll<Self::Output> {
            let this = self.project();

            match this.inner.poll(cx) {
                Poll::Ready(Ok(inner)) => Poll::Ready(Ok(ConnectionWithInfo {
                    inner,
                    info: this.info.take(),
                })),
                Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
                Poll::Pending => Poll::Pending,
            }
        }
    }
}

/// Interior service which adds connection information to the request extensions.
///
/// This service wraps the request/response service, not the connector service.
#[derive(Debug, Clone)]
pub struct ConnectionWithInfo<S, A> {
    inner: S,
    info: Option<ConnectionInfo<A>>,
}

impl<S, A, BIn, BOut> Service<Request<BIn>> for ConnectionWithInfo<S, A>
where
    S: Service<Request<BIn>, Response = Response<BOut>> + Clone + Send + 'static,
    S::Future: Send,
    S::Error: fmt::Display,
    BIn: Send + 'static,
    A: Clone + Send + Sync + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = S::Future;

    fn poll_ready(&mut self, cx: &mut std::task::Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut req: Request<BIn>) -> Self::Future {
        let next = self.inner.clone();
        let mut inner = std::mem::replace(&mut self.inner, next);

        if let Some(info) = self.info.take() {
            req.extensions_mut().insert(info);
        } else {
            tracing::error!("Connection called twice, info is not available");
        }
        inner.call(req)
    }
}

#[cfg(test)]
mod tests {

    use std::convert::Infallible;

    use tower::{make::Shared, ServiceBuilder};

    use crate::{info::DuplexAddr, server::conn::AcceptExt as _};

    use super::*;

    #[tokio::test]
    async fn connection_info_from_service() {
        let service = tower::service_fn(|req: http::Request<crate::Body>| {
            let info = req
                .extensions()
                .get::<ConnectionInfo<DuplexAddr>>()
                .unwrap();
            assert_eq!(*info.remote_addr(), DuplexAddr::new());
            async { Ok::<_, Infallible>(Response::new(())) }
        });

        let mut make_service = ServiceBuilder::new()
            .layer(MakeServiceConnectionInfoLayer::new())
            .service(Shared::new(service));

        let (client, incoming) = crate::stream::duplex::pair();

        let (_, conn) = tokio::try_join!(client.connect(1024), incoming.accept()).unwrap();

        let req = http::Request::new(crate::Body::empty());
        let mut svc = tower::Service::call(&mut make_service, &conn)
            .await
            .unwrap();

        svc.call(req).await.unwrap();
    }
}