File: token_bucket.go

package info (click to toggle)
golang-github-weaveworks-mesh 0%2Bgit20161024.3dd75b1-1~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 412 kB
  • sloc: sh: 59; makefile: 7
file content (48 lines) | stat: -rw-r--r-- 1,536 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package mesh

import (
	"time"
)

// TokenBucket acts as a rate-limiter.
// It is not safe for concurrent use by multiple goroutines.
type tokenBucket struct {
	capacity             int64         // Maximum capacity of bucket
	tokenInterval        time.Duration // Token replenishment rate
	refillDuration       time.Duration // Time to refill from empty
	earliestUnspentToken time.Time
}

// newTokenBucket returns a bucket containing capacity tokens, refilled at a
// rate of one token per tokenInterval.
func newTokenBucket(capacity int64, tokenInterval time.Duration) *tokenBucket {
	tb := tokenBucket{
		capacity:       capacity,
		tokenInterval:  tokenInterval,
		refillDuration: tokenInterval * time.Duration(capacity)}

	tb.earliestUnspentToken = tb.capacityToken()

	return &tb
}

// Blocks until there is a token available.
// Not safe for concurrent use by multiple goroutines.
func (tb *tokenBucket) wait() {
	// If earliest unspent token is in the future, sleep until then
	time.Sleep(tb.earliestUnspentToken.Sub(time.Now()))

	// Alternatively, enforce bucket capacity if necessary
	capacityToken := tb.capacityToken()
	if tb.earliestUnspentToken.Before(capacityToken) {
		tb.earliestUnspentToken = capacityToken
	}

	// 'Remove' a token from the bucket
	tb.earliestUnspentToken = tb.earliestUnspentToken.Add(tb.tokenInterval)
}

// Determine the historic token timestamp representing a full bucket
func (tb *tokenBucket) capacityToken() time.Time {
	return time.Now().Add(-tb.refillDuration).Truncate(tb.tokenInterval)
}