Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: unnecessary request cycle on non-idempotent methods #777 #896

Merged
merged 1 commit into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -1214,8 +1214,9 @@ func (r *Request) Execute(method, url string) (res *Response, err error) {
r.RetryCount = 0 // default behavior is no retry
}

isIdempotent := r.isIdempotent()
var backoff *backoffWithJitter
if r.RetryCount > 0 && r.isIdempotent() {
if r.RetryCount > 0 && isIdempotent {
backoff = newBackoffWithJitter(r.RetryWaitTime, r.RetryMaxWaitTime)
}

Expand All @@ -1234,7 +1235,8 @@ func (r *Request) Execute(method, url string) (res *Response, err error) {
}

// we have reached the maximum no. of requests
if r.Attempt-1 == r.RetryCount {
// or request method is not an idempotent
if r.Attempt-1 == r.RetryCount || !isIdempotent {
break
}

Expand Down
32 changes: 32 additions & 0 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2097,6 +2097,38 @@ func TestRequestAllowPayload(t *testing.T) {

}

func TestRequestNoRetryOnNonIdempotentMethod(t *testing.T) {
ts := createFileUploadServer(t)
defer ts.Close()

str := "test"
buf := []byte(str)

bufReader := bytes.NewReader(buf)
bufCpy := make([]byte, len(buf))

c := dcnl().
SetTimeout(time.Second * 3).
AddRetryHook(
func(response *Response, _ error) {
read, err := bufReader.Read(bufCpy)

assertNil(t, err)
assertEqual(t, len(buf), read)
assertEqual(t, str, string(bufCpy))
},
)

req := c.R().
SetRetryCount(3).
SetFileReader("name", "filename", bufReader)
resp, err := req.Post(ts.URL + "/set-reset-multipart-readers-test")

assertNil(t, err)
assertEqual(t, 1, resp.Request.Attempt)
assertEqual(t, 500, resp.StatusCode())
}

func TestRequestPanicContext(t *testing.T) {
defer func() {
if r := recover(); r == nil {
Expand Down