From 5cf5b55ef706d819b772d16ba64d4f8f17565870 Mon Sep 17 00:00:00 2001 From: Austin Abro <37223396+AustinAbro321@users.noreply.github.com> Date: Mon, 22 Apr 2024 15:10:18 -0400 Subject: [PATCH] refactor: retry improvements (#72) ## Description Before the retry function was blocking during the default case. If context was cancelled during the function call that's being retried it wouldn't continue. Now it will. Code is generally cleaner as well. --- helpers/misc.go | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/helpers/misc.go b/helpers/misc.go index 8b69715..47bd24c 100644 --- a/helpers/misc.go +++ b/helpers/misc.go @@ -31,11 +31,13 @@ func RetryWithContext(ctx context.Context, fn func() error, attempts int, delay return errors.New("invalid number of attempts, must be at least 1") } var err error + timer := time.NewTimer(0) + defer timer.Stop() for r := 0; r < attempts; r++ { select { case <-ctx.Done(): return ctx.Err() - default: + case <-timer.C: err = fn() if err == nil { return nil @@ -53,15 +55,7 @@ func RetryWithContext(ctx context.Context, fn func() error, attempts int, delay logger("Retrying in %s", backoff) - timer := time.NewTimer(backoff) - select { - case <-timer.C: - case <-ctx.Done(): - if !timer.Stop() { - <-timer.C - } - return ctx.Err() - } + timer.Reset(backoff) } }