diff --git a/internal/api/ratelimit.go b/internal/api/ratelimit.go index c3f4018..555d395 100644 --- a/internal/api/ratelimit.go +++ b/internal/api/ratelimit.go @@ -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 @@ -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, } } @@ -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) diff --git a/internal/api/ratelimit_test.go b/internal/api/ratelimit_test.go index 625c237..5faf719 100644 --- a/internal/api/ratelimit_test.go +++ b/internal/api/ratelimit_test.go @@ -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) @@ -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) { @@ -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 @@ -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() @@ -182,22 +222,26 @@ 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()) @@ -205,10 +249,10 @@ func TestTryAcquire(t *testing.T) { }) 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())