Skip to content

Commit

Permalink
fix unexpected sleep after the last retry
Browse files Browse the repository at this point in the history
Signed-off-by: zhyu <[email protected]>
  • Loading branch information
zhyu committed May 8, 2024
1 parent 7eecc89 commit 8b2649c
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
### Fixed

- Fixes opensearchtransport ignores request context cancellation when `retryBackoff` is configured ([#540](https://github.com/opensearch-project/opensearch-go/pull/540))
- Fixes opensearchtransport sleeps unexpectedly after the last retry ([#540](https://github.com/opensearch-project/opensearch-go/pull/540))

### Security

Expand Down
2 changes: 1 addition & 1 deletion opensearchtransport/opensearchtransport.go
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ func (c *Client) Perform(req *http.Request) (*http.Response, error) {
}

// Delay the retry if a backoff function is configured
if c.retryBackoff != nil {
if c.retryBackoff != nil && i < c.maxRetries {
var cancelled bool
timer := time.NewTimer(c.retryBackoff(i + 1))
select {
Expand Down
48 changes: 48 additions & 0 deletions opensearchtransport/opensearchtransport_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,54 @@ func TestTransportPerformRetries(t *testing.T) {
t.Fatalf("unexpected number of requests: expected 1, got %d", i)
}
})

t.Run("Don't backoff after the last retry", func(t *testing.T) {
var (
i int
j int
numReqs = 5
numRetries = numReqs - 1
)

u, _ := url.Parse("http://foo.bar")
tp, _ := New(Config{
MaxRetries: numRetries,
URLs: []*url.URL{u, u, u},
Transport: &mockTransp{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
i++
fmt.Printf("Request #%d", i)
fmt.Print(": ERR\n")
return nil, &mockNetError{error: fmt.Errorf("Mock network error (%d)", i)}
},
},

// A simple incremental backoff function
//
RetryBackoff: func(i int) time.Duration {
j++
d := time.Millisecond
fmt.Printf("Attempt: %d | Sleeping for %s...\n", i, d)
return d
},
})

req, _ := http.NewRequest(http.MethodGet, "/abc", nil)

//nolint:bodyclose // Mock response does not have a body to close
_, err := tp.Perform(req)
if err == nil {
t.Fatalf("Expected error, got: %v", err)
}

if i != numReqs {
t.Errorf("Unexpected number of requests, want=%d, got=%d", numReqs, i)
}

if j != numRetries {
t.Errorf("Unexpected number of backoffs, want=>%d, got=%d", numRetries, j)
}
})
}

func TestURLs(t *testing.T) {
Expand Down

0 comments on commit 8b2649c

Please sign in to comment.