Documentation
¶
Overview ¶
Package capacitor provides rate limiting backed by Valkey (Redis-compatible). All algorithm implementations are in this package.
Usage:
lim := capacitor.NewLeakyBucket(client, capacitor.NewLeakyBucketDefaultConfig())
mw := capacitor.NewMiddleware(lim)
http.Handle("/", mw(myHandler))
Index ¶
- Constants
- Variables
- func KeyFromRemoteIP(r *http.Request) string
- func NewMiddleware(limiter Capacitor, opts ...MiddlewareOption) func(http.Handler) http.Handler
- type Capacitor
- func NewFixedWindow(client valkey.Client, cfg FixedWindowConfig, opts ...Option) Capacitor
- func NewLeakyBucket(client valkey.Client, cfg LeakyBucketConfig, opts ...Option) Capacitor
- func NewSlidingTimeLog(client valkey.Client, cfg SlidingTimeLogConfig, opts ...Option) Capacitor
- func NewSlidingWindowCounter(client valkey.Client, cfg SlidingWindowCounterConfig, opts ...Option) Capacitor
- func NewTokenBucket(client valkey.Client, cfg TokenBucketConfig, opts ...Option) Capacitor
- type ClassifyFunc
- type FallbackStrategy
- type FixedWindowConfig
- type KeyFunc
- type LeakyBucketConfig
- type MetricsCollector
- type MiddlewareOption
- type Option
- type Options
- type ProfileConfig
- type Result
- type SlidingTimeLogConfig
- type SlidingWindowCounterConfig
- type TokenBucketConfig
Constants ¶
const ( FallbackFailOpen = ratelimit.FallbackFailOpen FallbackFailClosed = ratelimit.FallbackFailClosed )
Re-exported constants.
Variables ¶
var ( ErrEmptyUID = ratelimit.ErrEmptyUID ErrEvalResponse = ratelimit.ErrEvalResponse )
Re-exported errors.
var ( DefaultOptions = ratelimit.DefaultOptions WithLogger = ratelimit.WithLogger WithFallback = ratelimit.WithFallback )
Re-exported option constructors.
Functions ¶
func KeyFromRemoteIP ¶
KeyFromRemoteIP extracts the IP from RemoteAddr, stripping the port.
func NewMiddleware ¶
NewMiddleware returns standard net/http middleware that rate-limits requests using the provided Capacitor.
Types ¶
type Capacitor ¶
type Capacitor interface {
// Attempt checks whether the request identified by uid is allowed.
// On Valkey errors it returns a fallback result and the underlying error.
Attempt(ctx context.Context, uid string) (Result, error)
// HealthCheck verifies connectivity to the backing store.
HealthCheck(ctx context.Context) error
// Close releases resources held by the Capacitor.
Close()
}
Capacitor checks whether a request is allowed under a rate-limiting policy. Implementations must be safe for concurrent use.
func NewFixedWindow ¶ added in v0.4.0
func NewFixedWindow(client valkey.Client, cfg FixedWindowConfig, opts ...Option) Capacitor
NewFixedWindow creates a fixed-window Capacitor backed by the given Valkey client.
func NewLeakyBucket ¶ added in v0.4.0
func NewLeakyBucket(client valkey.Client, cfg LeakyBucketConfig, opts ...Option) Capacitor
NewLeakyBucket creates a leaky-bucket Capacitor backed by the given Valkey client.
func NewSlidingTimeLog ¶ added in v0.4.0
func NewSlidingTimeLog(client valkey.Client, cfg SlidingTimeLogConfig, opts ...Option) Capacitor
NewSlidingTimeLog creates a sliding-window log Capacitor backed by the given Valkey client.
func NewSlidingWindowCounter ¶ added in v0.4.0
func NewSlidingWindowCounter(client valkey.Client, cfg SlidingWindowCounterConfig, opts ...Option) Capacitor
NewSlidingWindowCounter creates a sliding-window counter Capacitor backed by the given Valkey client.
func NewTokenBucket ¶ added in v0.4.0
func NewTokenBucket(client valkey.Client, cfg TokenBucketConfig, opts ...Option) Capacitor
NewTokenBucket creates a token-bucket Capacitor backed by the given Valkey client.
type ClassifyFunc ¶ added in v0.2.0
ClassifyFunc determines the rate-limit profile name for a request. An empty return value uses the default limiter.
type FallbackStrategy ¶
type FallbackStrategy = ratelimit.FallbackStrategy
Re-exported types from internal/ratelimit.
type FixedWindowConfig ¶ added in v0.4.0
type FixedWindowConfig struct {
Limit int64 // maximum requests per window
Window time.Duration // window duration
KeyPrefix string // Valkey key prefix
Timeout time.Duration // per-operation Valkey timeout
}
FixedWindowConfig defines the parameters for a fixed-window rate limiter.
func NewFixedWindowDefaultConfig ¶ added in v0.4.0
func NewFixedWindowDefaultConfig() FixedWindowConfig
NewFixedWindowDefaultConfig returns a FixedWindowConfig with sensible defaults.
type KeyFunc ¶
KeyFunc extracts the rate-limit key from an incoming request.
func KeyFromHeader ¶
KeyFromHeader returns a KeyFunc that reads the given header.
type LeakyBucketConfig ¶ added in v0.4.0
type LeakyBucketConfig struct {
Capacity int64 // maximum number of requests the bucket can hold
LeakRate float64 // requests drained per second
KeyPrefix string // Valkey key prefix for bucket storage
Timeout time.Duration // per-operation Valkey timeout
}
LeakyBucketConfig defines the parameters for a leaky-bucket rate limiter.
func NewLeakyBucketDefaultConfig ¶ added in v0.4.0
func NewLeakyBucketDefaultConfig() LeakyBucketConfig
NewLeakyBucketDefaultConfig returns a LeakyBucketConfig with sensible defaults.
type MetricsCollector ¶
type MetricsCollector interface {
RecordAttempt(key, profile string)
RecordDenied(key, profile string)
RecordFallback(key, profile string)
RecordLatency(d time.Duration, profile string)
}
MetricsCollector receives rate-limiter telemetry. Profile is the name from ProfileConfig; empty string for the default limiter.
type MiddlewareOption ¶
type MiddlewareOption func(*middleware)
MiddlewareOption configures the HTTP middleware.
func WithClassifier ¶ added in v0.2.0
func WithClassifier(fn ClassifyFunc) MiddlewareOption
WithClassifier sets the function used to route a request to a named rate-limit profile. See WithProfiles.
func WithDenyHandler ¶
func WithDenyHandler(h http.Handler) MiddlewareOption
WithDenyHandler replaces the default 429 response handler.
func WithKeyFunc ¶
func WithKeyFunc(fn KeyFunc) MiddlewareOption
WithKeyFunc sets the function used to derive the rate-limit key. Defaults to KeyFromRemoteIP.
func WithMetrics ¶
func WithMetrics(mc MetricsCollector) MiddlewareOption
WithMetrics enables telemetry recording via the given collector.
func WithProfiles ¶ added in v0.2.0
func WithProfiles(profiles ProfileConfig) MiddlewareOption
WithProfiles configures per-profile limiters. Combine with WithClassifier to route requests to named profiles. Unknown or empty profile names fall back to the default limiter.
type ProfileConfig ¶ added in v0.2.0
ProfileConfig maps profile names to Capacitor instances. Use it with WithProfiles and WithClassifier to route requests to different rate-limiting policies.
type Result ¶
Result holds the outcome of a rate-limit check.
func FallbackResult ¶ added in v0.2.0
func FallbackResult(strategy FallbackStrategy, limit int64, retryAfterSecs float64) Result
FallbackResult returns a degraded Result based on the given strategy. Algorithm implementations call this when Valkey is unreachable.
type SlidingTimeLogConfig ¶ added in v0.4.0
type SlidingTimeLogConfig struct {
Limit int64 // maximum requests per window
Window time.Duration // window duration
KeyPrefix string // Valkey key prefix
Timeout time.Duration // per-operation Valkey timeout
}
SlidingTimeLogConfig defines the parameters for a sliding-window log rate limiter.
func NewSlidingTimeLogDefaultConfig ¶ added in v0.4.0
func NewSlidingTimeLogDefaultConfig() SlidingTimeLogConfig
NewSlidingTimeLogDefaultConfig returns a SlidingTimeLogConfig with sensible defaults.
type SlidingWindowCounterConfig ¶ added in v0.4.0
type SlidingWindowCounterConfig struct {
Limit int64 // maximum requests per window
Window time.Duration // window duration
KeyPrefix string // Valkey key prefix
Timeout time.Duration // per-operation Valkey timeout
}
SlidingWindowCounterConfig defines the parameters for a sliding-window counter rate limiter.
func NewSlidingWindowCounterDefaultConfig ¶ added in v0.4.0
func NewSlidingWindowCounterDefaultConfig() SlidingWindowCounterConfig
NewSlidingWindowCounterDefaultConfig returns a SlidingWindowCounterConfig with sensible defaults.
type TokenBucketConfig ¶ added in v0.4.0
type TokenBucketConfig struct {
Capacity int64 // maximum number of tokens the bucket can hold
RefillRate float64 // tokens refilled per second
KeyPrefix string // Valkey key prefix
Timeout time.Duration // per-operation Valkey timeout
}
TokenBucketConfig defines the parameters for a token-bucket rate limiter.
func NewTokenBucketDefaultConfig ¶ added in v0.4.0
func NewTokenBucketDefaultConfig() TokenBucketConfig
NewTokenBucketDefaultConfig returns a TokenBucketConfig with sensible defaults.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
ratelimit
Package ratelimit provides shared infrastructure for Capacitor algorithm implementations.
|
Package ratelimit provides shared infrastructure for Capacitor algorithm implementations. |
|
scripts
Package scripts embeds all Lua rate-limiting scripts and exposes them as ready-to-use *valkey.Lua values.
|
Package scripts embeds all Lua rate-limiting scripts and exposes them as ready-to-use *valkey.Lua values. |