Skip to main content

hyper_util/service/
glue.rs

1use pin_project_lite::pin_project;
2use std::{
3    pin::Pin,
4    task::{Context, Poll},
5};
6
7use super::Oneshot;
8
9/// A tower [`Service`][tower-svc] converted into a hyper [`Service`][hyper-svc].
10///
11/// This wraps an inner tower service `S` in a [`hyper::service::Service`] implementation. See
12/// the module-level documentation of [`service`][crate::service] for more information about using
13/// [`tower`][tower] services and middleware with [`hyper`].
14///
15/// [hyper-svc]: hyper::service::Service
16/// [tower]: https://docs.rs/tower/latest/tower/
17/// [tower-svc]: https://docs.rs/tower/latest/tower/trait.Service.html
18#[derive(Debug, Copy, Clone)]
19pub struct TowerToHyperService<S> {
20    service: S,
21}
22
23impl<S> TowerToHyperService<S> {
24    /// Create a new [`TowerToHyperService`] from a tower service.
25    pub fn new(tower_service: S) -> Self {
26        Self {
27            service: tower_service,
28        }
29    }
30}
31
32impl<S, R> hyper::service::Service<R> for TowerToHyperService<S>
33where
34    S: tower_service::Service<R> + Clone,
35{
36    type Response = S::Response;
37    type Error = S::Error;
38    type Future = TowerToHyperServiceFuture<S, R>;
39
40    fn call(&self, req: R) -> Self::Future {
41        TowerToHyperServiceFuture {
42            future: Oneshot::new(self.service.clone(), req),
43        }
44    }
45}
46
47pin_project! {
48    /// Response future for [`TowerToHyperService`].
49    ///
50    /// This future is acquired by [`call`][hyper::service::Service::call]ing a
51    /// [`TowerToHyperService`].
52    pub struct TowerToHyperServiceFuture<S, R>
53    where
54        S: tower_service::Service<R>,
55    {
56        #[pin]
57        future: Oneshot<S, R>,
58    }
59}
60
61impl<S, R> Future for TowerToHyperServiceFuture<S, R>
62where
63    S: tower_service::Service<R>,
64{
65    type Output = Result<S::Response, S::Error>;
66
67    #[inline]
68    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
69        self.project().future.poll(cx)
70    }
71}