summaryrefslogtreecommitdiffstats
path: root/pkg/backoff
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-13 11:40:59 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-13 11:40:59 +0000
commitbc4e624732bd51c0dd1e9529cf228e8c23127732 (patch)
treed95dab8960e9d02d3b95f8653074ad2e54ca207c /pkg/backoff
parentInitial commit. (diff)
downloadicingadb-bc4e624732bd51c0dd1e9529cf228e8c23127732.tar.xz
icingadb-bc4e624732bd51c0dd1e9529cf228e8c23127732.zip
Adding upstream version 1.1.1.upstream/1.1.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'pkg/backoff')
-rw-r--r--pkg/backoff/backoff.go43
1 files changed, 43 insertions, 0 deletions
diff --git a/pkg/backoff/backoff.go b/pkg/backoff/backoff.go
new file mode 100644
index 0000000..6ce7bee
--- /dev/null
+++ b/pkg/backoff/backoff.go
@@ -0,0 +1,43 @@
+package backoff
+
+import (
+ "math/rand"
+ "time"
+)
+
+// Backoff returns the backoff duration for a specific retry attempt.
+type Backoff func(uint64) time.Duration
+
+// NewExponentialWithJitter returns a backoff implementation that
+// exponentially increases the backoff duration for each retry from min,
+// never exceeding max. Some randomization is added to the backoff duration.
+// It panics if min >= max.
+func NewExponentialWithJitter(min, max time.Duration) Backoff {
+ if min <= 0 {
+ min = time.Millisecond * 100
+ }
+ if max <= 0 {
+ max = time.Second * 10
+ }
+ if min >= max {
+ panic("max must be larger than min")
+ }
+
+ return func(attempt uint64) time.Duration {
+ e := min << attempt
+ if e <= 0 || e > max {
+ e = max
+ }
+
+ return time.Duration(jitter(int64(e)))
+ }
+}
+
+// jitter returns a random integer distributed in the range [n/2..n).
+func jitter(n int64) int64 {
+ if n == 0 {
+ return 0
+ }
+
+ return n/2 + rand.Int63n(n/2)
+}