github.com/operator-framework/operator-lifecycle-manager@v0.30.0/pkg/lib/queueinformer/jitter.go (about)

     1  package queueinformer
     2  
     3  import (
     4  	"math"
     5  	"math/rand"
     6  	"time"
     7  )
     8  
     9  const DefaultResyncPeriod = 15 * time.Minute
    10  
    11  type float64er interface {
    12  	// Float64 returns a float64 in range [0.0, 1.0).
    13  	Float64() float64
    14  }
    15  
    16  type realFloat64er struct{}
    17  
    18  func (realFloat64er) Float64() float64 {
    19  	return rand.Float64()
    20  }
    21  
    22  // ResyncWithJitter takes a resync interval and adds jitter within a percent difference.
    23  // factor is a value between 0 and 1 indicating the amount of jitter
    24  // a factor of 0.2 and a period of 10m will have a range of 8 to 12 minutes (20%)
    25  func ResyncWithJitter(resyncPeriod time.Duration, factor float64) func() time.Duration {
    26  	return resyncWithJitter(resyncPeriod, factor, realFloat64er{})
    27  }
    28  
    29  func resyncWithJitter(period time.Duration, factor float64, rand float64er) func() time.Duration {
    30  	return func() time.Duration {
    31  		if period < 0.0 {
    32  			return DefaultResyncPeriod
    33  		}
    34  		if period > math.MaxInt64/2 { // 1281023h53m38.427387903s
    35  			// avoid overflowing time.Duration
    36  			return period
    37  		}
    38  		if factor < 0.0 || factor > 1.0 {
    39  			return period
    40  		}
    41  
    42  		// The effective scale will be in [1-factor, 1+factor) because rand.Float64() is in [0.0, 1.0).
    43  		return time.Duration((1 - factor + 2*rand.Float64()*factor) * float64(period))
    44  	}
    45  }