Documentation ¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ErrRateLimitExceeded = errors.New("rate limit exceeded")
ErrRateLimitExceeded is returned when the rate limit has been exceeded.
Functions ¶
This section is empty.
Types ¶
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements a token bucket rate limiting algorithm. It is used to control how frequently events are allowed to happen. The RateLimiter allows a certain number of events to occur within a fixed time frame and refills the tokens at a constant interval.
func NewRateLimiter ¶
func NewRateLimiter(capacity int, refillTime time.Duration, redis *cache.Redis, keyPrefix string) *RateLimiter
NewRateLimiter initializes and returns a new RateLimiter with the specified capacity, refill time, and Redis client. The capacity parameter specifies the maximum number of tokens, refillTime specifies how often the tokens are replenished, and redis is the Redis client for caching. A debug message showing the capacity is printed during initialization.
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow() bool
Allow checks if at least one token is available. If a token is available, it consumes a token by decrementing the token count and returns true, indicating that the event is allowed to proceed. If no tokens are available, it returns false, indicating that the rate limit has been exceeded. Tokens are refilled based on the elapsed time since the last refill, up to the maximum capacity.
func (*RateLimiter) Capacity ¶ added in v0.9.6
func (rl *RateLimiter) Capacity() int
Capacity returns the maximum number of tokens that can accumulate in the bucket.
func (*RateLimiter) CheckLimit ¶
func (rl *RateLimiter) CheckLimit() error
CheckLimit checks if the rate limit has been reached. If the rate limit has been reached, it returns an error indicating that the rate limit has been exceeded. Otherwise, it returns nil.
func (*RateLimiter) CurrentTokens ¶ added in v0.9.6
func (rl *RateLimiter) CurrentTokens() int
CurrentTokens returns the current number of available tokens.
func (*RateLimiter) LastRefillTime ¶ added in v0.9.6
func (rl *RateLimiter) LastRefillTime() time.Time
LastRefillTime returns the timestamp of the last refill operation.
func (*RateLimiter) RefillTime ¶ added in v0.9.6
func (rl *RateLimiter) RefillTime() time.Duration
RefillTime returns the time interval at which tokens are refilled to capacity.
func (*RateLimiter) WaitForToken ¶
func (rl *RateLimiter) WaitForToken()
WaitForToken blocks the caller until a token becomes available. If no tokens are available upon invoking this method, it waits for a signal from a separate goroutine indicating that tokens have been refilled. This method ensures that events respect the rate limit by waiting for permission to proceed rather than immediately returning false.