Skip to content
Open
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
36 changes: 33 additions & 3 deletions github/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,15 @@ func (t *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
var dataBuffer *bytes.Reader

for retry := 0; retry <= t.maxRetries; retry++ {
if err := req.Context().Err(); err != nil {
// Before the first attempt we still own the request body. Once
// sent, the underlying transport is responsible for closing it.
if retry == 0 && req.Body != nil {
_ = req.Body.Close()
}
return nil, err
}

// Reset the body
// Code from httpretry (https://github.com/ybbus/httpretry/blob/master/roundtripper.go#L60)
// if request provides GetBody() we use it as Body,
Expand Down Expand Up @@ -279,16 +288,37 @@ func (t *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
}

resp, err = t.transport.RoundTrip(req)
if resp != nil && !t.retryableErrors[resp.StatusCode] {
return resp, err
if err != nil {
// A RoundTripper must not return a response alongside an error,
// but discard it if one is returned so it cannot leak.
drainResponseBody(resp)
resp = nil
} else if !t.retryableErrors[resp.StatusCode] {
return resp, nil
}

time.Sleep(t.retryDelay)
if retry < t.maxRetries {
// Drain and close the intermediate response body before retrying,
// otherwise its connection and resources are leaked.
drainResponseBody(resp)
resp = nil
sleep(req.Context(), t.retryDelay)
}
}

return resp, err
}

// drainResponseBody reads up to 4KB and closes a discarded response body.
// Reaching EOF allows the underlying connection to be reused.
func drainResponseBody(resp *http.Response) {
if resp == nil || resp.Body == nil {
return
}
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024))
_ = resp.Body.Close()
}

// WithMaxRetries is used to set the max number of retries when encountering an error.
func WithMaxRetries(d int) RetryTransportOption {
return func(rt *RetryTransport) {
Expand Down
217 changes: 217 additions & 0 deletions github/transport_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"log"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -481,6 +482,222 @@ func TestRetryTransport_retry_post_success(t *testing.T) {
}
}

func TestRetryTransport_cancelled(t *testing.T) {
ts := githubApiMock([]*mockResponse{
{
ExpectedUri: "/repos/test/blah",
ResponseBody: `{
"message": "internal server error"
}`,
StatusCode: 500,
},
})
defer ts.Close()
client := mustCreateTestGitHubClient(t, ts.URL, github.WithTransport(NewRetryTransport(http.DefaultTransport,
WithMaxRetries(1),
WithRetryDelay(10*time.Second),
)))
ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond)
defer cancel()
start := time.Now()
_, _, err := client.Repositories.Get(ctx, "test", "blah")
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Expected context.DeadlineExceeded, got: %v", err)
}
if time.Since(start) > time.Second {
t.Fatalf("Waited longer than expected: %s", time.Since(start))
}
}

func TestRetryTransport_no_sleep_after_last_retry(t *testing.T) {
ts := githubApiMock([]*mockResponse{
{
ExpectedUri: "/repos/test/blah",
ResponseBody: `{
"message": "internal server error"
}`,
StatusCode: 500,
},
})
defer ts.Close()
client := mustCreateTestGitHubClient(t, ts.URL, github.WithTransport(NewRetryTransport(http.DefaultTransport,
WithMaxRetries(0),
WithRetryDelay(10*time.Second),
)))
start := time.Now()
ctx := context.WithValue(t.Context(), ctxId, t.Name())
_, _, _ = client.Repositories.Get(ctx, "test", "blah")
if time.Since(start) > time.Second {
t.Fatalf("Slept after last retry: %s", time.Since(start))
}
}

type recordingBody struct {
io.Reader
closed bool
reads int
closes int
}

func (b *recordingBody) Read(p []byte) (int, error) {
b.reads++
n, err := b.Reader.Read(p)
return n, err
}

func (b *recordingBody) Close() error {
b.closed = true
b.closes++
return nil
}

type staticTransport struct {
responses []*http.Response
errs []error
calls int
}

func (t *staticTransport) RoundTrip(*http.Request) (*http.Response, error) {
resp := t.responses[t.calls]
var err error
if t.errs != nil {
err = t.errs[t.calls]
}
t.calls++
return resp, err
}

func TestRetryTransport_closes_intermediate_response_bodies(t *testing.T) {
statuses := []int{500, 500, 200}
bodies := make([]*recordingBody, len(statuses))
responses := make([]*http.Response, len(statuses))
for i, status := range statuses {
bodies[i] = &recordingBody{Reader: strings.NewReader("{}")}
responses[i] = &http.Response{StatusCode: status, Body: bodies[i]}
}

rt := NewRetryTransport(&staticTransport{responses: responses},
WithMaxRetries(2),
WithRetryDelay(time.Millisecond),
)

resp, err := rt.RoundTrip(httptest.NewRequest(http.MethodGet, "http://example.com/", nil))
if err != nil {
t.Fatalf("Expected error to be nil, got: %v", err)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("Expected status %d, got: %d", http.StatusOK, resp.StatusCode)
}

for i, body := range bodies {
// The final response is owned by the caller, intermediate ones must be closed.
wantClosed := i < len(bodies)-1
if body.closed != wantClosed {
t.Fatalf("Response %d body closed = %t, want %t", i, body.closed, wantClosed)
}
}
}

func TestRetryTransport_closes_response_returned_with_error(t *testing.T) {
transportErr := errors.New("transport error")
firstBody := &recordingBody{Reader: strings.NewReader("{}")}
secondBody := &recordingBody{Reader: strings.NewReader("{}")}
rt := NewRetryTransport(&staticTransport{
responses: []*http.Response{
{StatusCode: http.StatusInternalServerError, Body: firstBody},
{StatusCode: http.StatusOK, Body: secondBody},
},
errs: []error{transportErr, nil},
},
WithMaxRetries(1),
WithRetryDelay(time.Millisecond),
)

resp, err := rt.RoundTrip(httptest.NewRequest(http.MethodGet, "http://example.com/", nil))
if err != nil {
t.Fatalf("Expected error to be nil, got: %v", err)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("Expected status %d, got: %d", http.StatusOK, resp.StatusCode)
}
if !firstBody.closed {
t.Fatal("Expected response body returned with an error to be closed")
}
if secondBody.closed {
t.Fatal("Expected final response body not to be closed")
}
}

type retryTestTransport func(*http.Request) (*http.Response, error)

func (f retryTestTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}

func TestRetryTransport_cancelled_request_body(t *testing.T) {
for _, kind := range []string{"nil", "no_body", "stream", "get_body"} {
t.Run(kind, func(t *testing.T) {
body := &recordingBody{Reader: strings.NewReader("request")}
req := httptest.NewRequest(http.MethodPost, "http://example.com/", nil)
switch kind {
case "nil":
req.Body = nil
case "no_body":
req.Body = http.NoBody
default:
req.Body = body
}
if kind == "get_body" {
req.GetBody = func() (io.ReadCloser, error) {
t.Fatal("GetBody called on a cancelled request")
return nil, nil
}
}
ctx, cancel := context.WithCancel(t.Context())
cancel()
req = req.WithContext(ctx)
rt := NewRetryTransport(retryTestTransport(func(*http.Request) (*http.Response, error) {
t.Fatal("Underlying transport called on a cancelled request")
return nil, nil
}), WithMaxRetries(1))

resp, err := rt.RoundTrip(req)
if resp != nil || !errors.Is(err, context.Canceled) {
t.Fatalf("Got (%v, %v), want (nil, context.Canceled)", resp, err)
}
if kind == "stream" || kind == "get_body" {
if body.closes != 1 || body.reads != 0 {
t.Fatalf("Body closes = %d, reads = %d; want 1, 0", body.closes, body.reads)
}
}
})
}
}

func TestRetryTransport_cancelled_after_attempt(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
body := &recordingBody{Reader: strings.NewReader("request")}
t.Cleanup(func() { _ = body.Close() })
req := httptest.NewRequest(http.MethodPost, "http://example.com/", nil).WithContext(ctx)
req.GetBody = func() (io.ReadCloser, error) { return body, nil }
calls := 0
rt := NewRetryTransport(retryTestTransport(func(*http.Request) (*http.Response, error) {
calls++
// The underlying transport may close the body asynchronously, after returning.
cancel()
return nil, context.Canceled
}), WithMaxRetries(1), WithRetryDelay(0))

resp, err := rt.RoundTrip(req)
if resp != nil || !errors.Is(err, context.Canceled) || calls != 1 {
t.Fatalf("Got (%v, %v), calls = %d; want (nil, context.Canceled), 1", resp, err, calls)
}
if body.closes != 0 || body.reads != 0 {
t.Fatalf("Sent body closes = %d, reads = %d; want 0, 0", body.closes, body.reads)
}
}

type mockResponse struct {
ExpectedUri string
ExpectedMethod string
Expand Down
Loading