Skip to content

Commit

Permalink
Fix exponentialBackoffer overflowing into negative
Browse files Browse the repository at this point in the history
Signed-off-by: Jakub Sztandera <[email protected]>
  • Loading branch information
Kubuxu committed Jul 24, 2024
1 parent 660547c commit 1d0d67d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
10 changes: 5 additions & 5 deletions gpbft/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,12 @@ func WithRebroadcastBackoff(exponent float64, base, max time.Duration) Option {
}
}

func exponentialBackoffer(exponent float64, base, max time.Duration) func(attempt int) time.Duration {
func exponentialBackoffer(exponent float64, base, maxBackoff time.Duration) func(attempt int) time.Duration {
return func(attempt int) time.Duration {
nextBackoff := time.Duration(float64(base) * math.Pow(exponent, float64(attempt)))
if nextBackoff > max {
return max
nextBackoff := float64(base) * math.Pow(exponent, float64(attempt))
if nextBackoff > float64(maxBackoff) {
return maxBackoff
}
return nextBackoff
return maxBackoff
}
}
18 changes: 18 additions & 0 deletions gpbft/options_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package gpbft

import (
"testing"
"time"

"github.com/stretchr/testify/require"
)

func Test_exponentialBackoffer(t *testing.T) {
maxBackoff := 30 * time.Second
backoffer := exponentialBackoffer(1.3, 3*time.Second, maxBackoff)
for i := 0; i < 10_000; i++ {
backoff := backoffer(i)
require.Positivef(t, backoff, "at %d", i)
require.LessOrEqualf(t, backoff, maxBackoff, "at %d", i)
}
}

0 comments on commit 1d0d67d

Please sign in to comment.