rate.go 12 KB

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