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
use crate::AsyncServiceWrapper;

/// Extension for a [`tower::Service`] to turn it into an async [`Service`].
///
/// [`tower::Service`]: https://docs.rs/tower/*/tower/trait.Service.html
/// [`Service`]: https://docs.rs/tower-async/*/tower_async/trait.Service.html
pub trait AsyncServiceExt<Request>: tower_service::Service<Request> {
    /// Turn this [`tower::Service`] into a [`tower_async_service::Service`].
    ///
    /// [`tower::Service`]: https://docs.rs/tower-service/*/tower_service/trait.Service.html
    /// [`tower_async_service::Service`]: https://docs.rs/tower-async/*/tower_async/trait.Service.html
    fn into_async(self) -> AsyncServiceWrapper<Self>
    where
        Self: Sized,
    {
        AsyncServiceWrapper::new(self)
    }
}

impl<S, Request> AsyncServiceExt<Request> for S where S: tower_service::Service<Request> {}

#[cfg(test)]
mod tests {
    use super::*;

    use std::{
        convert::Infallible,
        future::Future,
        pin::Pin,
        task::{Context, Poll},
        time::Duration,
    };

    use tower::{service_fn, Service};
    use tower_async::{
        make::Shared, MakeService, Service as AsyncService, ServiceBuilder, ServiceExt,
    };

    struct EchoService;

    impl Service<String> for EchoService {
        type Response = String;
        type Error = Infallible;
        type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

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

        fn call(&mut self, req: String) -> Self::Future {
            // create a response in a future.
            let fut = async { Ok(req) };

            // Return the response as an immediate future
            Box::pin(fut)
        }
    }

    struct AsyncEchoService;

    impl tower_async::Service<String> for AsyncEchoService {
        type Response = String;
        type Error = Infallible;

        async fn call(&self, req: String) -> Result<Self::Response, Self::Error> {
            Ok(req)
        }
    }

    #[tokio::test]
    async fn test_async_service_ext() {
        let service = EchoService;
        let service = ServiceBuilder::new()
            .timeout(Duration::from_secs(1))
            .service(service.into_async()); // use tower service as async service

        let response = service.oneshot("hello".to_string()).await.unwrap();
        assert_eq!(response, "hello");
    }

    async fn echo<R>(req: R) -> Result<R, Infallible> {
        Ok(req)
    }

    #[tokio::test]
    async fn as_make_service() {
        let service = Shared::new(service_fn(echo::<&'static str>).into_async());

        let svc = service.make_service(()).await.unwrap();

        let res = svc.call("foo").await.unwrap();

        assert_eq!(res, "foo");
    }
}