forked from gojek/heimdall
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhystrix_client.go
213 lines (172 loc) · 5.58 KB
/
hystrix_client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package hystrix
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"time"
"github.com/afex/hystrix-go/hystrix"
"github.com/gojektech/heimdall"
"github.com/pkg/errors"
)
type fallbackFunc func(error) error
// Client is the hystrix client implementation
type Client struct {
client heimdall.Doer
timeout time.Duration
hystrixTimeout time.Duration
hystrixCommandName string
maxConcurrentRequests int
requestVolumeThreshold int
sleepWindow int
errorPercentThreshold int
retryCount int
retrier heimdall.Retriable
fallbackFunc func(err error) error
}
const (
defaultHystrixRetryCount = 0
defaultHTTPTimeout = 30 * time.Second
defaultHystriximeout = 30 * time.Second
defaultMaxConcurrentRequests = 100
defaultErrorPercentThreshold = 25
defaultSleepWindow = 10
defaultRequestVolumeThreshold = 10
maxUint = ^uint(0)
maxInt = int(maxUint >> 1)
)
var _ heimdall.Client = (*Client)(nil)
var err5xx = errors.New("server returned 5xx status code")
// NewClient returns a new instance of hystrix Client
func NewClient(opts ...Option) *Client {
client := Client{
timeout: defaultHTTPTimeout,
hystrixTimeout: defaultHystriximeout,
maxConcurrentRequests: defaultMaxConcurrentRequests,
errorPercentThreshold: defaultErrorPercentThreshold,
sleepWindow: defaultSleepWindow,
requestVolumeThreshold: defaultRequestVolumeThreshold,
retryCount: defaultHystrixRetryCount,
retrier: heimdall.NewNoRetrier(),
}
for _, opt := range opts {
opt(&client)
}
if client.client == nil {
client.client = &http.Client{
Timeout: client.timeout,
}
}
hystrix.ConfigureCommand(client.hystrixCommandName, hystrix.CommandConfig{
Timeout: durationToInt(client.hystrixTimeout, time.Millisecond),
MaxConcurrentRequests: client.maxConcurrentRequests,
RequestVolumeThreshold: client.requestVolumeThreshold,
SleepWindow: client.sleepWindow,
ErrorPercentThreshold: client.errorPercentThreshold,
})
return &client
}
func durationToInt(duration, unit time.Duration) int {
durationAsNumber := duration / unit
if int64(durationAsNumber) > int64(maxInt) {
// Returning max possible value seems like best possible solution here
// the alternative is to panic as there is no way of returning an error
// without changing the NewClient API
return maxInt
}
return int(durationAsNumber)
}
// Get makes a HTTP GET request to provided URL
func (hhc *Client) Get(url string, headers http.Header) (*http.Response, error) {
var response *http.Response
request, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return response, errors.Wrap(err, "GET - request creation failed")
}
request.Header = headers
return hhc.Do(request)
}
// Post makes a HTTP POST request to provided URL and requestBody
func (hhc *Client) Post(url string, body io.Reader, headers http.Header) (*http.Response, error) {
var response *http.Response
request, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return response, errors.Wrap(err, "POST - request creation failed")
}
request.Header = headers
return hhc.Do(request)
}
// Put makes a HTTP PUT request to provided URL and requestBody
func (hhc *Client) Put(url string, body io.Reader, headers http.Header) (*http.Response, error) {
var response *http.Response
request, err := http.NewRequest(http.MethodPut, url, body)
if err != nil {
return response, errors.Wrap(err, "PUT - request creation failed")
}
request.Header = headers
return hhc.Do(request)
}
// Patch makes a HTTP PATCH request to provided URL and requestBody
func (hhc *Client) Patch(url string, body io.Reader, headers http.Header) (*http.Response, error) {
var response *http.Response
request, err := http.NewRequest(http.MethodPatch, url, body)
if err != nil {
return response, errors.Wrap(err, "PATCH - request creation failed")
}
request.Header = headers
return hhc.Do(request)
}
// Delete makes a HTTP DELETE request with provided URL
func (hhc *Client) Delete(url string, headers http.Header) (*http.Response, error) {
var response *http.Response
request, err := http.NewRequest(http.MethodDelete, url, nil)
if err != nil {
return response, errors.Wrap(err, "DELETE - request creation failed")
}
request.Header = headers
return hhc.Do(request)
}
// Do makes an HTTP request with the native `http.Do` interface
func (hhc *Client) Do(request *http.Request) (*http.Response, error) {
var response *http.Response
var err error
var bodyReader *bytes.Reader
if request.Body != nil {
reqData, err := ioutil.ReadAll(request.Body)
if err != nil {
return nil, err
}
bodyReader = bytes.NewReader(reqData)
request.Body = ioutil.NopCloser(bodyReader) // prevents closing the body between retries
}
for i := 0; i <= hhc.retryCount; i++ {
if response != nil {
response.Body.Close()
}
err = hystrix.Do(hhc.hystrixCommandName, func() error {
response, err = hhc.client.Do(request)
if bodyReader != nil {
// Reset the body reader after the request since at this point it's already read
// Note that it's safe to ignore the error here since the 0,0 position is always valid
_, _ = bodyReader.Seek(0, 0)
}
if err != nil {
return err
}
if response.StatusCode >= http.StatusInternalServerError {
return err5xx
}
return nil
}, hhc.fallbackFunc)
if err != nil {
backoffTime := hhc.retrier.NextInterval(i)
time.Sleep(backoffTime)
continue
}
break
}
if err == err5xx {
return response, nil
}
return response, err
}