-
Notifications
You must be signed in to change notification settings - Fork 363
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
Improve Retry Logic to Only Retry on Server-Side HTTP Errors #1390
Open
VishalGawade1
wants to merge
11
commits into
google:main
Choose a base branch
from
VishalGawade1:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
d8d00bc
Adding error handling for status code 5xx
VishalGawade1 55f448a
resolving merge conflict in go.mod
VishalGawade1 c91540b
updating osv.go comment for handling 200 inside makeRetryRequest
VishalGawade1 03db161
refactor: use standard library for test assertions
VishalGawade1 a30e28e
fix: correct makeRetryRequest retry logic and update tests
VishalGawade1 e297913
Removing the QueryEndpoint Override from test
VishalGawade1 8c369d6
Added error handling in makeRetryRequest, removed redundant function…
VishalGawade1 e81d59d
removed unused dependency in go.mod, reverted constants to original f…
VishalGawade1 f8676b7
Merge branch 'main' into main
VishalGawade1 4fa1286
Merge branch 'main' into main
VishalGawade1 a1a3e93
Adding error handling for status code 429
VishalGawade1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -156,21 +156,6 @@ | |
return append(chunks, items) | ||
} | ||
|
||
// checkResponseError checks if the response has an error. | ||
func checkResponseError(resp *http.Response) error { | ||
if resp.StatusCode == http.StatusOK { | ||
return nil | ||
} | ||
|
||
respBuf, err := io.ReadAll(resp.Body) | ||
if err != nil { | ||
return fmt.Errorf("failed to read error response from server: %w", err) | ||
} | ||
defer resp.Body.Close() | ||
|
||
return fmt.Errorf("server response error: %s", string(respBuf)) | ||
} | ||
|
||
// MakeRequest sends a batched query to osv.dev | ||
func MakeRequest(request BatchedQuery) (*BatchedResponse, error) { | ||
return MakeRequestWithClient(request, http.DefaultClient) | ||
|
@@ -306,10 +291,9 @@ | |
return &hydrated, nil | ||
} | ||
|
||
// makeRetryRequest will return an error on both network errors, and if the response is not 200 | ||
// makeRetryRequest executes HTTP requests with exponential backoff retry logic | ||
func makeRetryRequest(action func() (*http.Response, error)) (*http.Response, error) { | ||
var resp *http.Response | ||
var err error | ||
var lastErr error | ||
|
||
for i := range maxRetryAttempts { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. issue: I think you've changed this loop more than you need to
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah, you were right. Sorry for removing Jitter in the function. Added back! |
||
// rand is initialized with a random number (since go1.20), and is also safe to use concurrently | ||
|
@@ -318,17 +302,36 @@ | |
jitterAmount := (rand.Float64() * float64(jitterMultiplier) * float64(i)) | ||
time.Sleep(time.Duration(i*i)*time.Second + time.Duration(jitterAmount*1000)*time.Millisecond) | ||
|
||
resp, err = action() | ||
if err == nil { | ||
// Check the response for HTTP errors | ||
err = checkResponseError(resp) | ||
if err == nil { | ||
break | ||
} | ||
resp, err := action() | ||
if err != nil { | ||
lastErr = fmt.Errorf("attempt %d: request failed: %w", i+1, err) | ||
continue | ||
} | ||
|
||
if resp.StatusCode >= 200 && resp.StatusCode < 300 { | ||
return resp, nil | ||
} | ||
|
||
body, err := io.ReadAll(resp.Body) | ||
resp.Body.Close() | ||
if err != nil { | ||
lastErr = fmt.Errorf("attempt %d: failed to read response: %w", i+1, err) | ||
continue | ||
} | ||
|
||
if resp.StatusCode == 429 { | ||
lastErr = fmt.Errorf("attempt %d: too many requests: status=%d body=%s", i+1, resp.StatusCode, body) | ||
continue | ||
} | ||
|
||
if resp.StatusCode >= 400 && resp.StatusCode < 500 { | ||
another-rex marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return nil, fmt.Errorf("client error: status=%d body=%s", resp.StatusCode, body) | ||
} | ||
|
||
lastErr = fmt.Errorf("server error: status=%d body=%s", resp.StatusCode, body) | ||
} | ||
|
||
return resp, err | ||
return nil, fmt.Errorf("max retries exceeded: %w", lastErr) | ||
} | ||
|
||
func MakeDetermineVersionRequest(name string, hashes []DetermineVersionHash) (*DetermineVersionResponse, error) { | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
package osv | ||
|
||
import ( | ||
"fmt" | ||
"io" | ||
"net/http" | ||
"net/http/httptest" | ||
"strings" | ||
"testing" | ||
"time" | ||
) | ||
|
||
func TestMakeRetryRequest(t *testing.T) { | ||
t.Parallel() | ||
|
||
tests := []struct { | ||
name string | ||
statusCodes []int | ||
expectedError string | ||
wantAttempts int | ||
}{ | ||
{ | ||
name: "success on first attempt", | ||
statusCodes: []int{http.StatusOK}, | ||
wantAttempts: 1, | ||
}, | ||
{ | ||
name: "client error no retry", | ||
statusCodes: []int{http.StatusBadRequest}, | ||
expectedError: "client error: status=400", | ||
wantAttempts: 1, | ||
}, | ||
{ | ||
name: "server error then success", | ||
statusCodes: []int{http.StatusInternalServerError, http.StatusOK}, | ||
wantAttempts: 2, | ||
}, | ||
{ | ||
name: "max retries on server error", | ||
statusCodes: []int{http.StatusInternalServerError, http.StatusInternalServerError, http.StatusInternalServerError, http.StatusInternalServerError}, | ||
expectedError: "max retries exceeded", | ||
wantAttempts: 4, | ||
}, | ||
} | ||
|
||
for _, tt := range tests { | ||
tt := tt | ||
t.Run(tt.name, func(t *testing.T) { | ||
t.Parallel() | ||
|
||
attempts := 0 | ||
idx := 0 | ||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
attempts++ | ||
status := tt.statusCodes[idx] | ||
if idx < len(tt.statusCodes)-1 { | ||
idx++ | ||
} | ||
|
||
w.WriteHeader(status) | ||
message := fmt.Sprintf("response-%d", attempts) | ||
w.Write([]byte(message)) | ||
})) | ||
defer server.Close() | ||
|
||
client := &http.Client{Timeout: time.Second} | ||
|
||
resp, err := makeRetryRequest(func() (*http.Response, error) { | ||
return client.Get(server.URL) | ||
}) | ||
|
||
if attempts != tt.wantAttempts { | ||
t.Errorf("got %d attempts, want %d", attempts, tt.wantAttempts) | ||
} | ||
|
||
if tt.expectedError != "" { | ||
if err == nil { | ||
t.Fatalf("expected error containing %q, got nil", tt.expectedError) | ||
} | ||
if !strings.Contains(err.Error(), tt.expectedError) { | ||
t.Errorf("expected error containing %q, got %q", tt.expectedError, err) | ||
} | ||
return | ||
} | ||
|
||
if err != nil { | ||
t.Fatalf("unexpected error: %v", err) | ||
} | ||
|
||
if resp == nil { | ||
t.Fatal("expected non-nil response") | ||
} | ||
defer resp.Body.Close() | ||
|
||
body, err := io.ReadAll(resp.Body) | ||
if err != nil { | ||
t.Fatalf("failed to read response body: %v", err) | ||
} | ||
|
||
expectedBody := fmt.Sprintf("response-%d", attempts) | ||
if string(body) != expectedBody { | ||
t.Errorf("got body %q, want %q", string(body), expectedBody) | ||
} | ||
}) | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
issue: this needs to be reverted
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I ran the
scripts/run_lints.sh
script, and the only issues flagged were spacing warnings outside of the code I wrote. Let me know if you'd like me to address those too.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you run
go mod tidy
, which should remove these extra additions.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
friendly ping to run go mod tidy again here :)