Skip to main content

hyper/client/
dispatch.rs

1use std::task::{Context, Poll};
2#[cfg(feature = "http2")]
3use std::{future::Future, pin::Pin};
4
5#[cfg(feature = "http2")]
6use http::{Request, Response};
7#[cfg(feature = "http2")]
8use http_body::Body;
9#[cfg(feature = "http2")]
10use pin_project_lite::pin_project;
11use tokio::sync::{mpsc, oneshot};
12
13#[cfg(feature = "http2")]
14use crate::{body::Incoming, proto::h2::client::ResponseFutMap};
15
16pub(crate) type RetryPromise<T, U> = oneshot::Receiver<Result<U, TrySendError<T>>>;
17pub(crate) type Promise<T> = oneshot::Receiver<Result<T, crate::Error>>;
18
19/// An error when calling `try_send_request`.
20///
21/// There is a possibility of an error occurring on a connection in-between the
22/// time that a request is queued and when it is actually written to the IO
23/// transport. If that happens, it is safe to return the request back to the
24/// caller, as it was never fully sent.
25#[derive(Debug)]
26pub struct TrySendError<T> {
27    pub(crate) error: crate::Error,
28    pub(crate) message: Option<T>,
29}
30
31pub(crate) fn channel<T, U>() -> (Sender<T, U>, Receiver<T, U>) {
32    let (tx, rx) = mpsc::unbounded_channel();
33    let (giver, mut taker) = want::new();
34    // Seed with one want so the first request can be sent before the
35    // receiver is polled; every request must consume a want
36    taker.want();
37    let tx = Sender { giver, inner: tx };
38    let rx = Receiver {
39        inner: rx,
40        taker,
41        wanting: true,
42    };
43    (tx, rx)
44}
45
46/// A bounded sender of requests and callbacks for when responses are ready.
47///
48/// While the inner sender is unbounded, the Giver is used to determine
49/// if the Receiver is ready for another request.
50pub(crate) struct Sender<T, U> {
51    // Controls whether the sender is permitted to dispatch a request
52    // Beyond the initial request, the Receiver only grants readiness once
53    // the preceding request/response cycle has fully completed
54    giver: want::Giver,
55    // Capacity is enforced via the Giver
56    inner: mpsc::UnboundedSender<Envelope<T, U>>,
57}
58
59/// An unbounded version.
60///
61/// Cannot poll the Giver, but can still use it to determine if the Receiver
62/// has been dropped. However, this version can be cloned.
63#[cfg(feature = "http2")]
64pub(crate) struct UnboundedSender<T, U> {
65    /// Only used for `is_closed`, since `mpsc::UnboundedSender` cannot be checked.
66    giver: want::SharedGiver,
67    inner: mpsc::UnboundedSender<Envelope<T, U>>,
68}
69
70impl<T, U> Sender<T, U> {
71    #[cfg(feature = "http1")]
72    pub(crate) fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<crate::Result<()>> {
73        self.giver
74            .poll_want(cx)
75            .map_err(|_| crate::Error::new_closed())
76    }
77
78    #[cfg(feature = "http1")]
79    pub(crate) fn is_ready(&self) -> bool {
80        self.giver.is_wanting()
81    }
82
83    #[cfg(feature = "http1")]
84    pub(crate) fn is_closed(&self) -> bool {
85        self.giver.is_canceled()
86    }
87
88    #[cfg(feature = "http1")]
89    pub(crate) fn try_send(&mut self, val: T) -> Result<RetryPromise<T, U>, T> {
90        if !self.giver.give() {
91            return Err(val);
92        }
93        let (tx, rx) = oneshot::channel();
94        self.inner
95            .send(Envelope(Some((val, Callback::Retry(Some(tx))))))
96            .map(move |()| rx)
97            .map_err(|mut e| (e.0).0.take().expect("envelope not dropped").0)
98    }
99
100    #[cfg(feature = "http1")]
101    pub(crate) fn send(&mut self, val: T) -> Result<Promise<U>, T> {
102        if !self.giver.give() {
103            return Err(val);
104        }
105        let (tx, rx) = oneshot::channel();
106        self.inner
107            .send(Envelope(Some((val, Callback::NoRetry(Some(tx))))))
108            .map(move |()| rx)
109            .map_err(|mut e| (e.0).0.take().expect("envelope not dropped").0)
110    }
111
112    #[cfg(feature = "http2")]
113    pub(crate) fn unbound(self) -> UnboundedSender<T, U> {
114        UnboundedSender {
115            giver: self.giver.shared(),
116            inner: self.inner,
117        }
118    }
119}
120
121#[cfg(feature = "http2")]
122impl<T, U> UnboundedSender<T, U> {
123    pub(crate) fn is_ready(&self) -> bool {
124        !self.giver.is_canceled()
125    }
126
127    pub(crate) fn is_closed(&self) -> bool {
128        self.giver.is_canceled()
129    }
130
131    pub(crate) fn try_send(&mut self, val: T) -> Result<RetryPromise<T, U>, T> {
132        let (tx, rx) = oneshot::channel();
133        self.inner
134            .send(Envelope(Some((val, Callback::Retry(Some(tx))))))
135            .map(move |()| rx)
136            .map_err(|mut e| (e.0).0.take().expect("envelope not dropped").0)
137    }
138
139    pub(crate) fn send(&mut self, val: T) -> Result<Promise<U>, T> {
140        let (tx, rx) = oneshot::channel();
141        self.inner
142            .send(Envelope(Some((val, Callback::NoRetry(Some(tx))))))
143            .map(move |()| rx)
144            .map_err(|mut e| (e.0).0.take().expect("envelope not dropped").0)
145    }
146}
147
148#[cfg(feature = "http2")]
149impl<T, U> Clone for UnboundedSender<T, U> {
150    fn clone(&self) -> Self {
151        UnboundedSender {
152            giver: self.giver.clone(),
153            inner: self.inner.clone(),
154        }
155    }
156}
157
158pub(crate) struct Receiver<T, U> {
159    inner: mpsc::UnboundedReceiver<Envelope<T, U>>,
160    taker: want::Taker,
161    // Tracks whether readiness (`want`) has already been granted for the next request
162    wanting: bool,
163}
164
165impl<T, U> Receiver<T, U> {
166    pub(crate) fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Option<(T, Callback<T, U>)>> {
167        if !self.wanting {
168            self.taker.want();
169            self.wanting = true;
170        }
171        match self.inner.poll_recv(cx) {
172            Poll::Ready(item) => {
173                self.wanting = false;
174                Poll::Ready(item.map(|mut env| env.0.take().expect("envelope not dropped")))
175            }
176            // Avoid re-signaling `want` here: the sender might have already claimed it
177            // and enqueued a request, even if polling the channel returns `Pending`
178            // due to Tokio's coop budget exhaustion or a concurrent send
179            Poll::Pending => Poll::Pending,
180        }
181    }
182
183    pub(crate) fn close(&mut self) {
184        self.taker.cancel();
185        self.inner.close();
186    }
187
188    pub(crate) fn poll_close(&mut self, cx: &mut Context<'_>) -> Poll<()> {
189        self.close();
190        // A send that started before close may still be publishing its envelope.
191        // Keep the receiver alive until all such envelopes have been canceled.
192        while futures_core::ready!(self.inner.poll_recv(cx)).is_some() {}
193        Poll::Ready(())
194    }
195
196    #[cfg(feature = "http1")]
197    pub(crate) fn try_recv(&mut self) -> Option<(T, Callback<T, U>)> {
198        match crate::common::task::now_or_never(self.inner.recv()) {
199            Some(Some(mut env)) => env.0.take(),
200            _ => None,
201        }
202    }
203}
204
205impl<T, U> Drop for Receiver<T, U> {
206    fn drop(&mut self) {
207        // Notify the giver about the closure first, before dropping
208        // the mpsc::Receiver.
209        self.taker.cancel();
210    }
211}
212
213struct Envelope<T, U>(Option<(T, Callback<T, U>)>);
214
215impl<T, U> Drop for Envelope<T, U> {
216    fn drop(&mut self) {
217        if let Some((val, cb)) = self.0.take() {
218            cb.send(Err(TrySendError {
219                error: crate::Error::new_canceled().with("connection closed"),
220                message: Some(val),
221            }));
222        }
223    }
224}
225
226pub(crate) enum Callback<T, U> {
227    #[allow(unused)]
228    Retry(Option<oneshot::Sender<Result<U, TrySendError<T>>>>),
229    NoRetry(Option<oneshot::Sender<Result<U, crate::Error>>>),
230}
231
232impl<T, U> Drop for Callback<T, U> {
233    fn drop(&mut self) {
234        match self {
235            Callback::Retry(tx) => {
236                if let Some(tx) = tx.take() {
237                    let _ = tx.send(Err(TrySendError {
238                        error: dispatch_gone(),
239                        message: None,
240                    }));
241                }
242            }
243            Callback::NoRetry(tx) => {
244                if let Some(tx) = tx.take() {
245                    let _ = tx.send(Err(dispatch_gone()));
246                }
247            }
248        }
249    }
250}
251
252#[cold]
253fn dispatch_gone() -> crate::Error {
254    // FIXME(nox): What errors do we want here?
255    crate::Error::new_user_dispatch_gone().with(if std::thread::panicking() {
256        "user code panicked"
257    } else {
258        "runtime dropped the dispatch task"
259    })
260}
261
262impl<T, U> Callback<T, U> {
263    #[cfg(feature = "http2")]
264    pub(crate) fn is_canceled(&self) -> bool {
265        match self {
266            Callback::Retry(Some(tx)) => tx.is_closed(),
267            Callback::NoRetry(Some(tx)) => tx.is_closed(),
268            _ => unreachable!(),
269        }
270    }
271
272    pub(crate) fn poll_canceled(&mut self, cx: &mut Context<'_>) -> Poll<()> {
273        match self {
274            Callback::Retry(Some(tx)) => tx.poll_closed(cx),
275            Callback::NoRetry(Some(tx)) => tx.poll_closed(cx),
276            _ => unreachable!(),
277        }
278    }
279
280    pub(crate) fn send(mut self, val: Result<U, TrySendError<T>>) {
281        match &mut self {
282            Callback::Retry(tx) => {
283                let _ = tx
284                    .take()
285                    .expect("callback sender not dropped before send")
286                    .send(val);
287            }
288            Callback::NoRetry(tx) => {
289                let _ = tx
290                    .take()
291                    .expect("callback sender not dropped before send")
292                    .send(val.map_err(|e| e.error));
293            }
294        }
295    }
296}
297
298impl<T> TrySendError<T> {
299    /// Take the message from this error.
300    ///
301    /// The message will not always have been recovered. If an error occurs
302    /// after the message has been serialized onto the connection, it will not
303    /// be available here.
304    pub fn take_message(&mut self) -> Option<T> {
305        self.message.take()
306    }
307
308    /// Returns a reference to the recovered message.
309    ///
310    /// The message will not always have been recovered. If an error occurs
311    /// after the message has been serialized onto the connection, it will not
312    /// be available here.
313    pub fn message(&self) -> Option<&T> {
314        self.message.as_ref()
315    }
316
317    /// Consumes this to return the inner error.
318    pub fn into_error(self) -> crate::Error {
319        self.error
320    }
321
322    /// Returns a reference to the inner error.
323    pub fn error(&self) -> &crate::Error {
324        &self.error
325    }
326}
327
328#[cfg(feature = "http2")]
329pin_project! {
330    pub struct SendWhen<B, E>
331    where
332        B: Body,
333        B: 'static,
334    {
335        #[pin]
336        pub(crate) when: ResponseFutMap<B, E>,
337        #[pin]
338        pub(crate) call_back: Option<Callback<Request<B>, Response<Incoming>>>,
339    }
340}
341
342#[cfg(feature = "http2")]
343impl<B, E> Future for SendWhen<B, E>
344where
345    B: Body + 'static,
346    E: crate::rt::bounds::Http2UpgradedExec<B::Data>,
347{
348    type Output = ();
349
350    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
351        let mut this = self.project();
352
353        let mut call_back = this.call_back.take().expect("polled after complete");
354
355        match Pin::new(&mut this.when).poll(cx) {
356            Poll::Ready(Ok(res)) => {
357                call_back.send(Ok(res));
358                Poll::Ready(())
359            }
360            Poll::Pending => {
361                // check if the callback is canceled
362                match call_back.poll_canceled(cx) {
363                    Poll::Ready(v) => v,
364                    Poll::Pending => {
365                        // Move call_back back to struct before return
366                        this.call_back.set(Some(call_back));
367                        return Poll::Pending;
368                    }
369                }
370                trace!("send_when canceled");
371                // Tell pipe_task to reset the h2 stream so that
372                // RST_STREAM is sent and flow-control capacity freed.
373                this.when.as_mut().cancel();
374                Poll::Ready(())
375            }
376            Poll::Ready(Err((error, message))) => {
377                call_back.send(Err(TrySendError { error, message }));
378                Poll::Ready(())
379            }
380        }
381    }
382}
383
384#[cfg(test)]
385mod tests {
386    #[cfg(feature = "nightly")]
387    extern crate test;
388
389    use std::future::Future;
390    use std::pin::Pin;
391    use std::task::{Context, Poll};
392
393    use super::{channel, Callback, Receiver};
394
395    #[derive(Debug)]
396    struct Custom(#[allow(dead_code)] i32);
397
398    impl<T, U> Future for Receiver<T, U> {
399        type Output = Option<(T, Callback<T, U>)>;
400
401        fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
402            self.poll_recv(cx)
403        }
404    }
405
406    /// Helper to check if the future is ready after polling once.
407    struct PollOnce<'fut, F>(&'fut mut F);
408
409    impl<F, T> Future for PollOnce<'_, F>
410    where
411        F: Future<Output = T> + Unpin,
412    {
413        type Output = Option<()>;
414
415        fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
416            match Pin::new(&mut self.0).poll(cx) {
417                Poll::Ready(_) => Poll::Ready(Some(())),
418                Poll::Pending => Poll::Ready(None),
419            }
420        }
421    }
422
423    #[cfg(not(miri))]
424    #[tokio::test]
425    async fn drop_receiver_sends_cancel_errors() {
426        let _ = pretty_env_logger::try_init();
427
428        let (mut tx, mut rx) = channel::<Custom, ()>();
429
430        // must poll once for try_send to succeed
431        assert!(PollOnce(&mut rx).await.is_none(), "rx empty");
432
433        let promise = tx.try_send(Custom(43)).unwrap();
434        drop(rx);
435
436        let fulfilled = promise.await;
437        let err = fulfilled
438            .expect("fulfilled")
439            .expect_err("promise should error");
440        match (err.error.is_canceled(), err.message) {
441            (true, Some(_)) => (),
442            e => panic!("expected Error::Cancel(_), found {:?}", e),
443        }
444    }
445
446    #[cfg(not(miri))]
447    #[tokio::test]
448    async fn sender_checks_for_want_on_send() {
449        let (mut tx, mut rx) = channel::<Custom, ()>();
450
451        // one is allowed to buffer, second is rejected
452        tx.try_send(Custom(1)).expect("1 buffered");
453        tx.try_send(Custom(2)).expect_err("2 not ready");
454
455        assert!(PollOnce(&mut rx).await.is_some(), "rx once");
456
457        // Even though 1 has been popped, only 1 could be buffered for the
458        // lifetime of the channel.
459        tx.try_send(Custom(2)).expect_err("2 still not ready");
460
461        assert!(PollOnce(&mut rx).await.is_none(), "rx empty");
462
463        tx.try_send(Custom(2)).expect("2 ready");
464    }
465
466    #[cfg(feature = "http2")]
467    #[test]
468    fn unbounded_sender_doesnt_bound_on_want() {
469        let (tx, rx) = channel::<Custom, ()>();
470        let mut tx = tx.unbound();
471
472        tx.try_send(Custom(1)).unwrap();
473        tx.try_send(Custom(2)).unwrap();
474        tx.try_send(Custom(3)).unwrap();
475
476        drop(rx);
477
478        tx.try_send(Custom(4)).unwrap_err();
479    }
480
481    #[cfg(feature = "nightly")]
482    #[bench]
483    fn giver_queue_throughput(b: &mut test::Bencher) {
484        use crate::{body::Incoming, Request, Response};
485
486        let rt = tokio::runtime::Builder::new_current_thread()
487            .build()
488            .unwrap();
489        let (mut tx, mut rx) = channel::<Request<Incoming>, Response<Incoming>>();
490
491        b.iter(move || {
492            tx.send(Request::new(Incoming::empty())).unwrap();
493            rt.block_on(async {
494                loop {
495                    let poll_once = PollOnce(&mut rx);
496                    let opt = poll_once.await;
497                    if opt.is_none() {
498                        break;
499                    }
500                }
501            });
502        })
503    }
504
505    #[cfg(feature = "nightly")]
506    #[bench]
507    fn giver_queue_not_ready(b: &mut test::Bencher) {
508        let rt = tokio::runtime::Builder::new_current_thread()
509            .build()
510            .unwrap();
511        let (_tx, mut rx) = channel::<i32, ()>();
512        b.iter(move || {
513            rt.block_on(async {
514                let poll_once = PollOnce(&mut rx);
515                assert!(poll_once.await.is_none());
516            });
517        })
518    }
519
520    #[cfg(feature = "nightly")]
521    #[bench]
522    fn giver_queue_cancel(b: &mut test::Bencher) {
523        let (_tx, mut rx) = channel::<i32, ()>();
524
525        b.iter(move || {
526            rx.taker.cancel();
527        })
528    }
529}