Documentation ¶
Index ¶
- type Bucket
- type Limiter
- func (l *Limiter) AddBucket(key string, interval time.Duration, limit int64) *Bucket
- func (l *Limiter) OnError(c chan error)
- func (l *Limiter) Start() error
- func (l *Limiter) Stop()
- func (l *Limiter) Take(key string) (bool, error)
- func (l *Limiter) TakeOrAdd(key string, interval time.Duration, limit int64) bool
- type Options
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Bucket ¶
type Bucket struct { Interval time.Duration Limit int64 Key string // contains filtered or unexported fields }
Bucket holds rate-limiting capabilities for a given unique key, with defined limit in duration. For example, a bucket for the key "TEST" with a limit of 10 in a time interval of 1 minute will allow 10 operations (Takes) in 1 minute.
type Limiter ¶
type Limiter struct {
// contains filtered or unexported fields
}
Limiter manages buckets, and syncs their state to and from Redis. It is used as the main entry point to the rate-limiting functionality and encapsulates bucket management and bucket-capacity access. Buckets are managed in Redis as sorted sets with time-based scores (saved as UnixNano), and set members are expired based on their score, in relation to current time. This ensures a sliding-log behaviour where older entries are cleaned up based on the limit and time-interval of each bucket.
func (*Limiter) AddBucket ¶
AddBucket creates a new rate-limiting bucket on the provided key, with the given time interval and maximum limit. If a bucket already exists for the given key, it is returned. Otherwise a new bucket is created and returned.
func (*Limiter) OnError ¶
OnError accepts an error channel that can be used to listen to internal errors that occur during Redis operations and handle them
func (*Limiter) Start ¶
Start connects to Redis backend, and runs internal goroutine that executes async state syncing logic from and to Redis. It returns an error if Redis connection fails
func (*Limiter) Stop ¶
func (l *Limiter) Stop()
Stop tears down the Limiter's execution flow by stopping async state sync goroutine and disconnecting from Redis
func (*Limiter) Take ¶
Take will try to take a capacity of 1 from the bucket identified by key. If the bucket is found, Take will return a boolean flag indicating whether capacity if available (true) or not (false), along with nil error. If the bucket isn't found, Take will return false, along with an error indicating the bucket is missing.