1//! Services that are busy or newly created.
2//!
3//! The [`UnreadyService`] implementation is adapted from the one in [tower::Balance][tower-balance].
4//!
5//! [tower-balance]: https://github.com/tower-rs/tower/tree/master/tower/src/balance
67use std::{
8 future::Future,
9 marker::PhantomData,
10 pin::Pin,
11 task::{Context, Poll},
12};
1314use futures::{channel::oneshot, ready};
15use tower::Service;
1617use crate::peer_set::set::CancelClientWork;
1819#[cfg(test)]
20mod tests;
2122/// A Future that becomes satisfied when an `S`-typed service is ready.
23///
24/// May fail due to cancellation, i.e. if the service is removed from discovery.
25#[pin_project]
26#[derive(Debug)]
27pub(super) struct UnreadyService<K, S, Req> {
28/// The key used to lookup `service`.
29pub(super) key: Option<K>,
3031/// A oneshot used to cancel the request the `service` is currently working on, if any.
32#[pin]
33pub(super) cancel: oneshot::Receiver<CancelClientWork>,
3435/// The `service` that is busy (or newly created).
36pub(super) service: Option<S>,
3738/// Dropping `service` might drop a request.
39 /// This [`PhantomData`] tells the Rust compiler to do a drop check for `Req`.
40pub(super) _req: PhantomData<Req>,
41}
4243#[derive(Debug, Eq, PartialEq)]
44pub(super) enum Error<E> {
45 Inner(E),
46 Canceled,
47 CancelHandleDropped(oneshot::Canceled),
48}
4950impl<K, S: Service<Req>, Req> Future for UnreadyService<K, S, Req> {
51type Output = Result<(K, S), (K, Error<S::Error>)>;
5253fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
54let this = self.project();
5556if let Poll::Ready(oneshot_result) = this.cancel.poll(cx) {
57let key = this.key.take().expect("polled after ready");
5859// # Correctness
60 //
61 // Return an error if the service is explicitly canceled,
62 // or its cancel handle is dropped, implicitly cancelling it.
63match oneshot_result {
64Ok(CancelClientWork) => return Poll::Ready(Err((key, Error::Canceled))),
65Err(canceled_error) => {
66return Poll::Ready(Err((key, Error::CancelHandleDropped(canceled_error))))
67 }
68 }
69 }
7071// # Correctness
72 //
73 // The current task must be scheduled for wakeup every time we return
74 // `Poll::Pending`.
75 //
76 //`ready!` returns `Poll::Pending` when the service is unready, and
77 // the inner `poll_ready` schedules this task for wakeup.
78 //
79 // `cancel.poll` also schedules this task for wakeup if it is canceled.
80let res = ready!(this
81 .service
82 .as_mut()
83 .expect("polled after ready")
84 .poll_ready(cx));
8586let key = this.key.take().expect("polled after ready");
87let svc = this.service.take().expect("polled after ready");
8889match res {
90Ok(()) => Poll::Ready(Ok((key, svc))),
91Err(e) => Poll::Ready(Err((key, Error::Inner(e)))),
92 }
93 }
94}