sfm_sdk/utils/
backoff.rs

1use tokio::time::Duration;
2
3pub fn obtain_next_interval(
4    current_cycle: &usize,
5    cycle_ceiling: &usize,
6    retry_interval: &Duration,
7) -> Option<Duration> {
8    if cycle_ceiling < current_cycle {
9        return None
10    }
11
12    return if current_cycle <= &0 {
13        Option::from(Duration::from_millis(*current_cycle as u64 * (retry_interval.as_secs() * 1000)))
14    } else {
15        Option::from(obtain_next_interval(&(current_cycle - 1), cycle_ceiling, retry_interval).unwrap()
16            + Duration::from_millis(*current_cycle as u64 * (retry_interval.as_secs() * 1000)))
17    }
18}
19
20#[cfg(test)]
21mod tests {
22    use super::*;
23
24    #[test]
25    fn scenario_one() {
26        let interval = Duration::from_millis(5000);
27
28        assert_eq!(obtain_next_interval(&2, &5, &interval)
29                       .unwrap(), Duration::from_millis(15000));
30    }
31
32    #[test]
33    fn failing_scenario_one() {
34        let interval = Duration::from_millis(5000);
35
36        // This assert would fire and test will fail.
37        // Please note, that private functions can be tested too!
38        assert_eq!(obtain_next_interval(&5, &4,
39                                        &interval), None);
40    }
41}