github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/http/ratelimit/ratelimit.go (about)

     1  package ratelimit
     2  
     3  import (
     4  	"math"
     5  	"strconv"
     6  	"sync"
     7  	"time"
     8  )
     9  
    10  // Bucket represents a token bucket that fills at a predetermined rate.
    11  // Methods on Bucket may be called concurrently.
    12  // See http://en.wikipedia.org/wiki/Token_bucket.
    13  type Bucket struct {
    14  	clock Clock
    15  
    16  	// startTime holds the moment when the bucket was
    17  	// first created and ticks began.
    18  	startTime time.Time
    19  
    20  	// capacity holds the overall capacity of the bucket.
    21  	capacity int64
    22  
    23  	// quantum holds how many tokens are added on
    24  	// each tick.
    25  	quantum int64
    26  
    27  	// fillInterval holds the interval between each tick.
    28  	fillInterval time.Duration
    29  
    30  	// mu guards the fields below it.
    31  	mu sync.Mutex
    32  
    33  	// availableTokens holds the number of available
    34  	// tokens as of the associated latestTick.
    35  	// It will be negative when there are consumers
    36  	// waiting for tokens.
    37  	availableTokens int64
    38  
    39  	// latestTick holds the latest tick for which
    40  	// we know the number of tokens in the bucket.
    41  	latestTick int64
    42  }
    43  
    44  // NewBucket returns a new token bucket that fills at the
    45  // rate of one token every fillInterval, up to the given
    46  // maximum capacity. Both arguments must be
    47  // positive. The bucket is initially full.
    48  func NewBucket(fillInterval time.Duration, capacity int64) *Bucket {
    49  	return NewBucketWithClock(fillInterval, capacity, nil)
    50  }
    51  
    52  // NewBucketWithClock is identical to NewBucket but injects a testable clock
    53  // interface.
    54  func NewBucketWithClock(fillInterval time.Duration, capacity int64, clock Clock) *Bucket {
    55  	return NewBucketWithQuantumAndClock(fillInterval, capacity, 1, clock)
    56  }
    57  
    58  // rateMargin specifes the allowed variance of actual
    59  // rate from specified rate. 1% seems reasonable.
    60  const rateMargin = 0.01
    61  
    62  // NewBucketWithRate returns a token bucket that fills the bucket
    63  // at the rate of rate tokens per second up to the given
    64  // maximum capacity. Because of limited clock resolution,
    65  // at high rates, the actual rate may be up to 1% different from the
    66  // specified rate.
    67  func NewBucketWithRate(rate float64, capacity int64) *Bucket {
    68  	return NewBucketWithRateAndClock(rate, capacity, nil)
    69  }
    70  
    71  // NewBucketWithRateAndClock is identical to NewBucketWithRate but injects a
    72  // testable clock interface.
    73  func NewBucketWithRateAndClock(rate float64, capacity int64, clock Clock) *Bucket {
    74  	// Use the same bucket each time through the loop
    75  	// to save allocations.
    76  	tb := NewBucketWithQuantumAndClock(1, capacity, 1, clock)
    77  	for quantum := int64(1); quantum < 1<<50; quantum = nextQuantum(quantum) {
    78  		fillInterval := time.Duration(1e9 * float64(quantum) / rate)
    79  		if fillInterval <= 0 {
    80  			continue
    81  		}
    82  		tb.fillInterval = fillInterval
    83  		tb.quantum = quantum
    84  		if diff := math.Abs(tb.Rate() - rate); diff/rate <= rateMargin {
    85  			return tb
    86  		}
    87  	}
    88  	panic("cannot find suitable quantum for " + strconv.FormatFloat(rate, 'g', -1, 64))
    89  }
    90  
    91  // nextQuantum returns the next quantum to try after q.
    92  // We grow the quantum exponentially, but slowly, so we
    93  // get a good fit in the lower numbers.
    94  func nextQuantum(q int64) int64 {
    95  	q1 := q * 11 / 10
    96  	if q1 == q {
    97  		q1++
    98  	}
    99  	return q1
   100  }
   101  
   102  // NewBucketWithQuantum is similar to NewBucket, but allows
   103  // the specification of the quantum size - quantum tokens
   104  // are added every fillInterval.
   105  func NewBucketWithQuantum(fillInterval time.Duration, capacity, quantum int64) *Bucket {
   106  	return NewBucketWithQuantumAndClock(fillInterval, capacity, quantum, nil)
   107  }
   108  
   109  // NewBucketWithQuantumAndClock is like NewBucketWithQuantum, but
   110  // also has a clock argument that allows clients to fake the passing
   111  // of time. If clock is nil, the system clock will be used.
   112  func NewBucketWithQuantumAndClock(fillInterval time.Duration, capacity, quantum int64, clock Clock) *Bucket {
   113  	if clock == nil {
   114  		clock = realClock{}
   115  	}
   116  	if fillInterval <= 0 {
   117  		panic("token bucket fill interval is not > 0")
   118  	}
   119  	if capacity <= 0 {
   120  		panic("token bucket capacity is not > 0")
   121  	}
   122  	if quantum <= 0 {
   123  		panic("token bucket quantum is not > 0")
   124  	}
   125  	return &Bucket{
   126  		clock:           clock,
   127  		startTime:       clock.Now(),
   128  		latestTick:      0,
   129  		fillInterval:    fillInterval,
   130  		capacity:        capacity,
   131  		quantum:         quantum,
   132  		availableTokens: capacity,
   133  	}
   134  }
   135  
   136  // Wait takes count tokens from the bucket, waiting until they are
   137  // available.
   138  func (tb *Bucket) Wait(count int64) {
   139  	if d := tb.Take(count); d > 0 {
   140  		tb.clock.Sleep(d)
   141  	}
   142  }
   143  
   144  // WaitMaxDuration is like Wait except that it will
   145  // only take tokens from the bucket if it needs to wait
   146  // for no greater than maxWait. It reports whether
   147  // any tokens have been removed from the bucket
   148  // If no tokens have been removed, it returns immediately.
   149  func (tb *Bucket) WaitMaxDuration(count int64, maxWait time.Duration) bool {
   150  	d, ok := tb.TakeMaxDuration(count, maxWait)
   151  	if d > 0 {
   152  		tb.clock.Sleep(d)
   153  	}
   154  	return ok
   155  }
   156  
   157  const infinityDuration time.Duration = 0x7fffffffffffffff
   158  
   159  // Take takes count tokens from the bucket without blocking. It returns
   160  // the time that the caller should wait until the tokens are actually
   161  // available.
   162  //
   163  // Note that if the request is irrevocable - there is no way to return
   164  // tokens to the bucket once this method commits us to taking them.
   165  func (tb *Bucket) Take(count int64) time.Duration {
   166  	tb.mu.Lock()
   167  	defer tb.mu.Unlock()
   168  	d, _ := tb.take(tb.clock.Now(), count, infinityDuration)
   169  	return d
   170  }
   171  
   172  // TakeMaxDuration is like Take, except that
   173  // it will only take tokens from the bucket if the wait
   174  // time for the tokens is no greater than maxWait.
   175  //
   176  // If it would take longer than maxWait for the tokens
   177  // to become available, it does nothing and reports false,
   178  // otherwise it returns the time that the caller should
   179  // wait until the tokens are actually available, and reports
   180  // true.
   181  func (tb *Bucket) TakeMaxDuration(count int64, maxWait time.Duration) (time.Duration, bool) {
   182  	tb.mu.Lock()
   183  	defer tb.mu.Unlock()
   184  	return tb.take(tb.clock.Now(), count, maxWait)
   185  }
   186  
   187  // TakeAvailable takes up to count immediately available tokens from the
   188  // bucket. It returns the number of tokens removed, or zero if there are
   189  // no available tokens. It does not block.
   190  func (tb *Bucket) TakeAvailable(count int64) int64 {
   191  	tb.mu.Lock()
   192  	defer tb.mu.Unlock()
   193  	return tb.takeAvailable(tb.clock.Now(), count)
   194  }
   195  
   196  // takeAvailable is the internal version of TakeAvailable - it takes the
   197  // current time as an argument to enable easy testing.
   198  func (tb *Bucket) takeAvailable(now time.Time, count int64) int64 {
   199  	if count <= 0 {
   200  		return 0
   201  	}
   202  	tb.adjustavailableTokens(tb.currentTick(now))
   203  	if tb.availableTokens <= 0 {
   204  		return 0
   205  	}
   206  	if count > tb.availableTokens {
   207  		count = tb.availableTokens
   208  	}
   209  	tb.availableTokens -= count
   210  	return count
   211  }
   212  
   213  // Available returns the number of available tokens. It will be negative
   214  // when there are consumers waiting for tokens. Note that if this
   215  // returns greater than zero, it does not guarantee that calls that take
   216  // tokens from the buffer will succeed, as the number of available
   217  // tokens could have changed in the meantime. This method is intended
   218  // primarily for metrics reporting and debugging.
   219  func (tb *Bucket) Available() int64 {
   220  	return tb.available(tb.clock.Now())
   221  }
   222  
   223  // available is the internal version of available - it takes the current time as
   224  // an argument to enable easy testing.
   225  func (tb *Bucket) available(now time.Time) int64 {
   226  	tb.mu.Lock()
   227  	defer tb.mu.Unlock()
   228  	tb.adjustavailableTokens(tb.currentTick(now))
   229  	return tb.availableTokens
   230  }
   231  
   232  // Capacity returns the capacity that the bucket was created with.
   233  func (tb *Bucket) Capacity() int64 {
   234  	return tb.capacity
   235  }
   236  
   237  // Rate returns the fill rate of the bucket, in tokens per second.
   238  func (tb *Bucket) Rate() float64 {
   239  	return 1e9 * float64(tb.quantum) / float64(tb.fillInterval)
   240  }
   241  
   242  // take is the internal version of Take - it takes the current time as
   243  // an argument to enable easy testing.
   244  func (tb *Bucket) take(now time.Time, count int64, maxWait time.Duration) (time.Duration, bool) {
   245  	if count <= 0 {
   246  		return 0, true
   247  	}
   248  
   249  	tick := tb.currentTick(now)
   250  	tb.adjustavailableTokens(tick)
   251  	avail := tb.availableTokens - count
   252  	if avail >= 0 {
   253  		tb.availableTokens = avail
   254  		return 0, true
   255  	}
   256  	// Round up the missing tokens to the nearest multiple
   257  	// of quantum - the tokens won't be available until
   258  	// that tick.
   259  
   260  	// endTick holds the tick when all the requested tokens will
   261  	// become available.
   262  	endTick := tick + (-avail+tb.quantum-1)/tb.quantum
   263  	endTime := tb.startTime.Add(time.Duration(endTick) * tb.fillInterval)
   264  	waitTime := endTime.Sub(now)
   265  	if waitTime > maxWait {
   266  		return 0, false
   267  	}
   268  	tb.availableTokens = avail
   269  	return waitTime, true
   270  }
   271  
   272  // currentTick returns the current time tick, measured
   273  // from tb.startTime.
   274  func (tb *Bucket) currentTick(now time.Time) int64 {
   275  	return int64(now.Sub(tb.startTime) / tb.fillInterval)
   276  }
   277  
   278  // adjustavailableTokens adjusts the current number of tokens
   279  // available in the bucket at the given time, which must
   280  // be in the future (positive) with respect to tb.latestTick.
   281  func (tb *Bucket) adjustavailableTokens(tick int64) {
   282  	lastTick := tb.latestTick
   283  	tb.latestTick = tick
   284  	if tb.availableTokens >= tb.capacity {
   285  		return
   286  	}
   287  	tb.availableTokens += (tick - lastTick) * tb.quantum
   288  	if tb.availableTokens > tb.capacity {
   289  		tb.availableTokens = tb.capacity
   290  	}
   291  	return
   292  }
   293  
   294  // Clock represents the passage of time in a way that
   295  // can be faked out for tests.
   296  type Clock interface {
   297  	// Now returns the current time.
   298  	Now() time.Time
   299  	// Sleep sleeps for at least the given duration.
   300  	Sleep(d time.Duration)
   301  }
   302  
   303  // realClock implements Clock in terms of standard time functions.
   304  type realClock struct{}
   305  
   306  // Now implements Clock.Now by calling time.Now.
   307  func (realClock) Now() time.Time {
   308  	return time.Now()
   309  }
   310  
   311  // Now implements Clock.Sleep by calling time.Sleep.
   312  func (realClock) Sleep(d time.Duration) {
   313  	time.Sleep(d)
   314  }