ratelimit

package
v2.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 6, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetMigrations

func GetMigrations(ctx context.Context, provider string) (*embed.FS, error)

GetMigrations returns the migrations for the specified database provider.

Types

type DatabaseProvider

type DatabaseProvider struct {
	// contains filtered or unexported fields
}

DatabaseProvider is a database-backed rate limit provider for persistent rate limiting

func NewDatabaseProvider

func NewDatabaseProvider(db bun.IDB) (*DatabaseProvider, error)

NewDatabaseProvider creates a new database rate limit provider

func NewDatabaseProviderWithConfig

func NewDatabaseProviderWithConfig(db bun.IDB, config DatabaseStorageConfig) (*DatabaseProvider, error)

NewDatabaseProviderWithConfig creates a new database rate limit provider with custom config

func (*DatabaseProvider) CheckAndIncrement

func (p *DatabaseProvider) CheckAndIncrement(ctx context.Context, key string, window time.Duration, maxRequests int) (bool, int, time.Time, error)

CheckAndIncrement checks if a request is allowed and increments the counter

func (*DatabaseProvider) Close

func (p *DatabaseProvider) Close() error

Close closes the provider (no-op since we don't own the database connection)

func (*DatabaseProvider) GetName

func (p *DatabaseProvider) GetName() string

GetName returns the provider name

type DatabaseStorageConfig

type DatabaseStorageConfig struct {
	// CleanupInterval specifies how often to remove expired entries from the database
	// Defaults to 1 minute if not specified
	CleanupInterval time.Duration `json:"cleanup_interval" toml:"cleanup_interval"`
}

DatabaseStorageConfig contains configuration options for database rate limit storage

type InMemoryProvider

type InMemoryProvider struct {
	// contains filtered or unexported fields
}

InMemoryProvider is a thread-safe in-memory rate limit provider

func NewInMemoryProvider

func NewInMemoryProvider() *InMemoryProvider

NewInMemoryProvider creates a new in-memory rate limit provider

func NewInMemoryProviderWithConfig

func NewInMemoryProviderWithConfig(config MemoryStorageConfig) *InMemoryProvider

NewInMemoryProviderWithConfig creates a new in-memory rate limit provider with custom config

func (*InMemoryProvider) CheckAndIncrement

func (p *InMemoryProvider) CheckAndIncrement(ctx context.Context, key string, window time.Duration, maxRequests int) (bool, int, time.Time, error)

CheckAndIncrement checks if a request is allowed and increments the counter

func (*InMemoryProvider) Close

func (p *InMemoryProvider) Close() error

Close closes the provider (no-op for in-memory)

func (*InMemoryProvider) GetName

func (p *InMemoryProvider) GetName() string

GetName returns the provider name

type MemoryStorageConfig

type MemoryStorageConfig struct {
	// CleanupInterval specifies how often to remove expired entries
	// Defaults to 1 minute if not specified
	CleanupInterval time.Duration `json:"cleanup_interval" toml:"cleanup_interval"`
}

MemoryStorageConfig contains configuration options for in-memory rate limit storage

type RateLimit

type RateLimit struct {
	bun.BaseModel `bun:"table:rate_limits"`

	Key       string    `json:"key" bun:"column:key,pk"`
	Count     int       `json:"count" bun:"column:count"`
	ExpiresAt time.Time `json:"expires_at" bun:"column:expires_at"`
}

RateLimit represents a rate limit entry in the database for Bun ORM

type RateLimitCheckRequest

type RateLimitCheckRequest struct {
	ClientIP   string
	Path       string
	HTTPMethod string
}

RateLimitCheckRequest contains the information needed to check rate limits

type RateLimitCheckResponse

type RateLimitCheckResponse struct {
	// Allowed indicates whether the request should be allowed
	Allowed bool
	// Limit is the maximum number of requests allowed
	Limit int
	// Window is the time window for the rate limit in seconds
	Window int
	// RetryAfter is the number of seconds to wait before retrying (only set if Allowed is false)
	RetryAfter int
}

RateLimitCheckResponse contains the result of a rate limit check

type RateLimitEntry

type RateLimitEntry struct {
	Count     int
	FirstReq  time.Time
	LastReset time.Time
}

RateLimitEntry tracks requests for a specific key

type RateLimitHookHandler

type RateLimitHookHandler struct {
	// contains filtered or unexported fields
}

func NewRateLimitHookHandler

func NewRateLimitHookHandler(
	config *models.Config,
	logger models.Logger,
	pluginConfig RateLimitPluginConfig,
	provider RateLimitProvider,
) *RateLimitHookHandler

func (*RateLimitHookHandler) Handle

type RateLimitPlugin

type RateLimitPlugin struct {
	// contains filtered or unexported fields
}

func New

func (*RateLimitPlugin) Close

func (p *RateLimitPlugin) Close() error

func (*RateLimitPlugin) Config

func (p *RateLimitPlugin) Config() any

func (*RateLimitPlugin) Hooks

func (p *RateLimitPlugin) Hooks() []models.Hook

func (*RateLimitPlugin) Init

func (p *RateLimitPlugin) Init(ctx *models.PluginContext) error

func (*RateLimitPlugin) Metadata

func (p *RateLimitPlugin) Metadata() models.PluginMetadata

func (*RateLimitPlugin) Migrations

func (p *RateLimitPlugin) Migrations(ctx context.Context, dbProvider string) (*embed.FS, error)

func (*RateLimitPlugin) OnConfigUpdate

func (p *RateLimitPlugin) OnConfigUpdate(config *models.Config) error

type RateLimitPluginConfig

type RateLimitPluginConfig struct {
	Enabled bool `json:"enabled" toml:"enabled"`

	// Time window for the rate limit
	Window time.Duration `json:"window" toml:"window"`

	// Max number of requests allowed within the window
	Max int `json:"max" toml:"max"`

	// Optional override for the storage namespace prefix
	// Other plugins may also use their own prefixes when accessing secondary storage
	Prefix string `json:"prefix,omitempty" toml:"prefix"`

	// Custom rules for specific paths or methods
	CustomRules map[string]RateLimitRule `json:"custom_rules" toml:"custom_rules"`

	// Provider specifies which rate limit backend to use
	// Options: "memory", "redis", "database"
	// If not specified or if the selected provider is unavailable, defaults to "memory"
	//
	// Note: rate limit plugin can use either its own provider (if specified) or the
	// secondary-storage plugin if available. If secondary-storage plugin is configured
	// and enabled, that takes precedence over the provider selection here.
	Provider RateLimitProviderType `json:"provider" toml:"provider"`

	// Memory contains configuration options for in-memory storage
	Memory *MemoryStorageConfig `json:"memory,omitempty" toml:"memory"`

	// Database contains configuration options for database storage
	Database *DatabaseStorageConfig `json:"database,omitempty" toml:"database"`
}

func (*RateLimitPluginConfig) ApplyDefaults

func (config *RateLimitPluginConfig) ApplyDefaults()

type RateLimitProvider

type RateLimitProvider interface {
	// GetName returns the name of the provider
	GetName() string
	// CheckAndIncrement checks if a request is allowed and increments the counter if so
	// key is the fully-qualified key (with prefix already included)
	// window is the time window for expiration
	// maxRequests is the maximum number of requests allowed in the window
	// Returns: (allowed bool, currentCount int, resetTime time.Time, error)
	CheckAndIncrement(ctx context.Context, key string, window time.Duration, maxRequests int) (bool, int, time.Time, error)
	// Close closes any resources held by the provider
	Close() error
}

RateLimitProvider defines the interface for rate limit storage backends Implementations can use in-memory storage, Redis, database, or any other backend

type RateLimitProviderType

type RateLimitProviderType string
const (
	RateLimitProviderInMemory RateLimitProviderType = "memory"
	RateLimitProviderRedis    RateLimitProviderType = "redis"
	RateLimitProviderDatabase RateLimitProviderType = "database"
)

func (RateLimitProviderType) String

func (r RateLimitProviderType) String() string

type RateLimitRepository

type RateLimitRepository interface {
	// GetByKey retrieves a rate limit record by its key
	GetByKey(ctx context.Context, key string) (*RateLimit, error)

	// UpdateOrCreate updates count for an existing record, or creates a new one
	UpdateOrCreate(ctx context.Context, key string, window time.Duration) (*RateLimit, error)

	// CleanupExpired removes expired rate limit records
	CleanupExpired(ctx context.Context, now time.Time) error
}

RateLimitRepository defines the interface for rate limit record persistence

func NewRateLimitRepository

func NewRateLimitRepository(db bun.IDB) RateLimitRepository

NewRateLimitRepository creates a new RateLimitRepository with Bun backend

type RateLimitRule

type RateLimitRule struct {
	// Disable rate limiting for this endpoint entirely
	Disabled bool `json:"disabled" toml:"disabled"`

	// Time window for the rate limit
	Window time.Duration `json:"window" toml:"window"`

	// Max number of requests allowed within the window
	Max int `json:"max" toml:"max"`

	// Optional override for the storage namespace
	Prefix string `json:"prefix,omitempty" toml:"prefix"`
}

type RateLimitStore

type RateLimitStore struct {
	// contains filtered or unexported fields
}

RateLimitStore holds in-memory rate limit data

type SecondaryStorageProvider

type SecondaryStorageProvider struct {
	// contains filtered or unexported fields
}

SecondaryStorageProvider wraps a SecondaryStorage backend for rate limiting This allows rate limits to use distributed storage (Redis, database) instead of in-memory

func NewSecondaryStorageProvider

func NewSecondaryStorageProvider(name string, storage models.SecondaryStorage) *SecondaryStorageProvider

NewSecondaryStorageProvider creates a new provider wrapping a SecondaryStorage backend

func (*SecondaryStorageProvider) CheckAndIncrement

func (p *SecondaryStorageProvider) CheckAndIncrement(ctx context.Context, key string, window time.Duration, maxRequests int) (bool, int, time.Time, error)

CheckAndIncrement checks if a request is allowed and increments the counter

func (*SecondaryStorageProvider) Close

func (p *SecondaryStorageProvider) Close() error

Close closes the provider (no-op since we don't own the storage)

func (*SecondaryStorageProvider) GetName

func (p *SecondaryStorageProvider) GetName() string

GetName returns the provider name

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL