You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

375 lines
11 KiB

  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. if n > lim.burst && lim.limit != Inf {
  200. return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, lim.burst)
  201. }
  202. // Check if ctx is already cancelled
  203. select {
  204. case <-ctx.Done():
  205. return ctx.Err()
  206. default:
  207. }
  208. // Determine wait limit
  209. now := time.Now()
  210. waitLimit := InfDuration
  211. if deadline, ok := ctx.Deadline(); ok {
  212. waitLimit = deadline.Sub(now)
  213. }
  214. // Reserve
  215. r := lim.reserveN(now, n, waitLimit)
  216. if !r.ok {
  217. return fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n)
  218. }
  219. // Wait if necessary
  220. delay := r.DelayFrom(now)
  221. if delay == 0 {
  222. return nil
  223. }
  224. t := time.NewTimer(delay)
  225. defer t.Stop()
  226. select {
  227. case <-t.C:
  228. // We can proceed.
  229. return nil
  230. case <-ctx.Done():
  231. // Context was canceled before we could proceed. Cancel the
  232. // reservation, which may permit other events to proceed sooner.
  233. r.Cancel()
  234. return ctx.Err()
  235. }
  236. }
  237. // SetLimit is shorthand for SetLimitAt(time.Now(), newLimit).
  238. func (lim *Limiter) SetLimit(newLimit Limit) {
  239. lim.SetLimitAt(time.Now(), newLimit)
  240. }
  241. // SetLimitAt sets a new Limit for the limiter. The new Limit, and Burst, may be violated
  242. // or underutilized by those which reserved (using Reserve or Wait) but did not yet act
  243. // before SetLimitAt was called.
  244. func (lim *Limiter) SetLimitAt(now time.Time, newLimit Limit) {
  245. lim.mu.Lock()
  246. defer lim.mu.Unlock()
  247. now, _, tokens := lim.advance(now)
  248. lim.last = now
  249. lim.tokens = tokens
  250. lim.limit = newLimit
  251. }
  252. // reserveN is a helper method for AllowN, ReserveN, and WaitN.
  253. // maxFutureReserve specifies the maximum reservation wait duration allowed.
  254. // reserveN returns Reservation, not *Reservation, to avoid allocation in AllowN and WaitN.
  255. func (lim *Limiter) reserveN(now time.Time, n int, maxFutureReserve time.Duration) Reservation {
  256. lim.mu.Lock()
  257. if lim.limit == Inf {
  258. lim.mu.Unlock()
  259. return Reservation{
  260. ok: true,
  261. lim: lim,
  262. tokens: n,
  263. timeToAct: now,
  264. }
  265. }
  266. now, last, tokens := lim.advance(now)
  267. // Calculate the remaining number of tokens resulting from the request.
  268. tokens -= float64(n)
  269. // Calculate the wait duration
  270. var waitDuration time.Duration
  271. if tokens < 0 {
  272. waitDuration = lim.limit.durationFromTokens(-tokens)
  273. }
  274. // Decide result
  275. ok := n <= lim.burst && waitDuration <= maxFutureReserve
  276. // Prepare reservation
  277. r := Reservation{
  278. ok: ok,
  279. lim: lim,
  280. limit: lim.limit,
  281. }
  282. if ok {
  283. r.tokens = n
  284. r.timeToAct = now.Add(waitDuration)
  285. }
  286. // Update state
  287. if ok {
  288. lim.last = now
  289. lim.tokens = tokens
  290. lim.lastEvent = r.timeToAct
  291. } else {
  292. lim.last = last
  293. }
  294. lim.mu.Unlock()
  295. return r
  296. }
  297. // advance calculates and returns an updated state for lim resulting from the passage of time.
  298. // lim is not changed.
  299. func (lim *Limiter) advance(now time.Time) (newNow time.Time, newLast time.Time, newTokens float64) {
  300. last := lim.last
  301. if now.Before(last) {
  302. last = now
  303. }
  304. // Avoid making delta overflow below when last is very old.
  305. maxElapsed := lim.limit.durationFromTokens(float64(lim.burst) - lim.tokens)
  306. elapsed := now.Sub(last)
  307. if elapsed > maxElapsed {
  308. elapsed = maxElapsed
  309. }
  310. // Calculate the new number of tokens, due to time that passed.
  311. delta := lim.limit.tokensFromDuration(elapsed)
  312. tokens := lim.tokens + delta
  313. if burst := float64(lim.burst); tokens > burst {
  314. tokens = burst
  315. }
  316. return now, last, tokens
  317. }
  318. // durationFromTokens is a unit conversion function from the number of tokens to the duration
  319. // of time it takes to accumulate them at a rate of limit tokens per second.
  320. func (limit Limit) durationFromTokens(tokens float64) time.Duration {
  321. seconds := tokens / float64(limit)
  322. return time.Nanosecond * time.Duration(1e9*seconds)
  323. }
  324. // tokensFromDuration is a unit conversion function from a time duration to the number of tokens
  325. // which could be accumulated during that duration at a rate of limit tokens per second.
  326. func (limit Limit) tokensFromDuration(d time.Duration) float64 {
  327. return d.Seconds() * float64(limit)
  328. }