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
use futures_util::ready;
use pin_project::{pin_project, project};
use std::{
    future::Future,
    pin::Pin,
    task::{Context, Poll},
};
use tower_service::Service;

/// A `Future` consuming a `Service` and request, waiting until the `Service`
/// is ready, and then calling `Service::call` with the request, and
/// waiting for that `Future`.
#[pin_project]
pub struct Oneshot<S: Service<Req>, Req> {
    #[pin]
    state: State<S, Req>,
}

#[pin_project]
enum State<S: Service<Req>, Req> {
    NotReady(Option<(S, Req)>),
    Called(#[pin] S::Future),
    Done,
}

impl<S, Req> Oneshot<S, Req>
where
    S: Service<Req>,
{
    pub fn new(svc: S, req: Req) -> Self {
        Oneshot {
            state: State::NotReady(Some((svc, req))),
        }
    }
}

impl<S, Req> Future for Oneshot<S, Req>
where
    S: Service<Req>,
{
    type Output = Result<S::Response, S::Error>;

    #[project]
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = self.project();
        loop {
            #[project]
            match this.state.project() {
                State::NotReady(nr) => {
                    let (mut svc, req) = nr.take().expect("We immediately transition to ::Called");
                    let _ = ready!(svc.poll_ready(cx))?;
                    this.state.set(State::Called(svc.call(req)));
                }
                State::Called(fut) => {
                    let res = ready!(fut.poll(cx))?;
                    this.state.set(State::Done);
                    return Poll::Ready(Ok(res));
                }
                State::Done => panic!("polled after complete"),
            }
        }
    }
}