diff --git a/sdk/azcore/CHANGELOG.md b/sdk/azcore/CHANGELOG.md index c5c1daa74b55..d32305566be3 100644 --- a/sdk/azcore/CHANGELOG.md +++ b/sdk/azcore/CHANGELOG.md @@ -18,6 +18,7 @@ ### Breaking Changes ### Bugs Fixed +* Retry policy always clones the underlying `*http.Request` before invoking the next policy. ### Other Changes diff --git a/sdk/azcore/runtime/policy_retry.go b/sdk/azcore/runtime/policy_retry.go index 5f52ba75b459..e0c5929f3b70 100644 --- a/sdk/azcore/runtime/policy_retry.go +++ b/sdk/azcore/runtime/policy_retry.go @@ -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) diff --git a/sdk/azcore/runtime/policy_retry_test.go b/sdk/azcore/runtime/policy_retry_test.go index 61ce081b4204..228d0931a025 100644 --- a/sdk/azcore/runtime/policy_retry_test.go +++ b/sdk/azcore/runtime/policy_retry_test.go @@ -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()