Skip to content

Commit

Permalink
configure max attempts
Browse files Browse the repository at this point in the history
  • Loading branch information
jooola committed Jul 9, 2024
1 parent b422fe8 commit 3d0e854
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 10 deletions.
16 changes: 9 additions & 7 deletions hcloud/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ type Client struct {
endpoint string
token string
tokenValid bool
backoffFunc BackoffFunc
retryBackoffFunc BackoffFunc
retryMaxAttempts int
pollBackoffFunc BackoffFunc
httpClient *http.Client
applicationName string
Expand Down Expand Up @@ -131,7 +132,7 @@ func WithPollBackoffFunc(f BackoffFunc) ClientOption {
// The backoff function is used for retrying HTTP requests.
func WithBackoffFunc(f BackoffFunc) ClientOption {
return func(client *Client) {
client.backoffFunc = f
client.retryBackoffFunc = f
}
}

Expand Down Expand Up @@ -170,11 +171,12 @@ func WithInstrumentation(registry prometheus.Registerer) ClientOption {
// NewClient creates a new client.
func NewClient(options ...ClientOption) *Client {
client := &Client{
endpoint: Endpoint,
tokenValid: true,
httpClient: &http.Client{},
backoffFunc: ExponentialBackoff(2, 500*time.Millisecond),
pollBackoffFunc: ConstantBackoff(500 * time.Millisecond),
endpoint: Endpoint,
tokenValid: true,
httpClient: &http.Client{},
retryBackoffFunc: ExponentialBackoff(2, time.Second),
retryMaxAttempts: 5, // 1s + 2s + 4s + 8s + 16s = 31s
pollBackoffFunc: ConstantBackoff(500 * time.Millisecond),
}

for _, option := range options {
Expand Down
2 changes: 1 addition & 1 deletion hcloud/client_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func assembleHandlerChain(client *Client) handler {
h = wrapErrorHandler(h)

// Retry request if condition are met
h = wrapRetryHandler(h, client.backoffFunc)
h = wrapRetryHandler(h, client.retryBackoffFunc, client.retryMaxAttempts)

// Finally parse the response body into the provided schema
h = wrapParseHandler(h)
Expand Down
2 changes: 1 addition & 1 deletion hcloud/client_handler_retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func retryPolicy(resp *Response, err error) bool {

switch {
case errors.As(err, &apiErr):
switch apiErr.Code {
switch apiErr.Code { //nolint:exhaustive
case ErrorCodeConflict, ErrorCodeLocked:
return true
case ErrorCodeRateLimitExceeded:
Expand Down
2 changes: 1 addition & 1 deletion hcloud/client_handler_retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func TestRetryHandler(t *testing.T) {

retryCount++
return 0
})
}, 5)

client := NewClient(WithToken("dummy"))
req, err := client.NewRequest(context.Background(), "GET", "/", nil)
Expand Down

0 comments on commit 3d0e854

Please sign in to comment.