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
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use futures_util::ready;
use pin_project::pin_project;
use std::{
    future::Future,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};
use tokio::sync::{mpsc, oneshot, OwnedSemaphorePermit, Semaphore};
use tokio_util::sync::PollSemaphore;
use tower::{Service, ServiceExt};

/// A version of [`tower::buffer::Buffer`] which panicks on channel related errors, thus keeping
/// the error type of the service.
pub(crate) struct MpscBuffer<S, R>
where
    S: Service<R>,
{
    tx: mpsc::UnboundedSender<Msg<S, R>>,
    semaphore: PollSemaphore,
    permit: Option<OwnedSemaphorePermit>,
}

impl<S, R> Clone for MpscBuffer<S, R>
where
    S: Service<R>,
{
    fn clone(&self) -> Self {
        Self {
            tx: self.tx.clone(),
            semaphore: self.semaphore.clone(),
            permit: None,
        }
    }
}

impl<S, R> MpscBuffer<S, R>
where
    S: Service<R>,
{
    pub(crate) fn new(svc: S) -> Self
    where
        S: Send + 'static,
        R: Send + 'static,
        S::Error: Send + 'static,
        S::Future: Send + 'static,
    {
        let (tx, rx) = mpsc::unbounded_channel::<Msg<S, R>>();
        let semaphore = PollSemaphore::new(Arc::new(Semaphore::new(1024)));

        tokio::spawn(run_worker(svc, rx));

        Self {
            tx,
            semaphore,
            permit: None,
        }
    }
}

async fn run_worker<S, R>(mut svc: S, mut rx: mpsc::UnboundedReceiver<Msg<S, R>>)
where
    S: Service<R>,
{
    while let Some((req, reply_tx)) = rx.recv().await {
        match svc.ready().await {
            Ok(svc) => {
                let future = svc.call(req);
                let _ = reply_tx.send(WorkerReply::Future(future));
            }
            Err(err) => {
                let _ = reply_tx.send(WorkerReply::Error(err));
            }
        }
    }
}

type Msg<S, R> = (
    R,
    oneshot::Sender<WorkerReply<<S as Service<R>>::Future, <S as Service<R>>::Error>>,
);

enum WorkerReply<F, E> {
    Future(F),
    Error(E),
}

impl<S, R> Service<R> for MpscBuffer<S, R>
where
    S: Service<R>,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = ResponseFuture<S::Future, S::Error>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        if self.permit.is_some() {
            return Poll::Ready(Ok(()));
        }

        let permit = ready!(self.semaphore.poll_acquire(cx))
            .expect("buffer semaphore closed. This is a bug in axum and should never happen. Please file an issue");

        self.permit = Some(permit);

        Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: R) -> Self::Future {
        let permit = self
            .permit
            .take()
            .expect("semaphore permit missing. Did you forget to call `poll_ready`?");

        let (reply_tx, reply_rx) = oneshot::channel::<WorkerReply<S::Future, S::Error>>();

        self.tx.send((req, reply_tx)).unwrap_or_else(|_| {
            panic!("buffer worker not running. This is a bug in axum and should never happen. Please file an issue")
        });

        ResponseFuture {
            state: State::Channel(reply_rx),
            permit,
        }
    }
}

#[pin_project]
pub(crate) struct ResponseFuture<F, E> {
    #[pin]
    state: State<F, E>,
    permit: OwnedSemaphorePermit,
}

#[pin_project(project = StateProj)]
enum State<F, E> {
    Channel(oneshot::Receiver<WorkerReply<F, E>>),
    Future(#[pin] F),
}

impl<F, E, T> Future for ResponseFuture<F, E>
where
    F: Future<Output = Result<T, E>>,
{
    type Output = Result<T, E>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        loop {
            let mut this = self.as_mut().project();

            let new_state = match this.state.as_mut().project() {
                StateProj::Channel(reply_rx) => {
                    let msg = ready!(Pin::new(reply_rx).poll(cx))
                        .expect("buffer worker not running. This is a bug in axum and should never happen. Please file an issue");

                    match msg {
                        WorkerReply::Future(future) => State::Future(future),
                        WorkerReply::Error(err) => return Poll::Ready(Err(err)),
                    }
                }
                StateProj::Future(future) => {
                    return future.poll(cx);
                }
            };

            this.state.set(new_state);
        }
    }
}

#[cfg(test)]
mod tests {
    #[allow(unused_imports)]
    use super::*;
    use tower::ServiceExt;

    #[tokio::test]
    async fn test_buffer() {
        let mut svc = MpscBuffer::new(tower::service_fn(handle));

        let res = svc.ready().await.unwrap().call(42).await.unwrap();

        assert_eq!(res, "foo");
    }

    async fn handle(req: i32) -> Result<&'static str, std::convert::Infallible> {
        assert_eq!(req, 42);
        Ok("foo")
    }
}