@@ -5,12 +5,14 @@ import (
55 "time"
66)
77
8+ // BackoffConfig configures a Backoff
89type BackoffConfig struct {
910 MinBackoff time.Duration // start backoff at this level
1011 MaxBackoff time.Duration // increase exponentially to this level
1112 MaxRetries int // give up after this many; zero means infinite retries
1213}
1314
15+ // Backoff implements exponential backoff with randomized wait times
1416type Backoff struct {
1517 cfg BackoffConfig
1618 done <- chan struct {}
@@ -19,6 +21,7 @@ type Backoff struct {
1921 duration time.Duration
2022}
2123
24+ // NewBackoff creates a Backoff object. Pass a 'done' channel that can be closed to terminate the operation.
2225func NewBackoff (cfg BackoffConfig , done <- chan struct {}) * Backoff {
2326 return & Backoff {
2427 cfg : cfg ,
@@ -27,25 +30,32 @@ func NewBackoff(cfg BackoffConfig, done <-chan struct{}) *Backoff {
2730 }
2831}
2932
33+ // Reset the Backoff back to its initial condition
3034func (b * Backoff ) Reset () {
3135 b .numRetries = 0
3236 b .cancelled = false
3337 b .duration = b .cfg .MinBackoff
3438}
3539
40+ // Ongoing returns true if caller should keep going
3641func (b * Backoff ) Ongoing () bool {
3742 return ! b .cancelled && (b .cfg .MaxRetries == 0 || b .numRetries < b .cfg .MaxRetries )
3843}
3944
45+ // NumRetries returns the number of retries so far
4046func (b * Backoff ) NumRetries () int {
4147 return b .numRetries
4248}
4349
50+ // Wait sleeps for the backoff time then increases the retry count and backoff time
51+ // Returns immediately if done channel is closed
4452func (b * Backoff ) Wait () {
4553 b .numRetries ++
4654 b .WaitWithoutCounting ()
4755}
4856
57+ // WaitWithoutCounting sleeps for the backoff time then increases backoff time
58+ // Returns immediately if done channel is closed
4959func (b * Backoff ) WaitWithoutCounting () {
5060 if b .Ongoing () {
5161 select {
0 commit comments