Skip to content

Commit

Permalink
fix timeout bug
Browse files Browse the repository at this point in the history
Fixed a problem related to timeout config: ctx was being overwritten
when the timeout config value was set. As a result, the next retry
would immediately timeout. Fixed to not overwrite ctx when timeout
config value was set.
  • Loading branch information
convto committed Dec 26, 2022
1 parent a8d841e commit 9a38d4c
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
4 changes: 2 additions & 2 deletions async_retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ func (a *asyncRetry) call(ctx context.Context, f RetryableFunc, config *Config)
return retry.Do(
func() error {
if config.timeout > 0 {
var timeoutCancel context.CancelFunc
ctx, timeoutCancel = context.WithTimeout(ctx, config.timeout)
timeoutCtx, timeoutCancel := context.WithTimeout(ctx, config.timeout)
defer timeoutCancel()
return f(timeoutCtx)
}
return f(ctx)
},
Expand Down
7 changes: 7 additions & 0 deletions async_retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,16 @@ func Test_asyncRetry_Do(t *testing.T) {
name: "Timeout set correctly for each try",
args: args{
f: func(ctx context.Context) error {
started := time.Now()
counter++
select {
case <-ctx.Done():
// Since the timeout for this test case is 10 msec,
// even considering the error of the measurement,
// at least 9 msec should have elapsed by the time `ctx.Done()` is received.
if time.Since(started) < (9 * time.Millisecond) {
return Unrecoverable(fmt.Errorf("timeout is too fast"))
}
if counter < 3 {
return fmt.Errorf("timeout")
}
Expand Down

0 comments on commit 9a38d4c

Please sign in to comment.