ratelimit

package
v1.58.0 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2024 License: GPL-3.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SecondTimeWindow = "second"
	HourTimeWindow   = "hour"
	MonthTimeWindow  = "month"

	HeaderRateLimitLimit     = "ratelimit-limit"     // the rate limit ceiling that is applicable for the current request
	HeaderRateLimitRemaining = "ratelimit-remaining" // the number of requests left for the current rate-limit window
	HeaderRateLimitReset     = "ratelimit-reset"     // the number of seconds until the quota resets
	HeaderRateLimitWindow    = "ratelimit-window"    // what window the ratelimit represents
	HeaderRetryAfter         = "retry-after"         // the number of seconds until the quota resets, same as HeaderRateLimitReset, RFC 7231, 7.1.3

	HeaderRateLimitRemainingSecond = "x-ratelimit-remaining-second" // the number of requests left for the current rate-limit window
	HeaderRateLimitRemainingMinute = "x-ratelimit-remaining-minute" // the number of requests left for the current rate-limit window
	HeaderRateLimitRemainingHour   = "x-ratelimit-remaining-hour"   // the number of requests left for the current rate-limit window
	HeaderRateLimitRemainingDay    = "x-ratelimit-remaining-day"    // the number of requests left for the current rate-limit window
	HeaderRateLimitRemainingMonth  = "x-ratelimit-remaining-month"  // the number of requests left for the current rate-limit window

	HeaderRateLimitLimitSecond = "x-ratelimit-limit-second" // the rate limit ceiling that is applicable for the current user
	HeaderRateLimitLimitMinute = "x-ratelimit-limit-minute" // the rate limit ceiling that is applicable for the current user
	HeaderRateLimitLimitHour   = "x-ratelimit-limit-hour"   // the rate limit ceiling that is applicable for the current user
	HeaderRateLimitLimitDay    = "x-ratelimit-limit-day"    // the rate limit ceiling that is applicable for the current user
	HeaderRateLimitLimitMonth  = "x-ratelimit-limit-month"  // the rate limit ceiling that is applicable for the current user

	DefaultRateLimitSecond = 2   // RateLimit per second if no ratelimits are set in database
	DefaultRateLimitHour   = 500 // RateLimit per second if no ratelimits are set in database
	DefaultRateLimitMonth  = 0   // RateLimit per second if no ratelimits are set in database

	FallbackRateLimitSecond = 20 // RateLimit per second for when redis is offline
	FallbackRateLimitBurst  = 20 // RateLimit burst for when redis is offline

)

Variables

View Source
var DefaultRequestFilter = func(req *http.Request) bool {
	if req.URL == nil || !strings.HasPrefix(req.URL.Path, "/api") || strings.HasPrefix(req.URL.Path, "/api/i/") || strings.HasPrefix(req.URL.Path, "/api/v1/docs/") || strings.HasPrefix(req.URL.Path, "/api/v2/docs/") {
		return false
	}
	return true
}

Functions

func DBInvalidateApiKeys

func DBInvalidateApiKeys() (sql.Result, error)

DBInvalidateApiKeys invalidates api_keys that are not associated with a user. This func is only needed until api-key-mgmt is fully implemented - where users.apikey column is not used anymore.

func DBUpdate

func DBUpdate(redisClient *redis.Client)

func DBUpdateApiKeys

func DBUpdateApiKeys() (sql.Result, error)

DBUpdateApiKeys updates the api_keys table with the api_keys from the users table. This func is only needed until api-key-mgmt is fully implemented - where users.apikey column is not used anymore.

func DBUpdateApiRatelimits

func DBUpdateApiRatelimits() (sql.Result, error)

func DBUpdater

func DBUpdater()

func GetMaxBadRquestWeight

func GetMaxBadRquestWeight() int64

func GetRequestFilter

func GetRequestFilter() func(req *http.Request) bool

func HttpMiddleware

func HttpMiddleware(next http.Handler) http.Handler

HttpMiddleware returns an http.Handler that can be used as middleware to RateLimit requests. If redis is offline, it will use a fallback rate limiter.

func Init

func Init()

Init initializes the RateLimiting middleware, the rateLimiting middleware will not work without calling Init first. The second parameter is a function the will get called on every request, it will only apply ratelimiting to requests when this func returns true.

func SetMaxBadRquestWeight

func SetMaxBadRquestWeight(weight int64)

func SetRequestFilter

func SetRequestFilter(filter func(req *http.Request) bool)

Types

type ApiProduct

type ApiProduct struct {
	Name          string    `db:"name"`
	Bucket        string    `db:"bucket"`
	StripePriceID string    `db:"stripe_price_id"`
	Second        int64     `db:"second"`
	Hour          int64     `db:"hour"`
	Month         int64     `db:"month"`
	ValidFrom     time.Time `db:"valid_from"`
}

func DBGetCurrentApiProducts

func DBGetCurrentApiProducts() ([]*ApiProduct, error)

type DbEntry

type DbEntry struct {
	Date     time.Time
	UserId   int64
	ApiKey   string
	Endpoint string
	Count    int64
	Bucket   string
}

type FallbackRateLimiter

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

func NewFallbackRateLimiter

func NewFallbackRateLimiter() *FallbackRateLimiter

func (*FallbackRateLimiter) Handle

func (rl *FallbackRateLimiter) Handle(w http.ResponseWriter, r *http.Request, next func(writer http.ResponseWriter, request *http.Request))

type FallbackRateLimiterClient

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

type RateLimit

type RateLimit struct {
	Second int64
	Hour   int64
	Month  int64
}

func DBGetUserApiRateLimit

func DBGetUserApiRateLimit(userId int64) (*RateLimit, error)

type RateLimitResult

type RateLimitResult struct {
	BlockRequest  bool
	Time          time.Time
	Weight        int64
	Route         string
	IP            string
	Key           string
	IsValidKey    bool
	UserId        int64
	RedisKeys     []RedisKey
	RedisStatsKey string
	RateLimit     *RateLimit

	Limit       int64
	LimitSecond int64
	LimitMinute int64
	LimitHour   int64
	LimitDay    int64
	LimitMonth  int64

	Remaining       int64
	RemainingSecond int64
	RemainingMinute int64
	RemainingHour   int64
	RemainingDay    int64
	RemainingMonth  int64

	Reset  int64
	Bucket string
	Window TimeWindow
}

type RedisKey

type RedisKey struct {
	Key      string
	ExpireAt time.Time
}

type TimeWindow

type TimeWindow string

Jump to

Keyboard shortcuts

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