Skip to content

Commit

Permalink
Retry on internal server errors (#242)
Browse files Browse the repository at this point in the history
  • Loading branch information
gnvk authored Feb 15, 2023
1 parent 3e20b11 commit 2735b13
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
8 changes: 6 additions & 2 deletions marketdata/rest.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,13 +97,17 @@ func defaultDo(c *Client, req *http.Request) (*http.Response, error) {

var resp *http.Response
var err error

RetryLoop:
for i := 0; ; i++ {
resp, err = c.httpClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusTooManyRequests {
break
switch resp.StatusCode {
case http.StatusTooManyRequests, http.StatusInternalServerError:
default:
break RetryLoop
}
if i >= c.opts.RetryLimit {
break
Expand Down
11 changes: 7 additions & 4 deletions marketdata/rest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ func TestDefaultDo_InternalServerError(t *testing.T) {
defer func() { os.Setenv("APCA_API_DATA_URL", originalDataURL) }()
require.NoError(t, os.Setenv("APCA_API_DATA_URL", server.URL))
client := NewClient(ClientOpts{
OAuth: "myoauthkey",
OAuth: "myoauthkey",
RetryDelay: time.Nanosecond,
})
_, err := client.GetLatestBar("SPY", GetLatestBarRequest{})
require.Error(t, err)
Expand All @@ -49,8 +50,10 @@ func TestDefaultDo_Retry(t *testing.T) {
tryCount := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch tryCount {
case 0:
case 0, 2:
http.Error(w, "too many requests", http.StatusTooManyRequests)
case 1:
http.Error(w, "internal server error occurred", http.StatusInternalServerError)
default:
fmt.Fprint(w, `{"bars":{"SPY":{"t":"2021-11-20T00:59:00Z","o":469.18,"h":469.18,"l":469.11,"c":469.17,"v":740,"n":11,"vw":469.1355}}}`)
}
Expand All @@ -59,8 +62,8 @@ func TestDefaultDo_Retry(t *testing.T) {
defer server.Close()
client := NewClient(ClientOpts{
BaseURL: server.URL,
RetryDelay: time.Millisecond,
RetryLimit: 1,
RetryDelay: time.Nanosecond,
RetryLimit: 5,
})
bar, err := client.GetLatestBar("SPY", GetLatestBarRequest{})
require.NoError(t, err)
Expand Down

0 comments on commit 2735b13

Please sign in to comment.