rate.go 12 KB

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