Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

revert: fixed window ratelimiting #2116

Merged
merged 12 commits into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
28 changes: 6 additions & 22 deletions apps/agent/pkg/clock/real_clock.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,15 @@ package clock

import "time"

type TestClock struct {
now time.Time
type RealClock struct {
}

func NewTestClock(now ...time.Time) *TestClock {
if len(now) == 0 {
now = append(now, time.Now())
}
return &TestClock{now: now[0]}
func New() *RealClock {
return &RealClock{}
}

var _ Clock = &TestClock{}
var _ Clock = &RealClock{}

func (c *TestClock) Now() time.Time {
return c.now
}

// Tick advances the clock by the given duration and returns the new time.
func (c *TestClock) Tick(d time.Duration) time.Time {
c.now = c.now.Add(d)
return c.now
}

// Set sets the clock to the given time and returns the new time.
func (c *TestClock) Set(t time.Time) time.Time {
c.now = t
return c.now
func (c *RealClock) Now() time.Time {
return time.Now()
}
28 changes: 22 additions & 6 deletions apps/agent/pkg/clock/test_clock.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,31 @@ package clock

import "time"

type RealClock struct {
type TestClock struct {
now time.Time
}

func New() *RealClock {
return &RealClock{}
func NewTestClock(now ...time.Time) *TestClock {
if len(now) == 0 {
now = append(now, time.Now())
}
return &TestClock{now: now[0]}
}

var _ Clock = &RealClock{}
var _ Clock = &TestClock{}

func (c *RealClock) Now() time.Time {
return time.Now()
func (c *TestClock) Now() time.Time {
return c.now
}

// Tick advances the clock by the given duration and returns the new time.
func (c *TestClock) Tick(d time.Duration) time.Time {
c.now = c.now.Add(d)
return c.now
}

// Set sets the clock to the given time and returns the new time.
func (c *TestClock) Set(t time.Time) time.Time {
c.now = t
return c.now
}
17 changes: 9 additions & 8 deletions apps/agent/services/ratelimit/mitigate.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ func (s *service) Mitigate(ctx context.Context, req *ratelimitv1.MitigateRequest
duration := time.Duration(req.Duration) * time.Millisecond
bucket, _ := s.getBucket(bucketKey{req.Identifier, req.Limit, duration})
bucket.Lock()
defer bucket.Unlock()

bucket.windows[req.Window.GetSequence()] = req.Window
bucket.Unlock()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using defer for unlocking to ensure lock is always released

Replacing defer bucket.Unlock() with an explicit bucket.Unlock() may lead to the lock not being released if a panic occurs between the lock and unlock calls. Using defer ensures that the lock is always released, even in the event of an error or panic.

Apply this diff to revert to using defer:

 func (s *service) Mitigate(ctx context.Context, req *ratelimitv1.MitigateRequest) (*ratelimitv1.MitigateResponse, error) {
 	ctx, span := tracing.Start(ctx, "ratelimit.Mitigate")
 	defer span.End()

 	s.logger.Info().Interface("req", req).Msg("mitigating")

 	duration := time.Duration(req.Duration) * time.Millisecond
 	bucket, _ := s.getBucket(bucketKey{req.Identifier, req.Limit, duration})
 	bucket.Lock()
+	defer bucket.Unlock()
 	bucket.windows[req.Window.GetSequence()] = req.Window
-	bucket.Unlock()

 	return &ratelimitv1.MitigateResponse{}, nil
 }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
bucket.Unlock()
func (s *service) Mitigate(ctx context.Context, req *ratelimitv1.MitigateRequest) (*ratelimitv1.MitigateResponse, error) {
ctx, span := tracing.Start(ctx, "ratelimit.Mitigate")
defer span.End()
s.logger.Info().Interface("req", req).Msg("mitigating")
duration := time.Duration(req.Duration) * time.Millisecond
bucket, _ := s.getBucket(bucketKey{req.Identifier, req.Limit, duration})
bucket.Lock()
defer bucket.Unlock()
bucket.windows[req.Window.GetSequence()] = req.Window
return &ratelimitv1.MitigateResponse{}, nil
}


return &ratelimitv1.MitigateResponse{}, nil
}
Expand Down Expand Up @@ -51,12 +50,14 @@ func (s *service) broadcastMitigation(req mitigateWindowRequest) {
return
}
for _, peer := range peers {
_, err := peer.client.Mitigate(ctx, connect.NewRequest(&ratelimitv1.MitigateRequest{
Identifier: req.identifier,
Limit: req.limit,
Duration: req.duration.Milliseconds(),
Window: req.window,
}))
_, err := s.mitigateCircuitBreaker.Do(ctx, func(innerCtx context.Context) (*connect.Response[ratelimitv1.MitigateResponse], error) {
return peer.client.Mitigate(innerCtx, connect.NewRequest(&ratelimitv1.MitigateRequest{
Identifier: req.identifier,
Limit: req.limit,
Duration: req.duration.Milliseconds(),
Window: req.window,
}))
})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using a context with timeout to prevent hanging calls

Currently, context.Background() is used without any timeout or cancellation, which may lead to hanging calls if a peer does not respond. Consider using a context with a timeout to ensure that the Mitigate calls to peers do not block indefinitely.

Apply this diff to use a context with timeout:

 func (s *service) broadcastMitigation(req mitigateWindowRequest) {
-	ctx := context.Background()
+	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+	defer cancel()
 	node, err := s.cluster.FindNode(bucketKey{req.identifier, req.limit, req.duration}.toString())
 	if err != nil {
 		s.logger.Err(err).Msg("failed to find node")
 		return
 	}

Ensure that the context with timeout is used in the circuit breaker call:

 for _, peer := range peers {
 		_, err := s.mitigateCircuitBreaker.Do(ctx, func(innerCtx context.Context) (*connect.Response[ratelimitv1.MitigateResponse], error) {
-			return peer.client.Mitigate(innerCtx, connect.NewRequest(&ratelimitv1.MitigateRequest{
+			return peer.client.Mitigate(ctx, connect.NewRequest(&ratelimitv1.MitigateRequest{
 				Identifier: req.identifier,
 				Limit:      req.limit,
 				Duration:   req.duration.Milliseconds(),
 				Window:     req.window,
 			}))
 		})

Committable suggestion was skipped due to low confidence.

if err != nil {
s.logger.Err(err).Msg("failed to call mitigate")
} else {
Expand Down
10 changes: 6 additions & 4 deletions apps/agent/services/ratelimit/ratelimit_mitigation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ import (
)

func TestExceedingTheLimitShouldNotifyAllNodes(t *testing.T) {
t.Skip()
for _, clusterSize := range []int{1, 3, 5} {

for _, clusterSize := range []int{1, 3, 5, 9, 27} {
t.Run(fmt.Sprintf("Cluster Size %d", clusterSize), func(t *testing.T) {
logger := logging.New(nil)
clusters := []cluster.Cluster{}
Expand Down Expand Up @@ -94,23 +94,25 @@ func TestExceedingTheLimitShouldNotifyAllNodes(t *testing.T) {
ctx := context.Background()

// Saturate the window
for i := int64(0); i <= limit; i++ {
for i := int64(0); i < limit; i++ {
rl := util.RandomElement(ratelimiters)
res, err := rl.Ratelimit(ctx, req)
require.NoError(t, err)
t.Logf("saturate res: %+v", res)
require.True(t, res.Success)

}

time.Sleep(time.Second * 5)

// Let's hit everry node again
// They should all be mitigated
for i, rl := range ratelimiters {

res, err := rl.Ratelimit(ctx, req)
require.NoError(t, err)
t.Logf("res from %d: %+v", i, res)
// require.False(t, res.Success)
require.False(t, res.Success)
}

})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ import (
"github.com/unkeyed/unkey/apps/agent/pkg/util"
)

func TestReplication(t *testing.T) {
t.Skip()
func TestSync(t *testing.T) {
type Node struct {
srv *service
cluster cluster.Cluster
Expand Down
Loading
Loading