Documentation
¶
Overview ¶
Package rate provides functionality for rate limiting to protect resources.
This package implements a token bucket rate limiter to protect resources from being overwhelmed by too many requests.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Execute ¶
func Execute[T any](ctx context.Context, rl *RateLimiter, operation string, fn func(ctx context.Context) (T, error)) (T, error)
Execute executes the given function with rate limiting If the rate limit is exceeded, it will return an error immediately Otherwise, it will execute the function
func ExecuteWithWait ¶
func ExecuteWithWait[T any](ctx context.Context, rl *RateLimiter, operation string, fn func(ctx context.Context) (T, error)) (T, error)
ExecuteWithWait executes the given function with rate limiting If the rate limit is exceeded, it will wait until a token is available and then execute the function
Types ¶
type Config ¶
type Config struct {
// Enabled determines if the rate limiter is enabled
Enabled bool
// RequestsPerSecond is the number of requests allowed per second
RequestsPerSecond int
// BurstSize is the maximum number of requests allowed in a burst
BurstSize int
}
Config contains rate limiter configuration parameters
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a default rate limiter configuration
func (Config) WithBurstSize ¶
WithBurstSize sets the maximum number of requests allowed in a burst
func (Config) WithEnabled ¶
WithEnabled sets whether the rate limiter is enabled
func (Config) WithRequestsPerSecond ¶
WithRequestsPerSecond sets the number of requests allowed per second
type Options ¶
type Options struct {
// Logger is used for logging rate limiter operations
Logger *logging.ContextLogger
// Tracer is used for tracing rate limiter operations
Tracer telemetry.Tracer
// Name is the name of the rate limiter
Name string
}
Options contains additional options for the rate limiter
func DefaultOptions ¶
func DefaultOptions() Options
DefaultOptions returns default options for rate limiter operations
func (Options) WithLogger ¶
func (o Options) WithLogger(logger *logging.ContextLogger) Options
WithLogger sets the logger for the rate limiter
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements a token bucket rate limiter to protect resources from being overwhelmed by too many requests.
func NewRateLimiter ¶
func NewRateLimiter(config Config, options Options) *RateLimiter
NewRateLimiter creates a new rate limiter
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow() bool
Allow checks if a request should be allowed based on the rate limit It returns true if the request is allowed, false otherwise
func (*RateLimiter) Reset ¶
func (rl *RateLimiter) Reset()
Reset resets the rate limiter to its initial state