fuels_accounts/provider/retry_util.rs
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 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
use std::{fmt::Debug, future::Future, num::NonZeroU32, time::Duration};
use fuels_core::types::errors::{error, Result};
/// A set of strategies to control retry intervals between attempts.
///
/// The `Backoff` enum defines different strategies for managing intervals between retry attempts.
/// Each strategy allows you to customize the waiting time before a new attempt based on the
/// number of attempts made.
///
/// # Variants
///
/// - `Linear(Duration)`: Increases the waiting time linearly with each attempt.
/// - `Exponential(Duration)`: Doubles the waiting time with each attempt.
/// - `Fixed(Duration)`: Uses a constant waiting time between attempts.
///
/// # Examples
///
/// ```rust
/// use std::time::Duration;
/// use fuels_accounts::provider::Backoff;
///
/// let linear_backoff = Backoff::Linear(Duration::from_secs(2));
/// let exponential_backoff = Backoff::Exponential(Duration::from_secs(1));
/// let fixed_backoff = Backoff::Fixed(Duration::from_secs(5));
/// ```
//ANCHOR: backoff
#[derive(Debug, Clone)]
pub enum Backoff {
Linear(Duration),
Exponential(Duration),
Fixed(Duration),
}
//ANCHOR_END: backoff
impl Default for Backoff {
fn default() -> Self {
Backoff::Linear(Duration::from_millis(10))
}
}
impl Backoff {
pub fn wait_duration(&self, attempt: u32) -> Duration {
match self {
Backoff::Linear(base_duration) => *base_duration * (attempt + 1),
Backoff::Exponential(base_duration) => *base_duration * 2u32.pow(attempt),
Backoff::Fixed(interval) => *interval,
}
}
}
/// Configuration for controlling retry behavior.
///
/// The `RetryConfig` struct encapsulates the configuration parameters for controlling the retry behavior
/// of asynchronous actions. It includes the maximum number of attempts and the interval strategy from
/// the `Backoff` enum that determines how much time to wait between retry attempts.
///
/// # Fields
///
/// - `max_attempts`: The maximum number of attempts before giving up.
/// - `interval`: The chosen interval strategy from the `Backoff` enum.
///
/// # Examples
///
/// ```rust
/// use std::num::NonZeroUsize;
/// use std::time::Duration;
/// use fuels_accounts::provider::{Backoff, RetryConfig};
///
/// let max_attempts = 5;
/// let interval_strategy = Backoff::Exponential(Duration::from_secs(1));
///
/// let retry_config = RetryConfig::new(max_attempts, interval_strategy).unwrap();
/// ```
// ANCHOR: retry_config
#[derive(Clone, Debug)]
pub struct RetryConfig {
max_attempts: NonZeroU32,
interval: Backoff,
}
// ANCHOR_END: retry_config
impl RetryConfig {
pub fn new(max_attempts: u32, interval: Backoff) -> Result<Self> {
let max_attempts = NonZeroU32::new(max_attempts)
.ok_or_else(|| error!(Other, "`max_attempts` must be greater than `0`"))?;
Ok(RetryConfig {
max_attempts,
interval,
})
}
}
impl Default for RetryConfig {
fn default() -> Self {
Self {
max_attempts: NonZeroU32::new(1).expect("should not fail"),
interval: Default::default(),
}
}
}
/// Retries an asynchronous action with customizable retry behavior.
///
/// This function takes an asynchronous action represented by a closure `action`.
/// The action is executed repeatedly with backoff and retry logic based on the
/// provided `retry_config` and the `should_retry` condition.
///
/// The `action` closure should return a `Future` that resolves to a `Result<T, K>`,
/// where `T` represents the success type and `K` represents the error type.
///
/// # Parameters
///
/// - `action`: The asynchronous action to be retried.
/// - `retry_config`: A reference to the retry configuration.
/// - `should_retry`: A closure that determines whether to retry based on the result.
///
/// # Return
///
/// Returns `Ok(T)` if the action succeeds without requiring further retries.
/// Returns `Err(Error)` if the maximum number of attempts is reached and the action
/// still fails. If a retryable error occurs during the attempts, the error will
/// be returned if the `should_retry` condition allows further retries.
pub(crate) async fn retry<Fut, T, ShouldRetry>(
mut action: impl FnMut() -> Fut,
retry_config: &RetryConfig,
should_retry: ShouldRetry,
) -> T
where
Fut: Future<Output = T>,
ShouldRetry: Fn(&T) -> bool,
{
let mut last_result = None;
for attempt in 0..retry_config.max_attempts.into() {
let result = action().await;
if should_retry(&result) {
last_result = Some(result)
} else {
return result;
}
tokio::time::sleep(retry_config.interval.wait_duration(attempt)).await;
}
last_result.expect("should not happen")
}
#[cfg(test)]
mod tests {
mod retry_until {
use std::time::{Duration, Instant};
use fuels_core::types::errors::{error, Result};
use tokio::sync::Mutex;
use crate::provider::{retry_util, Backoff, RetryConfig};
#[tokio::test]
async fn returns_last_received_response() -> Result<()> {
// given
let err_msgs = ["err1", "err2", "err3"];
let number_of_attempts = Mutex::new(0usize);
let will_always_fail = || async {
let msg = err_msgs[*number_of_attempts.lock().await];
*number_of_attempts.lock().await += 1;
msg
};
let should_retry_fn = |_res: &_| -> bool { true };
let retry_options = RetryConfig::new(3, Backoff::Linear(Duration::from_millis(10)))?;
// when
let response =
retry_util::retry(will_always_fail, &retry_options, should_retry_fn).await;
// then
assert_eq!(response, "err3");
Ok(())
}
#[tokio::test]
async fn stops_retrying_when_predicate_is_satisfied() -> Result<()> {
// given
let values = Mutex::new(vec![1, 2, 3]);
let will_always_fail = || async { values.lock().await.pop().unwrap() };
let should_retry_fn = |res: &i32| *res != 2;
let retry_options = RetryConfig::new(3, Backoff::Linear(Duration::from_millis(10)))?;
// when
let response =
retry_util::retry(will_always_fail, &retry_options, should_retry_fn).await;
// then
assert_eq!(response, 2);
Ok(())
}
#[tokio::test]
async fn retry_respects_delay_between_attempts_fixed() -> Result<()> {
// given
let timestamps: Mutex<Vec<Instant>> = Mutex::new(vec![]);
let will_fail_and_record_timestamp = || async {
timestamps.lock().await.push(Instant::now());
Result::<()>::Err(error!(Other, "error"))
};
let should_retry_fn = |_res: &_| -> bool { true };
let retry_options = RetryConfig::new(3, Backoff::Fixed(Duration::from_millis(100)))?;
// when
let _ = retry_util::retry(
will_fail_and_record_timestamp,
&retry_options,
should_retry_fn,
)
.await;
// then
let timestamps_vec = timestamps.lock().await.clone();
let timestamps_spaced_out_at_least_100_mills = timestamps_vec
.iter()
.zip(timestamps_vec.iter().skip(1))
.all(|(current_timestamp, the_next_timestamp)| {
the_next_timestamp.duration_since(*current_timestamp)
>= Duration::from_millis(100)
});
assert!(
timestamps_spaced_out_at_least_100_mills,
"retry did not wait for the specified time between attempts"
);
Ok(())
}
#[tokio::test]
async fn retry_respects_delay_between_attempts_linear() -> Result<()> {
// given
let timestamps: Mutex<Vec<Instant>> = Mutex::new(vec![]);
let will_fail_and_record_timestamp = || async {
timestamps.lock().await.push(Instant::now());
Result::<()>::Err(error!(Other, "error"))
};
let should_retry_fn = |_res: &_| -> bool { true };
let retry_options = RetryConfig::new(3, Backoff::Linear(Duration::from_millis(100)))?;
// when
let _ = retry_util::retry(
will_fail_and_record_timestamp,
&retry_options,
should_retry_fn,
)
.await;
// then
let timestamps_vec = timestamps.lock().await.clone();
let timestamps_spaced_out_at_least_100_mills = timestamps_vec
.iter()
.zip(timestamps_vec.iter().skip(1))
.enumerate()
.all(|(attempt, (current_timestamp, the_next_timestamp))| {
the_next_timestamp.duration_since(*current_timestamp)
>= (Duration::from_millis(100) * (attempt + 1) as u32)
});
assert!(
timestamps_spaced_out_at_least_100_mills,
"retry did not wait for the specified time between attempts"
);
Ok(())
}
#[tokio::test]
async fn retry_respects_delay_between_attempts_exponential() -> Result<()> {
// given
let timestamps: Mutex<Vec<Instant>> = Mutex::new(vec![]);
let will_fail_and_record_timestamp = || async {
timestamps.lock().await.push(Instant::now());
Result::<()>::Err(error!(Other, "error"))
};
let should_retry_fn = |_res: &_| -> bool { true };
let retry_options =
RetryConfig::new(3, Backoff::Exponential(Duration::from_millis(100)))?;
// when
let _ = retry_util::retry(
will_fail_and_record_timestamp,
&retry_options,
should_retry_fn,
)
.await;
// then
let timestamps_vec = timestamps.lock().await.clone();
let timestamps_spaced_out_at_least_100_mills = timestamps_vec
.iter()
.zip(timestamps_vec.iter().skip(1))
.enumerate()
.all(|(attempt, (current_timestamp, the_next_timestamp))| {
the_next_timestamp.duration_since(*current_timestamp)
>= (Duration::from_millis(100) * (2_usize.pow((attempt) as u32)) as u32)
});
assert!(
timestamps_spaced_out_at_least_100_mills,
"retry did not wait for the specified time between attempts"
);
Ok(())
}
}
}