Skip to content

Commit

Permalink
feat: add backoff for an exponential backoff iterator.
Browse files Browse the repository at this point in the history
It's used for computing the backoff on the lock itself, but is certainly
useful in other occasions as well.
  • Loading branch information
Byron committed Nov 13, 2022
1 parent 6beb6f2 commit f9bb71b
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
5 changes: 4 additions & 1 deletion git-lock/src/backoff.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::time::Duration;

pub fn randomize(backoff_ms: usize) -> usize {
fn randomize(backoff_ms: usize) -> usize {
let new_value = (fastrand::usize(750..=1250) * backoff_ms) / 1000;
if new_value == 0 {
backoff_ms
Expand All @@ -9,6 +9,7 @@ pub fn randomize(backoff_ms: usize) -> usize {
}
}

/// A utility to calculate steps for exponential backoff similar to how it's done in `git`.
pub struct Exponential<Fn> {
multiplier: usize,
max_multiplier: usize,
Expand All @@ -28,6 +29,7 @@ impl Default for Exponential<fn(usize) -> usize> {
}

impl Exponential<fn(usize) -> usize> {
/// Create a new exponential backoff iterator that backs off in randomized, ever increasing steps.
pub fn default_with_random() -> Self {
Exponential {
multiplier: 1,
Expand All @@ -42,6 +44,7 @@ impl<Transform> Exponential<Transform>
where
Transform: Fn(usize) -> usize,
{
/// Return an iterator that yields `Duration` instances to sleep on until `time` is depleted.
pub fn until_no_remaining(&mut self, time: Duration) -> impl Iterator<Item = Duration> + '_ {
let mut elapsed = Duration::default();
let mut stop_next_iteration = false;
Expand Down
3 changes: 2 additions & 1 deletion git-lock/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ const DOT_LOCK_SUFFIX: &str = ".lock";

///
pub mod acquire;
mod backoff;
///
pub mod backoff;
///
pub mod commit;

Expand Down

0 comments on commit f9bb71b

Please sign in to comment.