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.
This commit is contained in:
2026-11-03 00:51:15 +00:00
parent a96ecb2dc9
commit d9ec84ebc0
2 changed files with 22 additions and 1 deletions
+3 -1
View File
@@ -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
+19
View File
@@ -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")
}
})
}