39 lines
953 B
Go
39 lines
953 B
Go
package ratelimit
|
|
|
|
import (
|
|
"strings"
|
|
"time"
|
|
|
|
"git.sendico.io/tech/sxchnge/bff/pkg/merrors"
|
|
)
|
|
|
|
const (
|
|
MinWindow = time.Second
|
|
MaxWindow = 24 * time.Hour
|
|
MaxLimit = 10000
|
|
)
|
|
|
|
type WindowConfig struct {
|
|
Limit int `yaml:"limit"`
|
|
Window string `yaml:"window"`
|
|
}
|
|
|
|
type Window struct {
|
|
Limit int
|
|
Window time.Duration
|
|
}
|
|
|
|
func ResolveWindow(raw WindowConfig, field string) (Window, error) {
|
|
if raw.Limit < 1 || raw.Limit > MaxLimit {
|
|
return Window{}, merrors.InvalidArgument("rate limit must be between 1 and 10000", field+".limit")
|
|
}
|
|
window, err := time.ParseDuration(strings.TrimSpace(raw.Window))
|
|
if err != nil {
|
|
return Window{}, merrors.InvalidArgument("rate limit window must be a valid duration", field+".window")
|
|
}
|
|
if window < MinWindow || window > MaxWindow {
|
|
return Window{}, merrors.InvalidArgument("rate limit window must be between 1s and 24h", field+".window")
|
|
}
|
|
return Window{Limit: raw.Limit, Window: window}, nil
|
|
}
|