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
//! Resting place for [KeenRetryExecutor].\
// //! Keep this in sync with ../keen_retry_async_executor.rs
use crate::{
resolved_result::ResolvedResult,
RetryResult,
};
use std::time::{Duration, SystemTime};
/// Executes the retry logic according to the chosen backoff algorithm and limits, keeping track of retry metrics;
pub enum KeenRetryExecutor<ReportedInput,
OriginalInput,
Output,
ErrorType,
RetryFn: FnMut(OriginalInput) -> RetryResult<ReportedInput, OriginalInput, Output, ErrorType>> {
/// Indicates no retrying is needed as the operation completed successfully on the initial attempt
ResolvedOk {
reported_input: ReportedInput,
output: Output
},
/// Indicates no retrying is needed as the operation completed fatally on the initial attempt
ResolvedErr {
original_input: OriginalInput,
error: ErrorType
},
/// Indicates executing retries is, indeed, needed, as the initial operation resulted into a retryable error
ToRetry {
input: OriginalInput,
retry_operation: RetryFn,
retry_errors: Vec<ErrorType>,
},
}
impl<ReportedInput,
OriginalInput,
Output,
ErrorType,
RetryFn: FnMut(OriginalInput) -> RetryResult<ReportedInput, OriginalInput, Output, ErrorType>>
KeenRetryExecutor<ReportedInput,
OriginalInput,
Output,
ErrorType,
RetryFn> {
pub fn new(original_input: OriginalInput, retry_operation: RetryFn, first_attempt_retryable_error: ErrorType) -> Self {
Self::ToRetry {
input: original_input,
retry_operation,
retry_errors: vec![first_attempt_retryable_error],
}
}
pub fn from_ok_result(reported_input: ReportedInput, output: Output) -> Self {
Self::ResolvedOk { reported_input, output }
}
pub fn from_err_result(original_input: OriginalInput, error: ErrorType) -> Self {
Self::ResolvedErr { original_input, error }
}
/// Upgrades this [KeenRetryExecutor] into the final [ResolvedResult], possibly executing the `retry_operation` as many times as
/// there are elements in `delays`, sleeping for the indicated amount on each attempt
/// See also [Self::spinning_forever()]
/// Example:
/// ```nocompile
/// // for an arithmetic progression in the sleeping times:
/// .with_delays((100..=1000).step_by(100).map(|millis| Duration::from_millis(millis)))
/// // for a geometric progression with a 1.289 ratio in 13 steps: sleeps from 1 to ~350ms
/// .with_delays((1..=13).map(|millis| Duration::from_millis((millis as f64 * 1.289f64.powi(millis)) as u64)))
pub fn with_delays(self, mut delays: impl Iterator<Item=Duration>) -> ResolvedResult<ReportedInput, OriginalInput, Output, ErrorType> {
self.retry_loop(
move |input, mut retry_errors| {
match delays.next() {
Some(delay) => {
std::thread::sleep(delay);
Ok((input, retry_errors))
},
None => {
// retries exhausted without success: report as `GivenUp` (unless the number of retries was 0)
let fatal_error = retry_errors.pop();
match fatal_error {
Some(fatal_error) => Err(ResolvedResult::GivenUp { input, retry_errors, fatal_error }),
None => panic!("BUG! the `keen-retry` crate has a bug in the way it start retries: a retry can only be created with the first retryable error having been registered"),
}
},
}
},
|_input, error, retry_errors_list| retry_errors_list.push(error)
)
}
/// Designed for really fast `retry_operation`s, upgrades this [KeenRetryAsyncExecutor] into the final [ResolvedResult], executing the `retry_operation`
/// until it either succeeds or fatably fails, relaxing the CPU on each attempt -- but not context-switching nor giving `tokio` a change to run other tasks.\
/// See also [Self::with_delays()]
pub fn spinning_forever(self) -> ResolvedResult<ReportedInput, OriginalInput, Output, ErrorType> {
self.retry_loop(
|input, retry_errors| {
// spin 32x
std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop();
std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop();
std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop();
std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop();
Ok((input, retry_errors))
},
|_input, _error, _retry_errors_list| ()
)
}
/// Upgrades this [KeenRetryExecutor] into the final [ResolvedResult], executing the `retry_operation`
/// until it either succeeds (or fatably fails) or `timeout` elapses -- in which case, the operation will fail
/// with the error given by `timeout_error`.\
/// Upon each new attempt, some time will be spent in the CPU Relaxed state & a context switch is likely to happen (to fetch the time)
/// -- since the CPU usage will still be 100%, using this method is recommended only for very short durations (<~100ms).
pub fn spinning_until_timeout(self,
timeout: Duration,
timeout_error: ErrorType)
-> ResolvedResult<ReportedInput, OriginalInput, Output, ErrorType> {
let mut timeout_error = Some(timeout_error);
let start = SystemTime::now();
self.retry_loop(
|input, retry_errors| {
// spin 32x
std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop();
std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop();
std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop();
std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop(); std::hint::spin_loop();
if start.elapsed().expect("keen_retry: error determining the elapsed time") >= timeout {
Err(ResolvedResult::GivenUp { input, retry_errors, fatal_error: timeout_error.take().unwrap() })
} else {
Ok((input, retry_errors))
}
},
|_input, _error, _retry_errors_list| ()
)
}
/// The low-level generic retry loop for this async executor -- for when [Self::with_delays()], [Self::spinning_forever()]
/// nor [Self::spinning_until_timeout()] suit your needs:
/// - `on_pre_reattempt(&input, &mut retry_errors_list) -> Result<(), ErrorType>`
/// Called before performing (another) retry attempt. If it returns a non-`Ok` value, the returned error
/// will be reported as `fatal` and the `retry_loop()` will end.
/// - `on_non_fatal_failure(&input, error, &mut retry_errors_list)`
/// Called when the current retry attempt failed. Used to, optionally, push the error in the `retry_errors_list`.
/// See the sources of [Self::with_delays()] for a good example of how to use this low level function.
pub fn retry_loop(self,
mut on_pre_attempt: impl FnMut(OriginalInput, Vec<ErrorType>) -> Result<(OriginalInput, Vec<ErrorType>), ResolvedResult<ReportedInput, OriginalInput, Output, ErrorType>>,
mut on_non_fatal_failure: impl FnMut(&OriginalInput, ErrorType, &mut Vec<ErrorType>))
-> ResolvedResult<ReportedInput, OriginalInput, Output, ErrorType> {
match self {
KeenRetryExecutor::ResolvedOk { reported_input, output } => ResolvedResult::from_ok_result(reported_input, output),
KeenRetryExecutor::ResolvedErr { original_input, error } => ResolvedResult::from_err_result(original_input, error),
KeenRetryExecutor::ToRetry { mut input, mut retry_operation, mut retry_errors } => {
loop {
(input, retry_errors) = match on_pre_attempt(input, retry_errors) {
Ok((input, mut retry_errors)) => {
let new_retry_result = retry_operation(input);
match new_retry_result {
RetryResult::Ok { reported_input, output } => break ResolvedResult::Recovered { reported_input, output, retry_errors },
RetryResult::Fatal { input, error } => break ResolvedResult::Unrecoverable { input, retry_errors, fatal_error: error },
RetryResult::Retry { input, error } => {
on_non_fatal_failure(&input, error, &mut retry_errors);
(input, retry_errors)
},
}
},
Err(resolved_result) => {
break resolved_result
}
};
}
}
}
}
}