Skip to content

Latest commit

 

History

History
230 lines (129 loc) · 5.75 KB

ratelimit.md

File metadata and controls

230 lines (129 loc) · 5.75 KB

ratelimit

import "github.com/andy2046/gopie/pkg/ratelimit"

Package ratelimit implements a rate limiter.

ratelimit.go sliding_window.go

const NotFound = -1

NotFound will be returned if it fails to get value.

type Limit float64

Limit defines the maximum number of requests per second.

func Every(interval time.Duration) Limit

Every converts a time interval between requests to a Limit.

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

Limiter implements a token bucket limiter at rate r tokens per second with burst size of b tokens.

func New(r Limit, b int) *Limiter

New returns a new Limiter at rate r tokens per second with burst of b tokens.

func (*Limiter) Allow

func (l *Limiter) Allow() bool

Allow is the shortcut for AllowN(time.Now(), 1).

func (*Limiter) AllowN

func (l *Limiter) AllowN(now time.Time, n int) bool

AllowN checks whether n requests may happen at time now.

func (*Limiter) Burst

func (l *Limiter) Burst() int

Burst returns the Limiter's burst size.

func (*Limiter) Limit

func (l *Limiter) Limit() Limit

Limit returns the Limiter's rate.

func (*Limiter) Wait

func (l *Limiter) Wait() (time.Duration, error)

Wait is the shortcut for WaitN(time.Now(), 1).

func (*Limiter) WaitN

func (l *Limiter) WaitN(now time.Time, n int) (time.Duration, error)

WaitN calculates the time duration to wait before n requests may happen at time now.

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

SlidingWindowLimiter implements a limiter with sliding window counter.

func NewSlidingWindowLimiter(r Limit, expire int, store Store) *SlidingWindowLimiter

NewSlidingWindowLimiter returns a new Limiter at rate r tokens per second, and the key expires in expire seconds.

func (*SlidingWindowLimiter) Allow

func (s *SlidingWindowLimiter) Allow(key string) bool

Allow is the shortcut for AllowN(time.Now(), key, 1).

func (*SlidingWindowLimiter) AllowN

func (s *SlidingWindowLimiter) AllowN(now time.Time, key string, n int) bool

AllowN checks whether n requests for key may happen at time now.

type Store interface {
    // Incr add `increment` to field `timestamp` in `key`
    Incr(key string, timestamp int64, increment int) error
    // SetIncr set `key` and add `increment` to field `timestamp` in `key`
    SetIncr(key string, timestamp int64, increment int) error
    // Expire set `key` to expire in `expire` seconds
    Expire(key string, expire int) error
    // Get returns value of field `timestamp` in `key`
    Get(key string, timestamp int64) int
    // Exists check if `key` exists
    Exists(key string) bool
}

Store represents a store for limiter state.

func NewRedisStore(clientOptions *redis.Options) (Store, error)

NewRedisStore returns a new Redis Store.


Generated by godoc2md