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
6 changes: 6 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ module github.com/tim/cu
go 1.24.4

require (
github.com/fatih/color v1.18.0
github.com/manifoldco/promptui v0.9.0
github.com/raksul/go-clickup v0.0.0-20241002105938-60c057c125ff
github.com/spf13/cobra v1.9.1
github.com/spf13/viper v1.20.1
github.com/stretchr/testify v1.10.0
github.com/zalando/go-keyring v0.2.6
gopkg.in/yaml.v3 v3.0.1
)
Expand All @@ -16,12 +18,16 @@ require (
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.6 // indirect
github.com/danieljoos/wincred v1.2.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fsnotify/fsnotify v1.8.0 // indirect
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
github.com/godbus/dbus/v5 v5.1.0 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/sagikazarmark/locafero v0.7.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
Expand Down
9 changes: 9 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ github.com/danieljoos/wincred v1.2.2/go.mod h1:w7w4Utbrz8lqeMbDAK0lkNJUv5sAOkFi7
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
Expand All @@ -36,6 +38,11 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/manifoldco/promptui v0.9.0 h1:3V4HzJk1TtXW1MTZMP7mdlwbBpIinw3HztaIlYthEiA=
github.com/manifoldco/promptui v0.9.0/go.mod h1:ka04sppxSGFAtxX0qhlYQjISsg9mR4GWtQEhdbn6Pgg=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
Expand Down Expand Up @@ -75,6 +82,8 @@ go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
Expand Down
218 changes: 218 additions & 0 deletions internal/api/ratelimit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
package api

import (
"context"
"sync"
"sync/atomic"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestNewRateLimiter(t *testing.T) {
t.Run("creates rate limiter with correct parameters", func(t *testing.T) {
rl := NewRateLimiter(10, time.Second)
assert.NotNil(t, rl)
assert.Equal(t, 10, rl.tokens)
assert.Equal(t, 10, rl.maxTokens)
assert.Equal(t, 100*time.Millisecond, rl.refillRate)
})

t.Run("different rates", func(t *testing.T) {
tests := []struct {
maxRequests int
per time.Duration
wantRefill time.Duration
}{
{100, time.Minute, 600 * time.Millisecond},
{60, time.Minute, time.Second},
{1, time.Second, time.Second},
{10, 100 * time.Millisecond, 10 * time.Millisecond},
}

for _, tt := range tests {
rl := NewRateLimiter(tt.maxRequests, tt.per)
assert.Equal(t, tt.wantRefill, rl.refillRate)
}
})
}

func TestRateLimiterWait(t *testing.T) {
t.Run("allows burst up to limit", func(t *testing.T) {
rl := NewRateLimiter(3, time.Second)
ctx := context.Background()

// 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")
}
})

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

// 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)

assert.NoError(t, err)
assert.GreaterOrEqual(t, elapsed, 100*time.Millisecond)
})

t.Run("respects context cancellation", func(t *testing.T) {
rl := NewRateLimiter(1, time.Hour) // Very slow refill
ctx, cancel := context.WithCancel(context.Background())

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

// Cancel context while waiting
go func() {
time.Sleep(50 * time.Millisecond)
cancel()
}()

start := time.Now()
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)
})

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

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

// Wait for refill
time.Sleep(60 * 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")
})
}

func TestRateLimiterConcurrency(t *testing.T) {
t.Run("handles concurrent requests safely", func(t *testing.T) {
rl := NewRateLimiter(10, 100*time.Millisecond)
ctx := context.Background()

var wg sync.WaitGroup
var successCount int32
numGoroutines := 20

for i := 0; i < numGoroutines; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if err := rl.Wait(ctx); err == nil {
atomic.AddInt32(&successCount, 1)
}
}()
}

wg.Wait()

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

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
rl := NewRateLimiter(5, 200*time.Millisecond)
ctx := context.Background()

start := time.Now()
requestCount := 0

// Try to make 10 requests
for i := 0; i < 10; i++ {
if err := rl.Wait(ctx); err == nil {
requestCount++
}
}

elapsed := time.Since(start)

// Should have made all 10 requests
assert.Equal(t, 10, requestCount)

// Should have taken at least 200ms to complete
// (5 immediate, then wait ~40ms, get 1, wait ~40ms, etc)
assert.True(t, elapsed >= 200*time.Millisecond, "Should respect rate limit timing")
})
}

func TestTryAcquire(t *testing.T) {
t.Run("acquires tokens correctly", func(t *testing.T) {
rl := NewRateLimiter(3, time.Second)

// Should succeed for available tokens
assert.True(t, rl.tryAcquire())
assert.True(t, rl.tryAcquire())
assert.True(t, rl.tryAcquire())

// Should fail when no tokens
assert.False(t, rl.tryAcquire())
})

t.Run("refills tokens correctly", func(t *testing.T) {
rl := NewRateLimiter(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)

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

// Wait for full refill
time.Sleep(55 * 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)

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

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