rate.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package rate provides a rate limiter.
  5. package rate
  6. import (
  7. "fmt"
  8. "math"
  9. "sync"
  10. "time"
  11. )
  12. // Limit defines the maximum frequency of some events.
  13. // Limit is represented as number of events per second.
  14. // A zero Limit allows no events.
  15. type Limit float64
  16. // Inf is the infinite rate limit; it allows all events (even if burst is zero).
  17. const Inf = Limit(math.MaxFloat64)
  18. // Every converts a minimum time interval between events to a Limit.
  19. func Every(interval time.Duration) Limit {
  20. if interval <= 0 {
  21. return Inf
  22. }
  23. return 1 / Limit(interval.Seconds())
  24. }
  25. // A Limiter controls how frequently events are allowed to happen.
  26. // It implements a "token bucket" of size b, initially full and refilled
  27. // at rate r tokens per second.
  28. // Informally, in any large enough time interval, the Limiter limits the
  29. // rate to r tokens per second, with a maximum burst size of b events.
  30. // As a special case, if r == Inf (the infinite rate), b is ignored.
  31. // See https://en.wikipedia.org/wiki/Token_bucket for more about token buckets.
  32. //
  33. // The zero value is a valid Limiter, but it will reject all events.
  34. // Use NewLimiter to create non-zero Limiters.
  35. //
  36. // Limiter has three main methods, Allow, Reserve, and Wait.
  37. // Most callers should use Wait.
  38. //
  39. // Each of the three methods consumes a single token.
  40. // They differ in their behavior when no token is available.
  41. // If no token is available, Allow returns false.
  42. // If no token is available, Reserve returns a reservation for a future token
  43. // and the amount of time the caller must wait before using it.
  44. // If no token is available, Wait blocks until one can be obtained
  45. // or its associated context.Context is canceled.
  46. //
  47. // The methods AllowN, ReserveN, and WaitN consume n tokens.
  48. type Limiter struct {
  49. limit Limit
  50. burst int
  51. mu sync.Mutex
  52. tokens float64
  53. // last is the last time the limiter's tokens field was updated
  54. last time.Time
  55. // lastEvent is the latest time of a rate-limited event (past or future)
  56. lastEvent time.Time
  57. }
  58. // Limit returns the maximum overall event rate.
  59. func (lim *Limiter) Limit() Limit {
  60. lim.mu.Lock()
  61. defer lim.mu.Unlock()
  62. return lim.limit
  63. }
  64. // Burst returns the maximum burst size. Burst is the maximum number of tokens
  65. // that can be consumed in a single call to Allow, Reserve, or Wait, so higher
  66. // Burst values allow more events to happen at once.
  67. // A zero Burst allows no events, unless limit == Inf.
  68. func (lim *Limiter) Burst() int {
  69. return lim.burst
  70. }
  71. // NewLimiter returns a new Limiter that allows events up to rate r and permits
  72. // bursts of at most b tokens.
  73. func NewLimiter(r Limit, b int) *Limiter {
  74. return &Limiter{
  75. limit: r,
  76. burst: b,
  77. }
  78. }
  79. // Allow is shorthand for AllowN(time.Now(), 1).
  80. func (lim *Limiter) Allow() bool {
  81. return lim.AllowN(time.Now(), 1)
  82. }
  83. // AllowN reports whether n events may happen at time now.
  84. // Use this method if you intend to drop / skip events that exceed the rate limit.
  85. // Otherwise use Reserve or Wait.
  86. func (lim *Limiter) AllowN(now time.Time, n int) bool {
  87. return lim.reserveN(now, n, 0).ok
  88. }
  89. // A Reservation holds information about events that are permitted by a Limiter to happen after a delay.
  90. // A Reservation may be canceled, which may enable the Limiter to permit additional events.
  91. type Reservation struct {
  92. ok bool
  93. lim *Limiter
  94. tokens int
  95. timeToAct time.Time
  96. // This is the Limit at reservation time, it can change later.
  97. limit Limit
  98. }
  99. // OK returns whether the limiter can provide the requested number of tokens
  100. // within the maximum wait time. If OK is false, Delay returns InfDuration, and
  101. // Cancel does nothing.
  102. func (r *Reservation) OK() bool {
  103. return r.ok
  104. }
  105. // Delay is shorthand for DelayFrom(time.Now()).
  106. func (r *Reservation) Delay() time.Duration {
  107. return r.DelayFrom(time.Now())
  108. }
  109. // InfDuration is the duration returned by Delay when a Reservation is not OK.
  110. const InfDuration = time.Duration(1<<63 - 1)
  111. // DelayFrom returns the duration for which the reservation holder must wait
  112. // before taking the reserved action. Zero duration means act immediately.
  113. // InfDuration means the limiter cannot grant the tokens requested in this
  114. // Reservation within the maximum wait time.
  115. func (r *Reservation) DelayFrom(now time.Time) time.Duration {
  116. if !r.ok {
  117. return InfDuration
  118. }
  119. delay := r.timeToAct.Sub(now)
  120. if delay < 0 {
  121. return 0
  122. }
  123. return delay
  124. }
  125. // Cancel is shorthand for CancelAt(time.Now()).
  126. func (r *Reservation) Cancel() {
  127. r.CancelAt(time.Now())
  128. return
  129. }
  130. // CancelAt indicates that the reservation holder will not perform the reserved action
  131. // and reverses the effects of this Reservation on the rate limit as much as possible,
  132. // considering that other reservations may have already been made.
  133. func (r *Reservation) CancelAt(now time.Time) {
  134. if !r.ok {
  135. return
  136. }
  137. r.lim.mu.Lock()
  138. defer r.lim.mu.Unlock()
  139. if r.lim.limit == Inf || r.tokens == 0 || r.timeToAct.Before(now) {
  140. return
  141. }
  142. // calculate tokens to restore
  143. // The duration between lim.lastEvent and r.timeToAct tells us how many tokens were reserved
  144. // after r was obtained. These tokens should not be restored.
  145. restoreTokens := float64(r.tokens) - r.limit.tokensFromDuration(r.lim.lastEvent.Sub(r.timeToAct))
  146. if restoreTokens <= 0 {
  147. return
  148. }
  149. // advance time to now
  150. now, _, tokens := r.lim.advance(now)
  151. // calculate new number of tokens
  152. tokens += restoreTokens
  153. if burst := float64(r.lim.burst); tokens > burst {
  154. tokens = burst
  155. }
  156. // update state
  157. r.lim.last = now
  158. r.lim.tokens = tokens
  159. if r.timeToAct == r.lim.lastEvent {
  160. prevEvent := r.timeToAct.Add(r.limit.durationFromTokens(float64(-r.tokens)))
  161. if !prevEvent.Before(now) {
  162. r.lim.lastEvent = prevEvent
  163. }
  164. }
  165. return
  166. }
  167. // Reserve is shorthand for ReserveN(time.Now(), 1).
  168. func (lim *Limiter) Reserve() *Reservation {
  169. return lim.ReserveN(time.Now(), 1)
  170. }
  171. // ReserveN returns a Reservation that indicates how long the caller must wait before n events happen.
  172. // The Limiter takes this Reservation into account when allowing future events.
  173. // ReserveN returns false if n exceeds the Limiter's burst size.
  174. // Usage example:
  175. // r := lim.ReserveN(time.Now(), 1)
  176. // if !r.OK() {
  177. // // Not allowed to act! Did you remember to set lim.burst to be > 0 ?
  178. // return
  179. // }
  180. // time.Sleep(r.Delay())
  181. // Act()
  182. // Use this method if you wish to wait and slow down in accordance with the rate limit without dropping events.
  183. // If you need to respect a deadline or cancel the delay, use Wait instead.
  184. // To drop or skip events exceeding rate limit, use Allow instead.
  185. func (lim *Limiter) ReserveN(now time.Time, n int) *Reservation {
  186. r := lim.reserveN(now, n, InfDuration)
  187. return &r
  188. }
  189. // contextContext is a temporary(?) copy of the context.Context type
  190. // to support both Go 1.6 using golang.org/x/net/context and Go 1.7+
  191. // with the built-in context package. If people ever stop using Go 1.6
  192. // we can remove this.
  193. type contextContext interface {
  194. Deadline() (deadline time.Time, ok bool)
  195. Done() <-chan struct{}
  196. Err() error
  197. Value(key interface{}) interface{}
  198. }
  199. // Wait is shorthand for WaitN(ctx, 1).
  200. func (lim *Limiter) wait(ctx contextContext) (err error) {
  201. return lim.WaitN(ctx, 1)
  202. }
  203. // WaitN blocks until lim permits n events to happen.
  204. // It returns an error if n exceeds the Limiter's burst size, the Context is
  205. // canceled, or the expected wait time exceeds the Context's Deadline.
  206. // The burst limit is ignored if the rate limit is Inf.
  207. func (lim *Limiter) waitN(ctx contextContext, n int) (err error) {
  208. if n > lim.burst && lim.limit != Inf {
  209. return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, lim.burst)
  210. }
  211. // Check if ctx is already cancelled
  212. select {
  213. case <-ctx.Done():
  214. return ctx.Err()
  215. default:
  216. }
  217. // Determine wait limit
  218. now := time.Now()
  219. waitLimit := InfDuration
  220. if deadline, ok := ctx.Deadline(); ok {
  221. waitLimit = deadline.Sub(now)
  222. }
  223. // Reserve
  224. r := lim.reserveN(now, n, waitLimit)
  225. if !r.ok {
  226. return fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n)
  227. }
  228. // Wait if necessary
  229. delay := r.DelayFrom(now)
  230. if delay == 0 {
  231. return nil
  232. }
  233. t := time.NewTimer(delay)
  234. defer t.Stop()
  235. select {
  236. case <-t.C:
  237. // We can proceed.
  238. return nil
  239. case <-ctx.Done():
  240. // Context was canceled before we could proceed. Cancel the
  241. // reservation, which may permit other events to proceed sooner.
  242. r.Cancel()
  243. return ctx.Err()
  244. }
  245. }
  246. // SetLimit is shorthand for SetLimitAt(time.Now(), newLimit).
  247. func (lim *Limiter) SetLimit(newLimit Limit) {
  248. lim.SetLimitAt(time.Now(), newLimit)
  249. }
  250. // SetLimitAt sets a new Limit for the limiter. The new Limit, and Burst, may be violated
  251. // or underutilized by those which reserved (using Reserve or Wait) but did not yet act
  252. // before SetLimitAt was called.
  253. func (lim *Limiter) SetLimitAt(now time.Time, newLimit Limit) {
  254. lim.mu.Lock()
  255. defer lim.mu.Unlock()
  256. now, _, tokens := lim.advance(now)
  257. lim.last = now
  258. lim.tokens = tokens
  259. lim.limit = newLimit
  260. }
  261. // reserveN is a helper method for AllowN, ReserveN, and WaitN.
  262. // maxFutureReserve specifies the maximum reservation wait duration allowed.
  263. // reserveN returns Reservation, not *Reservation, to avoid allocation in AllowN and WaitN.
  264. func (lim *Limiter) reserveN(now time.Time, n int, maxFutureReserve time.Duration) Reservation {
  265. lim.mu.Lock()
  266. if lim.limit == Inf {
  267. lim.mu.Unlock()
  268. return Reservation{
  269. ok: true,
  270. lim: lim,
  271. tokens: n,
  272. timeToAct: now,
  273. }
  274. }
  275. now, last, tokens := lim.advance(now)
  276. // Calculate the remaining number of tokens resulting from the request.
  277. tokens -= float64(n)
  278. // Calculate the wait duration
  279. var waitDuration time.Duration
  280. if tokens < 0 {
  281. waitDuration = lim.limit.durationFromTokens(-tokens)
  282. }
  283. // Decide result
  284. ok := n <= lim.burst && waitDuration <= maxFutureReserve
  285. // Prepare reservation
  286. r := Reservation{
  287. ok: ok,
  288. lim: lim,
  289. limit: lim.limit,
  290. }
  291. if ok {
  292. r.tokens = n
  293. r.timeToAct = now.Add(waitDuration)
  294. }
  295. // Update state
  296. if ok {
  297. lim.last = now
  298. lim.tokens = tokens
  299. lim.lastEvent = r.timeToAct
  300. } else {
  301. lim.last = last
  302. }
  303. lim.mu.Unlock()
  304. return r
  305. }
  306. // advance calculates and returns an updated state for lim resulting from the passage of time.
  307. // lim is not changed.
  308. func (lim *Limiter) advance(now time.Time) (newNow time.Time, newLast time.Time, newTokens float64) {
  309. last := lim.last
  310. if now.Before(last) {
  311. last = now
  312. }
  313. // Avoid making delta overflow below when last is very old.
  314. maxElapsed := lim.limit.durationFromTokens(float64(lim.burst) - lim.tokens)
  315. elapsed := now.Sub(last)
  316. if elapsed > maxElapsed {
  317. elapsed = maxElapsed
  318. }
  319. // Calculate the new number of tokens, due to time that passed.
  320. delta := lim.limit.tokensFromDuration(elapsed)
  321. tokens := lim.tokens + delta
  322. if burst := float64(lim.burst); tokens > burst {
  323. tokens = burst
  324. }
  325. return now, last, tokens
  326. }
  327. // durationFromTokens is a unit conversion function from the number of tokens to the duration
  328. // of time it takes to accumulate them at a rate of limit tokens per second.
  329. func (limit Limit) durationFromTokens(tokens float64) time.Duration {
  330. seconds := tokens / float64(limit)
  331. return time.Nanosecond * time.Duration(1e9*seconds)
  332. }
  333. // tokensFromDuration is a unit conversion function from a time duration to the number of tokens
  334. // which could be accumulated during that duration at a rate of limit tokens per second.
  335. func (limit Limit) tokensFromDuration(d time.Duration) float64 {
  336. return d.Seconds() * float64(limit)
  337. }