Skip to content

Commit 8416df3

Browse files
authored
fix: respect context cancellation in RetryTransport (#3383)
* fix: respect context cancellation in RetryTransport Use context-aware retry delays and check cancellation before each attempt. Do not sleep after the final attempt, and close unsent request bodies when cancellation prevents the initial attempt. Drain and close discarded responses before retrying, with a 4KB bound matching the new client implementation. Preserve the final response body for the caller, and discard responses returned alongside transport errors. Add deterministic virtual-time tests for cancellation and retry delays, plus coverage for request body ownership, exhausted responses, bounded draining, and read errors. * fix: inline retry response cleanup
1 parent 2a5e78c commit 8416df3

2 files changed

Lines changed: 451 additions & 34 deletions

File tree

‎github/transport.go‎

Lines changed: 56 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"context"
66
"errors"
7+
"fmt"
78
"io"
89
"log"
910
"net/http"
@@ -241,49 +242,70 @@ func NewRetryTransport(rt http.RoundTripper, options ...RetryTransportOption) *R
241242
func (t *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
242243
var err error
243244
var resp *http.Response
244-
var dataBuffer *bytes.Reader
245+
var data []byte
245246

246247
for retry := 0; retry <= t.maxRetries; retry++ {
247-
// Reset the body
248-
// Code from httpretry (https://github.com/ybbus/httpretry/blob/master/roundtripper.go#L60)
249-
// if request provides GetBody() we use it as Body,
250-
// because GetBody can be retrieved arbitrary times for retry
251-
if req.GetBody != nil {
252-
bodyReadCloser, _ := req.GetBody()
253-
req.Body = bodyReadCloser
254-
} else if req.Body != nil {
255-
256-
// we need to store the complete body, since we need to reset it if a retry happens
257-
// but: not very efficient because:
258-
// a) huge stream data size will all be buffered completely in the memory
259-
// imagine: 1GB stream data would work efficiently with io.Copy, but has to be buffered completely in memory
260-
// b) unnecessary if first attempt succeeds
261-
// a solution would be to at least support more types for GetBody()
262-
263-
// store it for the first time
264-
if dataBuffer == nil {
265-
data, err := io.ReadAll(req.Body)
266-
req.Body.Close()
267-
if err != nil {
268-
return nil, err
269-
}
270-
dataBuffer = bytes.NewReader(data)
271-
req.ContentLength = int64(dataBuffer.Len())
272-
req.Body = io.NopCloser(dataBuffer)
248+
if err := req.Context().Err(); err != nil {
249+
// Before the first attempt we still own the request body. Once
250+
// sent, the underlying transport is responsible for closing it.
251+
if retry == 0 && req.Body != nil {
252+
_ = req.Body.Close()
273253
}
254+
return nil, err
255+
}
274256

275-
// reset the request body
276-
if _, err = dataBuffer.Seek(0, io.SeekStart); err != nil {
277-
return nil, err
257+
// Shallow copy so we never mutate the caller's Request.
258+
reqCopy := new(*req)
259+
260+
if reqCopy.Body != nil && reqCopy.Body != http.NoBody {
261+
if req.GetBody != nil {
262+
// The first attempt uses the original body. Later attempts need a
263+
// fresh body so the request can be sent again.
264+
if retry > 0 {
265+
reqCopy.Body, err = req.GetBody()
266+
if err != nil {
267+
return nil, fmt.Errorf("failed to rewind request body: %w", err)
268+
}
269+
}
270+
} else {
271+
// Without GetBody, buffer the body once and use a fresh reader for
272+
// every attempt. This preserves the legacy transport's fallback for
273+
// streaming bodies without modifying the caller's Request.
274+
if retry == 0 {
275+
// There is no size limit: large bodies may consume significant memory.
276+
data, err = io.ReadAll(req.Body)
277+
_ = req.Body.Close()
278+
if err != nil {
279+
return nil, err
280+
}
281+
}
282+
reqCopy.ContentLength = int64(len(data))
283+
reqCopy.Body = io.NopCloser(bytes.NewReader(data))
278284
}
279285
}
280286

281-
resp, err = t.transport.RoundTrip(req)
282-
if resp != nil && !t.retryableErrors[resp.StatusCode] {
283-
return resp, err
287+
resp, err = t.transport.RoundTrip(reqCopy)
288+
if err != nil {
289+
// A RoundTripper must not return a response alongside an error,
290+
// but discard it if one is returned so it cannot leak.
291+
if resp != nil && resp.Body != nil {
292+
_ = resp.Body.Close()
293+
}
294+
resp = nil
295+
} else if !t.retryableErrors[resp.StatusCode] {
296+
return resp, nil
284297
}
285298

286-
time.Sleep(t.retryDelay)
299+
if retry < t.maxRetries {
300+
// Close the intermediate response body before retrying, otherwise its
301+
// connection and resources are leaked. Draining is unnecessary with
302+
// Go 1.27 and could block indefinitely on a stalled response body.
303+
if resp != nil && resp.Body != nil {
304+
_ = resp.Body.Close()
305+
}
306+
resp = nil
307+
sleep(req.Context(), t.retryDelay)
308+
}
287309
}
288310

289311
return resp, err

0 commit comments

Comments
 (0)