Skip to content

Commit

Permalink
Setting timeout on retryclient http client (#149)
Browse files Browse the repository at this point in the history
  • Loading branch information
bendbennett committed Feb 2, 2023
1 parent ee6b971 commit 627dc13
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 16 deletions.
23 changes: 10 additions & 13 deletions internal/provider/data_source_http.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,15 +236,9 @@ func (d *httpDataSource) Read(ctx context.Context, req datasource.ReadRequest, r

timeout := model.RequestTimeout

var cancel context.CancelFunc

if !timeout.IsNull() {
ctx, cancel = context.WithTimeout(ctx, time.Duration(timeout.ValueInt64())*time.Millisecond)
defer cancel()
}

retryClient := retryablehttp.NewClient()
retryClient.HTTPClient.Transport = clonedTr
retryClient.HTTPClient.Timeout = time.Duration(timeout.ValueInt64()) * time.Millisecond
retryClient.Logger = levelledLogger{ctx}
retryClient.RetryMax = int(retry.Attempts.ValueInt64())
retryClient.CheckRetry = func(ctx context.Context, resp *http.Response, err error) (bool, error) {
Expand Down Expand Up @@ -277,12 +271,15 @@ func (d *httpDataSource) Read(ctx context.Context, req datasource.ReadRequest, r

response, err := retryClient.Do(request)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
resp.Diagnostics.AddError(
"Error making request",
fmt.Sprintf("The request exceeded the specified timeout: %d ms", timeout.ValueInt64()),
)
return
target := &url.Error{}
if errors.As(err, &target) {
if target.Timeout() {
resp.Diagnostics.AddError(
"Error making request",
fmt.Sprintf("%s: request exceeded the specified timeout: %d ms", err, timeout.ValueInt64()),
)
return
}
}

resp.Diagnostics.AddError(
Expand Down
5 changes: 2 additions & 3 deletions internal/provider/data_source_http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -501,8 +501,7 @@ func TestDataSource_InsecureFalse(t *testing.T) {
ExpectError: regexp.MustCompile(
fmt.Sprintf(
"Error making request: GET %s giving up after 1\n"+
"attempt\\(s\\): request generated error: Get\n"+
"\"%s\": x509:",
"attempt\\(s\\): request generated error: Get \"%s\": x509:",
testServer.URL,
testServer.URL,
),
Expand Down Expand Up @@ -634,7 +633,7 @@ func TestDataSource_Timeout(t *testing.T) {
url = "%s"
request_timeout = 5
}`, svr.URL),
ExpectError: regexp.MustCompile(`The request exceeded the specified timeout: 5 ms`),
ExpectError: regexp.MustCompile(`request exceeded the\nspecified timeout: 5 ms`),
},
},
})
Expand Down

0 comments on commit 627dc13

Please sign in to comment.