From d9ec84ebc048a17ecafdb6948668e177c41ee15c Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Tue, 3 Nov 2026 00:51:15 +0000 Subject: [PATCH] fix(retry): stop the backoff timer when the wait ends early time.After keeps its timer alive until it fires on go 1.22 semantics, so each cancelled retry wait pinned a timer for up to 2s. A stoppable timer releases it at once. --- retry.go | 4 +++- retry_test.go | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/retry.go b/retry.go index fa7ee74..43a0afd 100644 --- a/retry.go +++ b/retry.go @@ -151,8 +151,10 @@ func (p *retryPolicy) totalTries() int { // normally (do should proceed with the next attempt), false when ctx // ended it early (do should stop retrying and return the last result). func defaultWaitFn(ctx context.Context, d time.Duration) bool { + t := time.NewTimer(d) + defer t.Stop() select { - case <-time.After(d): + case <-t.C: return true case <-ctx.Done(): return false diff --git a/retry_test.go b/retry_test.go index 165c999..a349ee4 100644 --- a/retry_test.go +++ b/retry_test.go @@ -1136,3 +1136,22 @@ func TestRetryPolicy_WaitBeforeLargeBackoffCapped(t *testing.T) { }) } } + +func TestDefaultWaitFn(t *testing.T) { + t.Run("completes", func(t *testing.T) { + if !defaultWaitFn(context.Background(), time.Millisecond) { + t.Fatal("want true after the wait elapses") + } + }) + t.Run("cancel returns promptly", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + start := time.Now() + if defaultWaitFn(ctx, time.Minute) { + t.Fatal("want false on canceled ctx") + } + if time.Since(start) > time.Second { + t.Fatal("canceled wait did not return promptly") + } + }) +}