more retries

This commit is contained in:
JMARyA 2025-03-10 18:59:35 +01:00
parent 46cb21dc2a
commit 4e49080958
Signed by: jmarya
GPG key ID: 901B2ADDF27C2263

View file

@ -76,6 +76,48 @@ pub fn retry<O, F: Fn() -> Option<O>>(f: F) -> O {
}
}
pub fn retry_max<O, F: Fn() -> Option<O>>(max: u64, f: F) -> Option<O> {
let mut counter = 0;
while counter < max {
match f() {
Some(resp) => {
return Some(resp);
}
None => {
log::info!("Got nothing, retrying {}/{}", counter + 1, max);
}
}
counter += 1;
}
None
}
/// Retries a function gracefully with exponential backoff.
///
/// - `f`: A function that returns an `Option<O>`, retried on `None`.
/// - Starts with `base_delay` and doubles it each attempt, capping at `max_delay`.
///
/// Returns `Some(O)` if successful, otherwise keeps retrying indefinitely.
pub fn retry_backoff<O, F: Fn() -> Option<O>>(
f: F,
base_delay: Duration,
max_delay: Duration,
) -> Option<O> {
let mut delay = base_delay;
loop {
match f() {
Some(resp) => return Some(resp),
None => {
log::info!("Got nothing, retrying in {:?}", delay);
thread::sleep(delay);
delay = (delay * 2).min(max_delay);
}
}
}
}
/// Run a background task.
///
/// This spawns a seperate thread for a background process.