Skip to content

Commit

Permalink
perf: runtime.Gosched() if RetryDelay returns 0
Browse files Browse the repository at this point in the history
Signed-off-by: Rueian <[email protected]>
  • Loading branch information
rueian committed Oct 24, 2024
1 parent 2b51b42 commit 1928749
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 22 deletions.
40 changes: 18 additions & 22 deletions retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package rueidis

import (
"context"
"runtime"
"time"

"github.com/redis/rueidis/internal/util"
Expand Down Expand Up @@ -57,36 +58,31 @@ func (r *retryer) RetryDelay(attempts int, cmd Completed, err error) time.Durati
}

func (r *retryer) WaitForRetry(ctx context.Context, duration time.Duration) {
if duration <= 0 {
return
}

if ch := ctx.Done(); ch != nil {
tm := time.NewTimer(duration)
defer tm.Stop()
select {
case <-ch:
case <-tm.C:
if duration > 0 {
if ch := ctx.Done(); ch != nil {
tm := time.NewTimer(duration)
defer tm.Stop()
select {
case <-ch:
case <-tm.C:
}
} else {
time.Sleep(duration)
}
} else {
time.Sleep(duration)
}
}

func (r *retryer) WaitOrSkipRetry(
ctx context.Context, attempts int, cmd Completed, err error,
) bool {
delay := r.RetryDelay(attempts, cmd, err)
if delay < 0 {
return false
}
if delay == 0 {
return true
}

if dl, ok := ctx.Deadline(); !ok || time.Until(dl) > delay {
r.WaitForRetry(ctx, delay)
if delay := r.RetryDelay(attempts, cmd, err); delay == 0 {
runtime.Gosched()
return true
} else if delay > 0 {
if dl, ok := ctx.Deadline(); !ok || time.Until(dl) > delay {
r.WaitForRetry(ctx, delay)
return true
}
}
return false
}
13 changes: 13 additions & 0 deletions retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,19 @@ func TestRetrier_WaitOrSkipRetry(t *testing.T) {
}
})

t.Run("RetryDelayFn returns 0 delay", func(t *testing.T) {
r := &retryer{
RetryDelayFn: func(attempts int, _ Completed, err error) time.Duration {
return 0
},
}

shouldRetry := r.WaitOrSkipRetry(nil, 0, Completed{}, nil)
if !shouldRetry {
t.Error("WaitOrSkipRetry() = false; want true")
}
})

t.Run("context is canceled", func(t *testing.T) {
r := &retryer{
RetryDelayFn: func(attempts int, _ Completed, err error) time.Duration {
Expand Down

0 comments on commit 1928749

Please sign in to comment.