limiter

package
v0.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 18, 2021 License: MIT Imports: 3 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Limiter

type Limiter interface {
	Request(n uint64) bool
	Commit(n uint64)
	Withdraw(n uint64)
}

Limiter is the interface for RunningTotalLimiter. It's there just so we can have a NopeLimiter which does nothing.

func NewRunningTotalLimiter

func NewRunningTotalLimiter(period time.Duration, limit uint64) Limiter

NewRunningTotalLimiter creates a Limiter which caps the running total in the 'period' to 'limit'.

type NopeLimiter

type NopeLimiter struct{}

NopeLimiter does no limit.

func (NopeLimiter) Commit

func (l NopeLimiter) Commit(n uint64)

Commit does nothing.

func (NopeLimiter) Request

func (l NopeLimiter) Request(n uint64) bool

Request always return true.

func (NopeLimiter) Withdraw

func (l NopeLimiter) Withdraw(n uint64)

Withdraw does nothing.

type RunningTotalLimiter

type RunningTotalLimiter struct {
	// contains filtered or unexported fields
}

RunningTotalLimiter is a variant of sliding log rate limiter. It keeps all requests with timestamps. What makes it different from a typical rate limiter is that there are two phases - The caller first requests for 'n' tokens, does some work, then either commits the tokens, or withdraws them so they can be requested by others. So at anytime, the running total represents the tokens committed in that period of time, plus those requested but not committed yet.

If we are going to have millions of requests, we should switch to a sliding window implementation like https://github.com/RussellLuo/slidingwindow, which saves space with the cost of some inaccuracy.

func (*RunningTotalLimiter) Commit

func (rl *RunningTotalLimiter) Commit(n uint64)

Commit makes the requested n tokens permanent for the configured period. It's the caller's responsibility to always request the tokens before committing them.

func (*RunningTotalLimiter) Request

func (rl *RunningTotalLimiter) Request(n uint64) bool

Request reqeusts for 'n' tokens and returns if granted or not. If granted, the tokens must be either withdrawed or committed some time later, or we'll run out of tokens.

func (*RunningTotalLimiter) Withdraw

func (rl *RunningTotalLimiter) Withdraw(n uint64)

Withdraw withdraws 'n' grant previously requested.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL