From ee9b968440d3f292575e11fdbcd62be1764d8b2b Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 9 Feb 2023 20:55:24 +0000 Subject: [PATCH] fix: Do first try immediately, then activate floor --- retrier.go | 5 ++++- retrier_test.go | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/retrier.go b/retrier.go index cfcbe7d..7ebfeab 100644 --- a/retrier.go +++ b/retrier.go @@ -15,7 +15,7 @@ type Retrier struct { // New creates a retrier that exponentially backs off from floor to ceil pauses. func New(floor, ceil time.Duration) *Retrier { return &Retrier{ - delay: floor, + delay: 0, floor: floor, ceil: ceil, } @@ -29,6 +29,9 @@ func (r *Retrier) Wait(ctx context.Context) bool { } select { case <-time.After(r.delay): + if r.delay < r.floor { + r.delay = r.floor + } return true case <-ctx.Done(): return false diff --git a/retrier_test.go b/retrier_test.go index c6ac1e7..0ac960e 100644 --- a/retrier_test.go +++ b/retrier_test.go @@ -15,3 +15,17 @@ func TestContextCancel(t *testing.T) { t.Fatalf("attempt allowed even though context cancelled") } } + +func TestFirstTryImmediately(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + r := New(time.Hour, time.Hour) + tt := time.Now() + if !r.Wait(ctx) { + t.Fatalf("attempt not allowed") + } + if time.Since(tt) > time.Second { + t.Fatalf("attempt took too long") + } +}