This commit is contained in:
Sudo-Ivan
2025-01-01 00:40:25 -06:00
parent 785bc7d782
commit 30ea1dd0c7
15 changed files with 1016 additions and 847 deletions

44
pkg/rate/rate.go Normal file
View File

@@ -0,0 +1,44 @@
package rate
import (
"sync"
"time"
)
type Limiter struct {
rate float64
interval time.Duration
lastUpdate time.Time
allowance float64
mutex sync.Mutex
}
func NewLimiter(rate float64, interval time.Duration) *Limiter {
return &Limiter{
rate: rate,
interval: interval,
lastUpdate: time.Now(),
allowance: rate,
}
}
func (l *Limiter) Allow() bool {
l.mutex.Lock()
defer l.mutex.Unlock()
now := time.Now()
elapsed := now.Sub(l.lastUpdate)
l.lastUpdate = now
l.allowance += elapsed.Seconds() * l.rate
if l.allowance > l.rate {
l.allowance = l.rate
}
if l.allowance < 1.0 {
return false
}
l.allowance -= 1.0
return true
}