Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion internal/api/ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type RateLimiter struct {
maxTokens int
refillRate time.Duration
lastRefill time.Time
now func() time.Time // injectable clock; tests substitute a fake
}

// NewRateLimiter creates a new rate limiter
Expand All @@ -22,6 +23,7 @@ func NewRateLimiter(maxRequests int, per time.Duration) *RateLimiter {
maxTokens: maxRequests,
refillRate: per / time.Duration(maxRequests),
lastRefill: time.Now(),
now: time.Now,
}
}

Expand All @@ -47,7 +49,7 @@ func (r *RateLimiter) tryAcquire() bool {
defer r.mu.Unlock()

// Refill tokens based on time elapsed
now := time.Now()
now := r.now()
elapsed := now.Sub(r.lastRefill)
tokensToAdd := int(elapsed / r.refillRate)

Expand Down
136 changes: 90 additions & 46 deletions internal/api/ratelimit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,42 @@ import (
"github.com/stretchr/testify/require"
)

// fakeClock is a manually advanced clock for deterministic refill tests.
type fakeClock struct {
mu sync.Mutex
t time.Time
}

func (c *fakeClock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.t
}

func (c *fakeClock) Advance(d time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.t = c.t.Add(d)
}

// newFakeClockLimiter returns a limiter driven by a fake clock that only
// moves when the test calls Advance.
func newFakeClockLimiter(maxRequests int, per time.Duration) (*RateLimiter, *fakeClock) {
clk := &fakeClock{t: time.Unix(0, 0)}
rl := NewRateLimiter(maxRequests, per)
rl.now = clk.Now
rl.lastRefill = clk.Now()
return rl, clk
}

// guardCtx bounds Wait calls that should return immediately, so a
// regression fails the test instead of hanging it.
func guardCtx(t *testing.T) context.Context {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
t.Cleanup(cancel)
return ctx
}

func TestNewRateLimiter(t *testing.T) {
t.Run("creates rate limiter with correct parameters", func(t *testing.T) {
rl := NewRateLimiter(10, time.Second)
Expand Down Expand Up @@ -41,35 +77,42 @@ func TestNewRateLimiter(t *testing.T) {

func TestRateLimiterWait(t *testing.T) {
t.Run("allows burst up to limit", func(t *testing.T) {
rl := NewRateLimiter(3, time.Second)
ctx := context.Background()
// Clock is frozen, so these can only succeed from the initial burst
rl, _ := newFakeClockLimiter(3, time.Second)
ctx := guardCtx(t)

// Should allow 3 immediate requests
for i := 0; i < 3; i++ {
start := time.Now()
err := rl.Wait(ctx)
elapsed := time.Since(start)

assert.NoError(t, err)
assert.Less(t, elapsed, 10*time.Millisecond, "Should not wait for burst")
assert.NoError(t, rl.Wait(ctx))
}
assert.False(t, rl.tryAcquire(), "Burst should be exhausted")
})

t.Run("waits when limit exceeded", func(t *testing.T) {
rl := NewRateLimiter(2, 200*time.Millisecond)
ctx := context.Background()
rl, clk := newFakeClockLimiter(2, 20*time.Millisecond)
ctx := guardCtx(t)

// Use up tokens
require.NoError(t, rl.Wait(ctx))
require.NoError(t, rl.Wait(ctx))

// Next request should wait
start := time.Now()
err := rl.Wait(ctx)
elapsed := time.Since(start)
done := make(chan error, 1)
go func() { done <- rl.Wait(ctx) }()

// Clock is frozen, so Wait cannot return yet
select {
case err := <-done:
t.Fatalf("Wait returned before refill: %v", err)
case <-time.After(50 * time.Millisecond):
}

assert.NoError(t, err)
assert.GreaterOrEqual(t, elapsed, 100*time.Millisecond)
// One refill period unblocks it on the next poll
clk.Advance(10 * time.Millisecond)
select {
case err := <-done:
assert.NoError(t, err)
case <-time.After(5 * time.Second):
t.Fatal("Wait did not return after refill")
}
})

t.Run("respects context cancellation", func(t *testing.T) {
Expand All @@ -89,36 +132,35 @@ func TestRateLimiterWait(t *testing.T) {
err := rl.Wait(ctx)
elapsed := time.Since(start)

assert.Error(t, err)
assert.Equal(t, context.Canceled, err)
assert.Less(t, elapsed, 100*time.Millisecond)
assert.ErrorIs(t, err, context.Canceled)
// Generous bound: refill is an hour, so returning at all proves cancellation
assert.Less(t, elapsed, 5*time.Second)
})

t.Run("refills tokens over time", func(t *testing.T) {
rl := NewRateLimiter(2, 100*time.Millisecond)
ctx := context.Background()
rl, clk := newFakeClockLimiter(2, 100*time.Millisecond)
ctx := guardCtx(t)

// Use all tokens
require.NoError(t, rl.Wait(ctx))
require.NoError(t, rl.Wait(ctx))

// Wait for refill
time.Sleep(60 * time.Millisecond)
// One refill period; with the clock frozen otherwise, Wait can only
// succeed from the refilled token
clk.Advance(50 * time.Millisecond)

// Should have 1 token refilled
start := time.Now()
err := rl.Wait(ctx)
elapsed := time.Since(start)

assert.NoError(t, err)
assert.Less(t, elapsed, 10*time.Millisecond, "Should not wait after refill")
assert.NoError(t, rl.Wait(ctx))
assert.False(t, rl.tryAcquire(), "Only one token should have refilled")
})
}

func TestRateLimiterConcurrency(t *testing.T) {
t.Run("handles concurrent requests safely", func(t *testing.T) {
rl := NewRateLimiter(10, 100*time.Millisecond)
ctx := context.Background()
// Frozen clock: no refills, so exactly the burst succeeds and the
// rest block until the context expires
rl, _ := newFakeClockLimiter(10, 100*time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()

var wg sync.WaitGroup
var successCount int32
Expand All @@ -136,14 +178,12 @@ func TestRateLimiterConcurrency(t *testing.T) {

wg.Wait()

// Should have allowed exactly 10 requests immediately
// Others would need to wait for refill
assert.GreaterOrEqual(t, atomic.LoadInt32(&successCount), int32(10))
assert.Equal(t, int32(10), atomic.LoadInt32(&successCount))
})

t.Run("maintains rate limit under load", func(t *testing.T) {
// This test is inherently timing-sensitive
// We'll use a larger window to reduce flakiness
// Real time; only a lower bound is asserted, which sleep overshoot
// cannot violate
rl := NewRateLimiter(5, 200*time.Millisecond)
ctx := context.Background()

Expand Down Expand Up @@ -182,33 +222,37 @@ func TestTryAcquire(t *testing.T) {
})

t.Run("refills tokens correctly", func(t *testing.T) {
rl := NewRateLimiter(2, 100*time.Millisecond)
rl, clk := newFakeClockLimiter(2, 100*time.Millisecond)

// Use all tokens
assert.True(t, rl.tryAcquire())
assert.True(t, rl.tryAcquire())
assert.False(t, rl.tryAcquire())

// Wait for one refill period
time.Sleep(55 * time.Millisecond)
// Just short of one refill period
clk.Advance(49 * time.Millisecond)
assert.False(t, rl.tryAcquire())

// Complete one refill period
clk.Advance(1 * time.Millisecond)

// Should have 1 token
assert.True(t, rl.tryAcquire())
assert.False(t, rl.tryAcquire())

// Wait for full refill
time.Sleep(55 * time.Millisecond)
// Another refill period
clk.Advance(50 * time.Millisecond)

// Should have 1 more token (not exceeding max)
assert.True(t, rl.tryAcquire())
assert.False(t, rl.tryAcquire())
})

t.Run("does not exceed max tokens", func(t *testing.T) {
rl := NewRateLimiter(2, 100*time.Millisecond)
rl, clk := newFakeClockLimiter(2, 100*time.Millisecond)

// Wait long enough for multiple refills
time.Sleep(300 * time.Millisecond)
// Long enough for multiple refills
clk.Advance(300 * time.Millisecond)

// Should still be capped at max
assert.True(t, rl.tryAcquire())
Expand Down
Loading