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
use std::{
    future::Future,
    pin::Pin,
    task::{Context, Poll},
};

use tower::{util::Oneshot, ServiceExt as _};

/// A hyper service that wraps a tower service.
#[derive(Debug, Clone)]
pub struct TowerHyperService<S> {
    service: S,
}

impl<S> TowerHyperService<S> {
    /// Create a new `TowerHyperService` around a tower::Service.
    pub fn new(inner: S) -> Self {
        Self { service: inner }
    }
}

impl<S, R> hyper::service::Service<R> for TowerHyperService<S>
where
    S: tower::Service<R> + Clone,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = TowerHyperFuture<S, R>;

    fn call(&self, req: R) -> Self::Future {
        TowerHyperFuture {
            future: self.service.clone().oneshot(req),
        }
    }
}

/// A future returned by `TowerHyperService`.
#[pin_project::pin_project]
#[derive(Debug)]
pub struct TowerHyperFuture<S, R>
where
    S: tower::Service<R>,
{
    #[pin]
    future: Oneshot<S, R>,
}

impl<S, R> Future for TowerHyperFuture<S, R>
where
    S: tower::Service<R>,
{
    type Output = Result<S::Response, S::Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        self.project().future.poll(cx)
    }
}