github.com/uber/kraken@v0.1.4/utils/httputil/backoff.go (about)

     1  package httputil
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/cenkalti/backoff"
     7  )
     8  
     9  // ExponentialBackOffConfig maps backoff settings into YAML config format.
    10  type ExponentialBackOffConfig struct {
    11  	Enabled             bool          `yaml:"enabled"`
    12  	InitialInterval     time.Duration `yaml:"initial_interval"`
    13  	RandomizationFactor float64       `yaml:"randomization_factor"`
    14  	Multiplier          float64       `yaml:"multiplier"`
    15  	MaxInterval         time.Duration `yaml:"max_interval"`
    16  	MaxRetries          uint64        `yaml:"max_retries"`
    17  }
    18  
    19  func (c *ExponentialBackOffConfig) applyDefaults() {
    20  	if c.InitialInterval == 0 {
    21  		c.InitialInterval = 2 * time.Second
    22  	}
    23  	if c.RandomizationFactor == 0 {
    24  		c.RandomizationFactor = 0.05
    25  	}
    26  	if c.Multiplier == 0 {
    27  		c.Multiplier = 2
    28  	}
    29  	if c.MaxInterval == 0 {
    30  		c.MaxInterval = 30 * time.Second
    31  	}
    32  	if c.MaxRetries == 0 {
    33  		c.MaxRetries = 5
    34  	}
    35  }
    36  
    37  // Build creates a new ExponentialBackOff using c's settings (if enabled).
    38  func (c ExponentialBackOffConfig) Build() backoff.BackOff {
    39  	if c.Enabled {
    40  		c.applyDefaults()
    41  		b := &backoff.ExponentialBackOff{
    42  			InitialInterval:     c.InitialInterval,
    43  			RandomizationFactor: c.RandomizationFactor,
    44  			Multiplier:          c.Multiplier,
    45  			MaxInterval:         c.MaxInterval,
    46  			Clock:               backoff.SystemClock,
    47  		}
    48  		return backoff.WithMaxRetries(b, c.MaxRetries)
    49  	}
    50  	return &backoff.StopBackOff{}
    51  }