bucket.go 11 KB

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