refactor: update Limiter implementation to use capacity instead of interval and adjust related tests

This commit is contained in:
2025-12-30 12:35:15 -06:00
parent 53b981cb21
commit a01b253473
2 changed files with 15 additions and 9 deletions

View File

@@ -28,18 +28,18 @@ const (
type Limiter struct { type Limiter struct {
rate float64 rate float64
interval time.Duration capacity float64
lastUpdate time.Time lastUpdate time.Time
allowance float64 allowance float64
mutex sync.Mutex mutex sync.Mutex
} }
func NewLimiter(rate float64, interval time.Duration) *Limiter { func NewLimiter(rate float64, capacity float64) *Limiter {
return &Limiter{ return &Limiter{
rate: rate, rate: rate,
interval: interval, capacity: capacity,
lastUpdate: time.Now(), lastUpdate: time.Now(),
allowance: rate, allowance: capacity,
} }
} }
@@ -52,8 +52,8 @@ func (l *Limiter) Allow() bool {
l.lastUpdate = now l.lastUpdate = now
l.allowance += elapsed.Seconds() * l.rate l.allowance += elapsed.Seconds() * l.rate
if l.allowance > l.rate { if l.allowance > l.capacity {
l.allowance = l.rate l.allowance = l.capacity
} }
if l.allowance < AllowanceMinThreshold { if l.allowance < AllowanceMinThreshold {
@@ -175,7 +175,13 @@ func (ic *IngressControl) ProcessAnnounce(announceHash string, announceData []by
} }
ic.announceCount++ ic.announceCount++
burstFreq := float64(ic.announceCount) / elapsed.Seconds()
// Avoid division by zero and handle very small elapsed times
seconds := elapsed.Seconds()
if seconds < 0.01 {
seconds = 0.01
}
burstFreq := float64(ic.announceCount) / seconds
// Hold announce if burst frequency exceeded // Hold announce if burst frequency exceeded
if burstFreq > maxFreq { if burstFreq > maxFreq {

View File

@@ -6,14 +6,14 @@ import (
) )
func TestNewLimiter(t *testing.T) { func TestNewLimiter(t *testing.T) {
limiter := NewLimiter(10.0, time.Second) limiter := NewLimiter(10.0, 1.0)
if limiter == nil { if limiter == nil {
t.Fatal("NewLimiter() returned nil") t.Fatal("NewLimiter() returned nil")
} }
} }
func TestLimiter_Allow(t *testing.T) { func TestLimiter_Allow(t *testing.T) {
limiter := NewLimiter(10.0, time.Second) limiter := NewLimiter(10.0, 1.0)
if !limiter.Allow() { if !limiter.Allow() {
t.Error("Allow() should return true initially") t.Error("Allow() should return true initially")