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
use crate::request_meta::RequestMeta;
use hyper::{body::HttpBody, service::Service};
use routerify::{RequestServiceBuilder, Router};
use std::{
convert::Infallible,
future::{ready, Ready},
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
task::{Context, Poll},
};
use tower::util::{BoxService, ServiceExt};
#[derive(Debug)]
pub struct UnixRouterService<B, E>
where
B: HttpBody + Send + Sync + 'static,
{
builder: RequestServiceBuilder<B, E>,
}
impl<
B: HttpBody + Send + Sync + 'static,
E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
> UnixRouterService<B, E>
{
pub fn new(router: Router<B, E>) -> routerify::Result<UnixRouterService<B, E>> {
let builder = RequestServiceBuilder::new(router)?;
Ok(UnixRouterService { builder })
}
}
impl<
B: HttpBody + Send + Sync + 'static,
E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
> Service<&tokio::net::UnixStream> for UnixRouterService<B, E>
{
type Response =
BoxService<hyper::Request<hyper::Body>, hyper::Response<B>, routerify::RouteError>;
type Error = Infallible;
type Future = Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, conn: &tokio::net::UnixStream) -> Self::Future {
let loopback = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 0));
let meta = RequestMeta::new(conn);
let req_service = self.builder.build(loopback).map_request(
move |mut req: hyper::Request<hyper::Body>| {
let ext = req.extensions_mut();
if ext.get_mut::<RequestMeta>().is_none() {
ext.insert(meta.clone());
}
req
},
);
ready(Ok(BoxService::new(req_service)))
}
}