use std::time::Duration;
use gadk_agent::AgentError;
use gadk_platform::Platform;
use crate::workflow::RetryConfig;
use crate::workflow::config::default_should_retry;
pub fn calculate_delay(cfg: &RetryConfig, failed_attempts: i32, platform: &Platform) -> Duration {
if failed_attempts <= 0 {
return Duration::ZERO;
}
let backoff = if cfg.backoff_factor <= 0.0 {
1.0
} else {
cfg.backoff_factor
};
let mut delay = cfg.initial_delay.as_nanos() as f64;
for _ in 1..failed_attempts {
delay *= backoff;
}
let max_delay = cfg.max_delay.as_nanos() as f64;
if max_delay > 0.0 && delay > max_delay {
delay = max_delay;
}
if cfg.jitter > 0.0 {
let rand_val = jitter_fraction(platform);
delay += (rand_val * 2.0 - 1.0) * cfg.jitter * delay;
if delay < 0.0 {
delay = 0.0;
}
}
Duration::from_nanos(delay as u64)
}
fn jitter_fraction(platform: &Platform) -> f64 {
let id = platform.new_uuid();
let hex: String = id
.chars()
.filter(|c| c.is_ascii_hexdigit())
.take(8)
.collect();
u32::from_str_radix(&hex, 16).map_or(0.0, |n| f64::from(n) / 4_294_967_296.0)
}
pub fn should_retry(cfg: &RetryConfig, err: &AgentError, failed_attempts: i32) -> bool {
if cfg.max_attempts <= 1 || failed_attempts >= cfg.max_attempts {
return false;
}
match &cfg.should_retry {
Some(pred) => pred(err),
None => default_should_retry(err),
}
}