cubefs
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
5// Package rate provides a rate limiter.
6package rate7
8import (9"context"10"fmt"11"math"12"sync"13"time"14)
15
16// Limit defines the maximum frequency of some events.
17// Limit is represented as number of events per second.
18// A zero Limit allows no events.
19type Limit float6420
21// Inf is the infinite rate limit; it allows all events (even if burst is zero).
22const Inf = Limit(math.MaxFloat64)23
24// Every converts a minimum time interval between events to a Limit.
25func Every(interval time.Duration) Limit {26if interval <= 0 {27return Inf28}29return 1 / Limit(interval.Seconds())30}
31
32// A Limiter controls how frequently events are allowed to happen.
33// It implements a "token bucket" of size b, initially full and refilled
34// at rate r tokens per second.
35// Informally, in any large enough time interval, the Limiter limits the
36// rate to r tokens per second, with a maximum burst size of b events.
37// As a special case, if r == Inf (the infinite rate), b is ignored.
38// See https://en.wikipedia.org/wiki/Token_bucket for more about token buckets.
39//
40// The zero value is a valid Limiter, but it will reject all events.
41// Use NewLimiter to create non-zero Limiters.
42//
43// Limiter has three main methods, Allow, Reserve, and Wait.
44// Most callers should use Wait.
45//
46// Each of the three methods consumes a single token.
47// They differ in their behavior when no token is available.
48// If no token is available, Allow returns false.
49// If no token is available, Reserve returns a reservation for a future token
50// and the amount of time the caller must wait before using it.
51// If no token is available, Wait blocks until one can be obtained
52// or its associated context.Context is canceled.
53//
54// The methods AllowN, ReserveN, and WaitN consume n tokens.
55type Limiter struct {56mu sync.Mutex57limit Limit
58burst int59tokens float6460// last is the last time the limiter's tokens field was updated61last time.Time62// lastEvent is the latest time of a rate-limited event (past or future)63lastEvent time.Time64}
65
66// Limit returns the maximum overall event rate.
67func (lim *Limiter) Limit() Limit {68lim.mu.Lock()69defer lim.mu.Unlock()70return lim.limit71}
72
73// Burst returns the maximum burst size. Burst is the maximum number of tokens
74// that can be consumed in a single call to Allow, Reserve, or Wait, so higher
75// Burst values allow more events to happen at once.
76// A zero Burst allows no events, unless limit == Inf.
77func (lim *Limiter) Burst() int {78lim.mu.Lock()79defer lim.mu.Unlock()80return lim.burst81}
82
83// NewLimiter returns a new Limiter that allows events up to rate r and permits
84// bursts of at most b tokens.
85func NewLimiter(r Limit, b int) *Limiter {86return &Limiter{87limit: r,88burst: b,89}90}
91
92// Allow is shorthand for AllowN(time.Now(), 1).
93func (lim *Limiter) Allow() bool {94return lim.AllowN(time.Now(), 1)95}
96
97// AllowN reports whether n events may happen at time now.
98// Use this method if you intend to drop / skip events that exceed the rate limit.
99// Otherwise use Reserve or Wait.
100func (lim *Limiter) AllowN(now time.Time, n int) bool {101return lim.reserveN(now, n, 0).ok102}
103
104// A Reservation holds information about events that are permitted by a Limiter to happen after a delay.
105// A Reservation may be canceled, which may enable the Limiter to permit additional events.
106type Reservation struct {107ok bool108lim *Limiter109tokens int110timeToAct time.Time111// This is the Limit at reservation time, it can change later.112limit Limit
113}
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.
118func (r *Reservation) OK() bool {119return r.ok120}
121
122// Delay is shorthand for DelayFrom(time.Now()).
123func (r *Reservation) Delay() time.Duration {124return r.DelayFrom(time.Now())125}
126
127// InfDuration is the duration returned by Delay when a Reservation is not OK.
128const InfDuration = time.Duration(1<<63 - 1)129
130// DelayFrom returns the duration for which the reservation holder must wait
131// before taking the reserved action. Zero duration means act immediately.
132// InfDuration means the limiter cannot grant the tokens requested in this
133// Reservation within the maximum wait time.
134func (r *Reservation) DelayFrom(now time.Time) time.Duration {135if !r.ok {136return InfDuration137}138delay := r.timeToAct.Sub(now)139if delay < 0 {140return 0141}142return delay143}
144
145// Cancel is shorthand for CancelAt(time.Now()).
146func (r *Reservation) Cancel() {147r.CancelAt(time.Now())148}
149
150// CancelAt indicates that the reservation holder will not perform the reserved action
151// and reverses the effects of this Reservation on the rate limit as much as possible,
152// considering that other reservations may have already been made.
153func (r *Reservation) CancelAt(now time.Time) {154if !r.ok {155return156}157
158r.lim.mu.Lock()159defer r.lim.mu.Unlock()160
161if r.lim.limit == Inf || r.tokens == 0 || r.timeToAct.Before(now) {162return163}164
165// calculate tokens to restore166// The duration between lim.lastEvent and r.timeToAct tells us how many tokens were reserved167// after r was obtained. These tokens should not be restored.168restoreTokens := float64(r.tokens) - r.limit.tokensFromDuration(r.lim.lastEvent.Sub(r.timeToAct))169if restoreTokens <= 0 {170return171}172// advance time to now173now, _, tokens := r.lim.advance(now)174// calculate new number of tokens175tokens += restoreTokens176if burst := float64(r.lim.burst); tokens > burst {177tokens = burst178}179// update state180r.lim.last = now181r.lim.tokens = tokens182if r.timeToAct == r.lim.lastEvent {183prevEvent := r.timeToAct.Add(r.limit.durationFromTokens(float64(-r.tokens)))184if !prevEvent.Before(now) {185r.lim.lastEvent = prevEvent186}187}188}
189
190// Reserve is shorthand for ReserveN(time.Now(), 1).
191func (lim *Limiter) Reserve() *Reservation {192return lim.ReserveN(time.Now(), 1)193}
194
195// ReserveN returns a Reservation that indicates how long the caller must wait before n events happen.
196// The Limiter takes this Reservation into account when allowing future events.
197// The returned Reservation’s OK() method returns false if n exceeds the Limiter's burst size.
198// Usage example:
199// r := lim.ReserveN(time.Now(), 1)
200// if !r.OK() {
201// // Not allowed to act! Did you remember to set lim.burst to be > 0 ?
202// return
203// }
204// time.Sleep(r.Delay())
205// Act()
206// Use this method if you wish to wait and slow down in accordance with the rate limit without dropping events.
207// If you need to respect a deadline or cancel the delay, use Wait instead.
208// To drop or skip events exceeding rate limit, use Allow instead.
209func (lim *Limiter) ReserveN(now time.Time, n int) *Reservation {210r := lim.reserveN(now, n, InfDuration)211return &r212}
213
214// Wait is shorthand for WaitN(ctx, 1).
215func (lim *Limiter) Wait(ctx context.Context) (err error) {216return lim.WaitN(ctx, 1)217}
218
219// WaitN blocks until lim permits n events to happen.
220// It returns an error if n exceeds the Limiter's burst size, the Context is
221// canceled, or the expected wait time exceeds the Context's Deadline.
222// The burst limit is ignored if the rate limit is Inf.
223func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) {224lim.mu.Lock()225burst := lim.burst226limit := lim.limit227lim.mu.Unlock()228
229if n > burst && limit != Inf {230return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, burst)231}232// Check if ctx is already cancelled233select {234case <-ctx.Done():235return ctx.Err()236default:237}238// Determine wait limit239now := time.Now()240waitLimit := InfDuration241if deadline, ok := ctx.Deadline(); ok {242waitLimit = deadline.Sub(now)243}244// Reserve245r := lim.reserveN(now, n, waitLimit)246if !r.ok {247return fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n)248}249// Wait if necessary250delay := r.DelayFrom(now)251if delay == 0 {252return nil253}254t := time.NewTimer(delay)255defer t.Stop()256select {257case <-t.C:258// We can proceed.259return nil260case <-ctx.Done():261// Context was canceled before we could proceed. Cancel the262// reservation, which may permit other events to proceed sooner.263r.Cancel()264return ctx.Err()265}266}
267
268// SetLimit is shorthand for SetLimitAt(time.Now(), newLimit).
269func (lim *Limiter) SetLimit(newLimit Limit) {270lim.SetLimitAt(time.Now(), newLimit)271}
272
273// SetLimitAt sets a new Limit for the limiter. The new Limit, and Burst, may be violated
274// or underutilized by those which reserved (using Reserve or Wait) but did not yet act
275// before SetLimitAt was called.
276func (lim *Limiter) SetLimitAt(now time.Time, newLimit Limit) {277lim.mu.Lock()278defer lim.mu.Unlock()279
280now, _, tokens := lim.advance(now)281
282lim.last = now283lim.tokens = tokens284lim.limit = newLimit285}
286
287// SetBurst is shorthand for SetBurstAt(time.Now(), newBurst).
288func (lim *Limiter) SetBurst(newBurst int) {289lim.SetBurstAt(time.Now(), newBurst)290}
291
292// SetBurstAt sets a new burst size for the limiter.
293func (lim *Limiter) SetBurstAt(now time.Time, newBurst int) {294lim.mu.Lock()295defer lim.mu.Unlock()296
297now, _, tokens := lim.advance(now)298
299lim.last = now300lim.tokens = tokens301lim.burst = newBurst302}
303
304// reserveN is a helper method for AllowN, ReserveN, and WaitN.
305// maxFutureReserve specifies the maximum reservation wait duration allowed.
306// reserveN returns Reservation, not *Reservation, to avoid allocation in AllowN and WaitN.
307func (lim *Limiter) reserveN(now time.Time, n int, maxFutureReserve time.Duration) Reservation {308lim.mu.Lock()309defer lim.mu.Unlock()310
311if lim.limit == Inf {312return Reservation{313ok: true,314lim: lim,315tokens: n,316timeToAct: now,317}318} else if lim.limit == 0 {319var ok bool320if lim.burst >= n {321ok = true322lim.burst -= n323}324return Reservation{325ok: ok,326lim: lim,327tokens: lim.burst,328timeToAct: now,329}330}331
332now, last, tokens := lim.advance(now)333
334// Calculate the remaining number of tokens resulting from the request.335tokens -= float64(n)336
337// Calculate the wait duration338var waitDuration time.Duration339if tokens < 0 {340waitDuration = lim.limit.durationFromTokens(-tokens)341}342
343// Decide result344ok := n <= lim.burst && waitDuration <= maxFutureReserve345
346// Prepare reservation347r := Reservation{348ok: ok,349lim: lim,350limit: lim.limit,351}352if ok {353r.tokens = n354r.timeToAct = now.Add(waitDuration)355}356
357// Update state358if ok {359lim.last = now360lim.tokens = tokens361lim.lastEvent = r.timeToAct362} else {363lim.last = last364}365
366return r367}
368
369// advance calculates and returns an updated state for lim resulting from the passage of time.
370// lim is not changed.
371// advance requires that lim.mu is held.
372func (lim *Limiter) advance(now time.Time) (newNow time.Time, newLast time.Time, newTokens float64) {373last := lim.last374if now.Before(last) {375last = now376}377
378// Calculate the new number of tokens, due to time that passed.379elapsed := now.Sub(last)380delta := lim.limit.tokensFromDuration(elapsed)381tokens := lim.tokens + delta382if burst := float64(lim.burst); tokens > burst {383tokens = burst384}385return now, last, tokens386}
387
388// durationFromTokens is a unit conversion function from the number of tokens to the duration
389// of time it takes to accumulate them at a rate of limit tokens per second.
390func (limit Limit) durationFromTokens(tokens float64) time.Duration {391if limit <= 0 {392return InfDuration393}394seconds := tokens / float64(limit)395return time.Duration(float64(time.Second) * seconds)396}
397
398// tokensFromDuration is a unit conversion function from a time duration to the number of tokens
399// which could be accumulated during that duration at a rate of limit tokens per second.
400func (limit Limit) tokensFromDuration(d time.Duration) float64 {401if limit <= 0 {402return 0403}404return d.Seconds() * float64(limit)405}
406