From a01b2534734013211ec27cb1f1c1991b9adb0662 Mon Sep 17 00:00:00 2001 From: Sudo-Ivan Date: Tue, 30 Dec 2025 12:35:15 -0600 Subject: [PATCH] refactor: update Limiter implementation to use capacity instead of interval and adjust related tests --- pkg/rate/rate.go | 20 +++++++++++++------- pkg/rate/rate_test.go | 4 ++-- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/pkg/rate/rate.go b/pkg/rate/rate.go index e6d5244..fec28eb 100644 --- a/pkg/rate/rate.go +++ b/pkg/rate/rate.go @@ -28,18 +28,18 @@ const ( type Limiter struct { rate float64 - interval time.Duration + capacity float64 lastUpdate time.Time allowance float64 mutex sync.Mutex } -func NewLimiter(rate float64, interval time.Duration) *Limiter { +func NewLimiter(rate float64, capacity float64) *Limiter { return &Limiter{ rate: rate, - interval: interval, + capacity: capacity, lastUpdate: time.Now(), - allowance: rate, + allowance: capacity, } } @@ -52,8 +52,8 @@ func (l *Limiter) Allow() bool { l.lastUpdate = now l.allowance += elapsed.Seconds() * l.rate - if l.allowance > l.rate { - l.allowance = l.rate + if l.allowance > l.capacity { + l.allowance = l.capacity } if l.allowance < AllowanceMinThreshold { @@ -175,7 +175,13 @@ func (ic *IngressControl) ProcessAnnounce(announceHash string, announceData []by } 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 if burstFreq > maxFreq { diff --git a/pkg/rate/rate_test.go b/pkg/rate/rate_test.go index fafdcfe..8ca6f86 100644 --- a/pkg/rate/rate_test.go +++ b/pkg/rate/rate_test.go @@ -6,14 +6,14 @@ import ( ) func TestNewLimiter(t *testing.T) { - limiter := NewLimiter(10.0, time.Second) + limiter := NewLimiter(10.0, 1.0) if limiter == nil { t.Fatal("NewLimiter() returned nil") } } func TestLimiter_Allow(t *testing.T) { - limiter := NewLimiter(10.0, time.Second) + limiter := NewLimiter(10.0, 1.0) if !limiter.Allow() { t.Error("Allow() should return true initially")