rate.go 12 KB

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