feat(limiter/traffic): add burst support, dropped-packet counters, and cache fixes
- Add NewLimiterWithBurst(rate, burst) for independent burst control - Extend parseLimit to accept optional 4th field as burst size - Add DroppedPacketCounter interface with DroppedPackets() for packet/udp conns - Export ErrRateLimited sentinel for rate-limit error checks - Fix IP-level cache expiration (NoExpiration → defaultExpiration) to prevent unbounded growth; reset TTL on access in In/Out - Short-circuit single-limiter path to avoid limiterGroup allocation - Add nil guard in cachedTrafficLimiter when both old and new values are nil - Remove unused ctx field from wrapper structs
This commit is contained in:
@@ -1,11 +1,12 @@
|
||||
package traffic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLimitGenerator_In(t *testing.T) {
|
||||
g := newLimitGenerator(100, 0)
|
||||
g := newLimitGenerator(100, 0, 0)
|
||||
lim := g.In()
|
||||
if lim == nil {
|
||||
t.Fatal("In() should not be nil for positive in")
|
||||
@@ -22,14 +23,14 @@ func TestLimitGenerator_In(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestLimitGenerator_In_Zero(t *testing.T) {
|
||||
g := newLimitGenerator(0, 200)
|
||||
g := newLimitGenerator(0, 200, 0)
|
||||
if lim := g.In(); lim != nil {
|
||||
t.Fatal("In() should be nil for zero in")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimitGenerator_Out(t *testing.T) {
|
||||
g := newLimitGenerator(0, 200)
|
||||
g := newLimitGenerator(0, 200, 0)
|
||||
lim := g.Out()
|
||||
if lim == nil {
|
||||
t.Fatal("Out() should not be nil for positive out")
|
||||
@@ -46,7 +47,7 @@ func TestLimitGenerator_Out(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestLimitGenerator_Out_Zero(t *testing.T) {
|
||||
g := newLimitGenerator(100, 0)
|
||||
g := newLimitGenerator(100, 0, 0)
|
||||
if lim := g.Out(); lim != nil {
|
||||
t.Fatal("Out() should be nil for zero out")
|
||||
}
|
||||
@@ -61,3 +62,27 @@ func TestLimitGenerator_NilReceiver(t *testing.T) {
|
||||
t.Fatal("nil receiver Out() should return nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimitGenerator_Burst(t *testing.T) {
|
||||
// Burst specified: should use NewLimiterWithBurst.
|
||||
g := newLimitGenerator(100, 200, 500)
|
||||
limIn := g.In()
|
||||
if limIn == nil {
|
||||
t.Fatal("In() should not be nil")
|
||||
}
|
||||
if limIn.Limit() != 100 {
|
||||
t.Fatalf("expected limit 100, got %d", limIn.Limit())
|
||||
}
|
||||
// With burst=500, Wait for 500 should succeed immediately.
|
||||
if n := limIn.Wait(context.Background(), 500); n != 500 {
|
||||
t.Fatalf("expected 500 with burst, got %d", n)
|
||||
}
|
||||
|
||||
limOut := g.Out()
|
||||
if limOut == nil {
|
||||
t.Fatal("Out() should not be nil")
|
||||
}
|
||||
if limOut.Limit() != 200 {
|
||||
t.Fatalf("expected limit 200, got %d", limOut.Limit())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user