Documentation
¶
Overview ¶
Package ratelimit provides token-bucket rate limiting for the switchAILocal proxy. It supports a pre-auth global system-wide limiter and post-auth per-principal limiters.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CheckPerKey ¶ added in v0.6.6
CheckPerKey enforces the post-auth per-key rate limit using the Limiter attached to the request context by GlobalMiddleware. It returns true when the request is allowed or when no enabled limiter is attached.
func PrincipalFromContext ¶ added in v0.6.6
PrincipalFromContext returns the authenticated principal identifier set on the request context, or an empty string if none was set.
func SetPrincipal ¶ added in v0.6.6
SetPrincipal binds an authenticated principal identifier to the request context for post-auth per-key rate limiting. Empty principals are ignored.
Types ¶
type Limiter ¶
type Limiter struct {
// contains filtered or unexported fields
}
Limiter manages global and per-principal rate limiting using token buckets. The global limiter runs pre-auth to protect the system from total overload. Per-key limiters run post-auth and key buckets only by the authenticated principal.
func New ¶
func New(cfg config.RateLimiterConfig) *Limiter
New creates a new rate limiter from the given configuration. When enabled, the background stale-key eviction goroutine starts lazily on the first per-key bucket insertion. Call Close to stop it if started.
func (*Limiter) BucketCount ¶ added in v0.6.6
BucketCount returns the number of currently tracked per-principal buckets.
func (*Limiter) BucketKeys ¶ added in v0.6.6
BucketKeys returns a snapshot of the currently tracked per-principal bucket keys.
func (*Limiter) CheckPerKey ¶ added in v0.6.6
CheckPerKey enforces the post-auth per-key rate limit for the principal stored on the Gin context. Requests without an authenticated principal are allowed without creating any bucket. Rate-limited requests receive HTTP 429 with Retry-After: 1, abort the context, and return false.
func (*Limiter) Close ¶ added in v0.6.6
func (l *Limiter) Close()
Close stops the background eviction goroutine if running and waits for it to exit. Safe to call multiple times or on a nil receiver.
func (*Limiter) GlobalMiddleware ¶ added in v0.6.6
func (l *Limiter) GlobalMiddleware() gin.HandlerFunc
GlobalMiddleware returns a Gin middleware that enforces the pre-auth global rate limit and binds this Limiter to the request context for post-auth CheckPerKey enforcement. Rate-limited requests receive HTTP 429 with Retry-After: 1.