Skip to content

Commit

Permalink
Retry policy will always clone the *http.Request (Azure#20843)
Browse files Browse the repository at this point in the history
* Retry policy will always clone the *http.Request

This ensures that the entirety of the request is restored on retries.

* simplify test
  • Loading branch information
jhendrixMSFT authored May 12, 2023
1 parent e1bbe45 commit a3b2c13
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
1 change: 1 addition & 0 deletions sdk/azcore/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
### Breaking Changes

### Bugs Fixed
* Retry policy always clones the underlying `*http.Request` before invoking the next policy.

### Other Changes

Expand Down
3 changes: 2 additions & 1 deletion sdk/azcore/runtime/policy_retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,8 @@ func (p *retryPolicy) Do(req *policy.Request) (resp *http.Response, err error) {
}

if options.TryTimeout == 0 {
resp, err = req.Next()
clone := req.Clone(req.Raw().Context())
resp, err = clone.Next()
} else {
// Set the per-try time for this particular retry operation and then Do the operation.
tryCtx, tryCancel := context.WithTimeout(req.Raw().Context(), options.TryTimeout)
Expand Down
33 changes: 33 additions & 0 deletions sdk/azcore/runtime/policy_retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -810,6 +810,39 @@ func TestRetryableRequestBodyWithCloser(t *testing.T) {
require.True(t, tr.closeCalled)
}

func TestRetryPolicySuccessWithRetryPreserveHeaders(t *testing.T) {
srv, close := mock.NewServer()
defer close()
srv.AppendResponse(mock.WithStatusCode(http.StatusRequestTimeout))
srv.AppendResponse()
pl := exported.NewPipeline(srv, NewRetryPolicy(testRetryOptions()), exported.PolicyFunc(challengeLikePolicy))
req, err := NewRequest(context.Background(), http.MethodGet, srv.URL())
require.NoError(t, err)
body := newRewindTrackingBody("stuff")
require.NoError(t, req.SetBody(body, "text/plain"))
resp, err := pl.Do(req)
require.NoError(t, err)
require.EqualValues(t, http.StatusOK, resp.StatusCode)
require.EqualValues(t, 2, srv.Requests())
require.EqualValues(t, 1, body.rcount)
require.True(t, body.closed)
}

func challengeLikePolicy(req *policy.Request) (*http.Response, error) {
if req.Body() == nil {
return nil, errors.New("request body wasn't restored")
}
if req.Raw().Header.Get("content-type") != "text/plain" {
return nil, errors.New("content-type header wasn't restored")
}

// remove the body and header. the retry policy should restore them
if err := req.SetBody(nil, ""); err != nil {
return nil, err
}
return req.Next()
}

func newRewindTrackingBody(s string) *rewindTrackingBody {
// there are two rewinds that happen before rewinding for a retry
// 1. to get the body's size in SetBody()
Expand Down

0 comments on commit a3b2c13

Please sign in to comment.