rate.go 12 KB

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