2023-03-28 18:39:22 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2023-05-05 14:38:22 +00:00
|
|
|
package queue
|
2022-12-16 21:49:26 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
)
|
|
|
|
|
2023-05-05 14:38:22 +00:00
|
|
|
type Request struct{ Kind string }
|
|
|
|
|
2022-12-16 21:49:26 +00:00
|
|
|
func TestRateLimiter_Backoff(t *testing.T) {
|
|
|
|
t.Parallel()
|
|
|
|
|
2023-05-05 14:38:22 +00:00
|
|
|
limiter := NewRateLimiter[Request](1*time.Millisecond, 1*time.Second)
|
2022-12-16 21:49:26 +00:00
|
|
|
|
|
|
|
request := Request{Kind: "one"}
|
|
|
|
require.Equal(t, 1*time.Millisecond, limiter.NextRetry(request))
|
|
|
|
require.Equal(t, 2*time.Millisecond, limiter.NextRetry(request))
|
|
|
|
require.Equal(t, 4*time.Millisecond, limiter.NextRetry(request))
|
|
|
|
require.Equal(t, 8*time.Millisecond, limiter.NextRetry(request))
|
|
|
|
require.Equal(t, 16*time.Millisecond, limiter.NextRetry(request))
|
|
|
|
|
|
|
|
requestTwo := Request{Kind: "two"}
|
|
|
|
require.Equal(t, 1*time.Millisecond, limiter.NextRetry(requestTwo))
|
|
|
|
require.Equal(t, 2*time.Millisecond, limiter.NextRetry(requestTwo))
|
|
|
|
|
|
|
|
limiter.Forget(request)
|
|
|
|
require.Equal(t, 1*time.Millisecond, limiter.NextRetry(request))
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestRateLimiter_Overflow(t *testing.T) {
|
|
|
|
t.Parallel()
|
|
|
|
|
2023-05-05 14:38:22 +00:00
|
|
|
limiter := NewRateLimiter[Request](1*time.Millisecond, 1000*time.Second)
|
2022-12-16 21:49:26 +00:00
|
|
|
|
|
|
|
request := Request{Kind: "one"}
|
|
|
|
for i := 0; i < 5; i++ {
|
|
|
|
limiter.NextRetry(request)
|
|
|
|
}
|
|
|
|
// ensure we have a normally incrementing exponential backoff
|
|
|
|
require.Equal(t, 32*time.Millisecond, limiter.NextRetry(request))
|
|
|
|
|
|
|
|
overflow := Request{Kind: "overflow"}
|
|
|
|
for i := 0; i < 1000; i++ {
|
|
|
|
limiter.NextRetry(overflow)
|
|
|
|
}
|
|
|
|
// make sure we're capped at the passed in max backoff
|
|
|
|
require.Equal(t, 1000*time.Second, limiter.NextRetry(overflow))
|
|
|
|
|
2023-05-05 14:38:22 +00:00
|
|
|
limiter = NewRateLimiter[Request](1*time.Minute, 1000*time.Hour)
|
2022-12-16 21:49:26 +00:00
|
|
|
|
|
|
|
for i := 0; i < 2; i++ {
|
|
|
|
limiter.NextRetry(request)
|
|
|
|
}
|
|
|
|
// ensure we have a normally incrementing exponential backoff
|
|
|
|
require.Equal(t, 4*time.Minute, limiter.NextRetry(request))
|
|
|
|
|
|
|
|
for i := 0; i < 1000; i++ {
|
|
|
|
limiter.NextRetry(overflow)
|
|
|
|
}
|
|
|
|
// make sure we're capped at the passed in max backoff
|
|
|
|
require.Equal(t, 1000*time.Hour, limiter.NextRetry(overflow))
|
|
|
|
}
|