From 2735b134c25f28ca0e7ed83661260652acd907e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gergely=20Nov=C3=A1k?= Date: Wed, 15 Feb 2023 16:27:58 +0100 Subject: [PATCH] Retry on internal server errors (#242) --- marketdata/rest.go | 8 ++++++-- marketdata/rest_test.go | 11 +++++++---- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/marketdata/rest.go b/marketdata/rest.go index 76a5aad..2d6aacf 100644 --- a/marketdata/rest.go +++ b/marketdata/rest.go @@ -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 diff --git a/marketdata/rest_test.go b/marketdata/rest_test.go index 7067c25..37d03f3 100644 --- a/marketdata/rest_test.go +++ b/marketdata/rest_test.go @@ -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) @@ -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}}}`) } @@ -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)