ratelimiter

package
v0.0.0-...-aefcfe0 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2022 License: GPL-3.0 Imports: 2 Imported by: 0

Documentation

Overview

Package ratelimiter implements rate limiting functionality.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Limit

type Limit struct {
	// MaxCount represents maximum number of allowed works
	MaxCount int `json:"m"`
	// IntervalStr represents time interval in string representation, for maximum allowed works to run
	IntervalStr string `json:"i"`
	// Interval represents time interval in for maximum allowed works to run
	Interval time.Duration `json:"-"`
	// LimitState represents current state
	LimitState `json:"-"`
}

Limit represents the limit with current state

func (*Limit) IsUnlimited

func (l *Limit) IsUnlimited() bool

IsUnlimited checks if the interval is unlimited

func (*Limit) Left

func (l *Limit) Left() time.Duration

Left returns how much time needed to wait until the limiter would allow to run work again

type LimitState

type LimitState struct {
	// CurCount represents counter of allowed works
	CurCount int `json:"c"`
	// LastTime represents time since the counter started to count
	LastTime time.Time `json:"l"`
}

LimitState represents the state of the limit

type RateLimiter

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

RateLimiter was inspired by https://github.com/golang/go/wiki/RateLimiting. However, the go example is not good for setting high qps limits because it will cause the ticker to fire too often. Also, the ticker will continue to fire when the system is idle. This new Ratelimiter achieves the same thing, but by using just counters with no tickers or channels.

func NewRateLimiter

func NewRateLimiter(limits ...*Limit) *RateLimiter

NewRateLimiter creates a new RateLimiter. MaxCount is the max burst allowed while interval specifies the duration for a burst. The effective rate limit is equal to MaxCount/interval. For example, if you want to a max QPS of 5000, and want to limit bursts to no more than 500, you'd specify a MaxCount of 500 and an interval of 100*time.Millilsecond.

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow() (bool, *Limit)

Allow returns true if a request is within the rate limit norms. Otherwise, it returns false.

func (*RateLimiter) GetState

func (rl *RateLimiter) GetState() []LimitState

GetState returns current state of the limits

Jump to

Keyboard shortcuts

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