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
//! Defines the [`RetryPolicy`] trait and related types.

use futures::future::BoxFuture;

use crate::append::AppendError;
use crate::error::ShutDown;
use crate::error::ShutDownOr;
use crate::invocation::Invocation;

/// Policy that determines whether an append should be retried.
pub trait RetryPolicy: 'static {
    /// Parametrization of the paxakos algorithm.
    type Invocation: Invocation;

    /// Type of error produced by this policy.
    type Error;

    /// Union of `Self::Error` and `ShutDown`.
    ///
    /// See [`Node::append_static`][crate::Node::append_static].
    // TODO default to ShutDownOr<Self::Error> (https://github.com/rust-lang/rust/issues/29661)
    type StaticError;

    /// Type of future returned from [RetryPolicy::eval].
    // TODO this needs GATs for a lifetime parameter
    type Future: std::future::Future<Output = Result<(), Self::Error>>;

    /// Determines wheter another attempt to append should be made.
    ///
    /// The given `error` is the reason the latest attempt failed. Returning
    /// `Ok(())` implies that another attempt should be made.
    fn eval(&mut self, error: AppendError<Self::Invocation>) -> Self::Future;
}

impl<I: Invocation, E: 'static, F: 'static> RetryPolicy
    for Box<
        dyn RetryPolicy<
                Invocation = I,
                Error = E,
                StaticError = F,
                Future = BoxFuture<'static, Result<(), E>>,
            > + Send,
    >
{
    type Invocation = I;
    type Error = E;
    type StaticError = F;
    type Future = BoxFuture<'static, Result<(), Self::Error>>;

    fn eval(&mut self, error: AppendError<Self::Invocation>) -> Self::Future {
        (**self).eval(error)
    }
}

/// Implementation of [`RetryPolicy`] that never retries.
#[derive(Copy, Debug)]
pub struct DoNotRetry<I>(crate::util::PhantomSend<I>);

impl<I> DoNotRetry<I> {
    /// Constructs a new `DoNoRetry` policy.
    pub fn new() -> Self {
        Self(crate::util::PhantomSend::new())
    }
}

impl<I> Default for DoNotRetry<I> {
    fn default() -> Self {
        Self(Default::default())
    }
}

impl<I> Clone for DoNotRetry<I> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<I: Invocation> RetryPolicy for DoNotRetry<I> {
    type Invocation = I;
    type Error = AppendError<Self::Invocation>;
    type StaticError = AppendError<Self::Invocation>;
    type Future = futures::future::Ready<Result<(), Self::Error>>;

    fn eval(&mut self, err: AppendError<Self::Invocation>) -> Self::Future {
        futures::future::ready(Err(err))
    }
}

/// Append was not retried.
#[derive(thiserror::Error)]
#[error("append was aborted")]
pub struct AbortedError<I: Invocation>(AppendError<I>);

impl<I: Invocation> std::fmt::Debug for AbortedError<I> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("AbortedError").field(&self.0).finish()
    }
}

impl<I: Invocation> From<ShutDown> for AbortedError<I> {
    fn from(shut_down: ShutDown) -> Self {
        Self(shut_down.into())
    }
}

impl<I: Invocation> From<ShutDownOr<AbortedError<I>>> for AbortedError<I> {
    fn from(err: ShutDownOr<AbortedError<I>>) -> Self {
        match err {
            ShutDownOr::Other(err) => err,
            ShutDownOr::ShutDown => Self::from(ShutDown),
        }
    }
}

#[cfg(feature = "backoff")]
pub use cfg_backoff::RetryWithBackoff;

#[cfg(feature = "backoff")]
mod cfg_backoff {
    use std::marker::PhantomData;

    use backoff::backoff::Backoff;
    use backoff::exponential::ExponentialBackoff;
    use futures::future::BoxFuture;
    use futures::FutureExt;

    use crate::append::AppendArgs;
    use crate::append::AppendError;
    use crate::invocation::Invocation;

    use super::AbortedError;
    use super::RetryPolicy;

    /// Retry policy basod on a [`Backoff`] implementation.
    pub struct RetryWithBackoff<B, I>(B, PhantomData<I>);

    impl<C, I> Default for RetryWithBackoff<ExponentialBackoff<C>, I>
    where
        C: backoff::Clock + Default + Send + 'static,
        I: Invocation + Send,
    {
        fn default() -> Self {
            Self(ExponentialBackoff::default(), Default::default())
        }
    }

    impl<B: Backoff, I> From<B> for RetryWithBackoff<B, I> {
        fn from(backoff: B) -> Self {
            Self(backoff, std::marker::PhantomData)
        }
    }

    impl<C, I> From<ExponentialBackoff<C>> for AppendArgs<I, RetryWithBackoff<ExponentialBackoff<C>, I>>
    where
        C: backoff::Clock + Send + 'static,
        I: Invocation + Send,
    {
        fn from(backoff: ExponentialBackoff<C>) -> Self {
            RetryWithBackoff::from(backoff).into()
        }
    }

    impl<B: Backoff + Send + 'static, I: Invocation + Send> RetryPolicy for RetryWithBackoff<B, I> {
        type Invocation = I;
        type Error = AbortedError<I>;
        type StaticError = AbortedError<I>;
        type Future = BoxFuture<'static, Result<(), Self::Error>>;

        fn eval(&mut self, err: AppendError<Self::Invocation>) -> Self::Future {
            let next_backoff = self.0.next_backoff();

            async move {
                if let Some(d) = next_backoff {
                    futures_timer::Delay::new(d).await;
                    Ok(())
                } else {
                    Err(AbortedError(err))
                }
            }
            .boxed()
        }
    }
}