Skip to content

Commit db8541d

Browse files
authored
Retry on timeout, when server doesn't respond (#1161)
* Retry on timeout, when server doesn't respond Signed-off-by: Romain Philibert <[email protected]> * update comment Signed-off-by: Romain <[email protected]> --------- Signed-off-by: Romain Philibert <[email protected]> Signed-off-by: Romain <[email protected]>
1 parent 423f5e3 commit db8541d

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

keycloak/keycloak_client.go

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,30 @@ func (keycloakClient *KeycloakClient) marshal(body interface{}) ([]byte, error)
499499
return json.Marshal(body)
500500
}
501501

502+
func RetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error) {
503+
// do retry on context.Canceled or context.DeadlineExceeded
504+
if ctx.Err() != nil {
505+
return true, ctx.Err()
506+
}
507+
508+
// 429 Too Many Requests is recoverable. Sometimes the server puts
509+
// a Retry-After response header to indicate when the server is
510+
// available to start processing request from client.
511+
if resp.StatusCode == http.StatusTooManyRequests {
512+
return true, nil
513+
}
514+
515+
// Check the response code. We retry on 500-range responses to allow
516+
// the server time to recover, as 500's are typically not permanent
517+
// errors and may relate to outages on the server side. This will catch
518+
// invalid response codes as well, like 0 and 999.
519+
if resp.StatusCode == 0 || (resp.StatusCode >= 500 && resp.StatusCode != http.StatusNotImplemented) {
520+
return true, nil
521+
}
522+
523+
return false, nil
524+
}
525+
502526
func newHttpClient(tlsInsecureSkipVerify bool, clientTimeout int, caCert string) (*http.Client, error) {
503527
cookieJar, err := cookiejar.New(&cookiejar.Options{
504528
PublicSuffixList: publicsuffix.List,
@@ -519,9 +543,10 @@ func newHttpClient(tlsInsecureSkipVerify bool, clientTimeout int, caCert string)
519543
}
520544

521545
retryClient := retryablehttp.NewClient()
522-
retryClient.RetryMax = 1
546+
retryClient.CheckRetry = RetryPolicy
547+
retryClient.RetryMax = 5
523548
retryClient.RetryWaitMin = time.Second * 1
524-
retryClient.RetryWaitMax = time.Second * 3
549+
retryClient.RetryWaitMax = time.Second * 60
525550

526551
httpClient := retryClient.StandardClient()
527552
httpClient.Timeout = time.Second * time.Duration(clientTimeout)

0 commit comments

Comments
 (0)