1use std::pin::Pin;
23use futures::{Future, FutureExt};
4use tower::retry::Policy;
56/// A very basic retry policy with a limited number of retry attempts.
7///
8/// TODO: Remove this when <https://github.com/tower-rs/tower/pull/414> lands.
9#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
10pub struct RetryLimit {
11 remaining_tries: usize,
12}
1314impl RetryLimit {
15/// Create a policy with the given number of retry attempts.
16pub fn new(retry_attempts: usize) -> Self {
17 RetryLimit {
18 remaining_tries: retry_attempts,
19 }
20 }
21}
2223impl<Req: Clone + std::fmt::Debug, Res, E: std::fmt::Debug> Policy<Req, Res, E> for RetryLimit {
24type Future = Pin<Box<dyn Future<Output = Self> + Send + Sync + 'static>>;
2526fn retry(&self, req: &Req, result: Result<&Res, &E>) -> Option<Self::Future> {
27if let Err(e) = result {
28if self.remaining_tries > 0 {
29tracing::debug!(?req, ?e, remaining_tries = self.remaining_tries, "retrying");
3031let remaining_tries = self.remaining_tries - 1;
32let retry_outcome = RetryLimit { remaining_tries };
3334Some(
35// Let other tasks run, so we're more likely to choose a different peer,
36 // and so that any notfound inv entries win the race to the PeerSet.
37 //
38 // # Security
39 //
40 // We want to choose different peers for retries, so we have a better chance of getting each block.
41 // This is implemented by the connection state machine sending synthetic `notfound`s to the
42 // `InventoryRegistry`, as well as forwarding actual `notfound`s from peers.
43Box::pin(tokio::task::yield_now().map(move |()| retry_outcome)),
44 )
45 } else {
46None
47}
48 } else {
49None
50}
51 }
5253fn clone_request(&self, req: &Req) -> Option<Req> {
54Some(req.clone())
55 }
56}