grain/config/setSizeLimit.go

72 lines
1.4 KiB
Go
Raw Normal View History

2024-07-30 15:27:38 +00:00
package config
2024-07-26 20:46:01 +00:00
import (
"sync"
2024-07-31 15:56:55 +00:00
config "grain/config/types"
2024-07-26 20:46:01 +00:00
)
type SizeLimiter struct {
globalMaxSize int
kindSizeLimits map[int]int
mu sync.RWMutex
}
2024-09-05 15:09:03 +00:00
func SetSizeLimit(cfg *config.ServerConfig) {
2024-07-30 15:51:05 +00:00
sizeLimiter := NewSizeLimiter(cfg.RateLimit.MaxEventSize)
for _, kindSizeLimit := range cfg.RateLimit.KindSizeLimits {
sizeLimiter.AddKindSizeLimit(kindSizeLimit.Kind, kindSizeLimit.MaxSize)
}
2024-09-05 15:09:03 +00:00
SizeLimit(sizeLimiter)
2024-07-30 15:51:05 +00:00
}
2024-07-26 20:46:01 +00:00
func NewSizeLimiter(globalMaxSize int) *SizeLimiter {
return &SizeLimiter{
globalMaxSize: globalMaxSize,
kindSizeLimits: make(map[int]int),
}
}
var sizeLimiterInstance *SizeLimiter
var sizeOnce sync.Once
func GetSizeLimiter() *SizeLimiter {
return sizeLimiterInstance
}
2024-09-05 15:09:03 +00:00
func SizeLimit(sl *SizeLimiter) {
2024-07-26 20:46:01 +00:00
sizeOnce.Do(func() {
sizeLimiterInstance = sl
})
}
func (sl *SizeLimiter) SetGlobalMaxSize(maxSize int) {
sl.mu.Lock()
defer sl.mu.Unlock()
sl.globalMaxSize = maxSize
}
func (sl *SizeLimiter) AddKindSizeLimit(kind int, maxSize int) {
sl.mu.Lock()
defer sl.mu.Unlock()
sl.kindSizeLimits[kind] = maxSize
}
func (sl *SizeLimiter) AllowSize(kind int, size int) (bool, string) {
sl.mu.RLock()
defer sl.mu.RUnlock()
if size > sl.globalMaxSize {
return false, "Global event size limit exceeded"
}
if maxSize, exists := sl.kindSizeLimits[kind]; exists {
if size > maxSize {
return false, "Event size limit exceeded for kind"
}
}
return true, ""
}