forked from grafana/k6
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
238 lines (196 loc) · 4.95 KB
/
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package cloudapi
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
"github.com/sirupsen/logrus"
)
const (
// RetryInterval is the default cloud request retry interval
RetryInterval = 500 * time.Millisecond
// MaxRetries specifies max retry attempts
MaxRetries = 3
k6IdempotencyKeyHeader = "K6-Idempotency-Key"
)
// Client handles communication with the k6 Cloud API.
type Client struct {
client *http.Client
token string
baseURL string
version string
logger logrus.FieldLogger
retries int
retryInterval time.Duration
}
// NewClient return a new client for the cloud API
func NewClient(logger logrus.FieldLogger, token, host, version string, timeout time.Duration) *Client {
c := &Client{
client: &http.Client{Timeout: timeout},
token: token,
baseURL: fmt.Sprintf("%s/v1", host),
version: version,
retries: MaxRetries,
retryInterval: RetryInterval,
logger: logger,
}
return c
}
// BaseURL returns configured host.
func (c *Client) BaseURL() string {
return c.baseURL
}
// NewRequest creates new HTTP request.
//
// This is the same as http.NewRequest, except that data if not nil
// will be serialized in json format.
func (c *Client) NewRequest(method, url string, data interface{}) (*http.Request, error) {
var buf io.Reader
if data != nil {
b, err := json.Marshal(&data)
if err != nil {
return nil, err
}
buf = bytes.NewBuffer(b)
}
req, err := http.NewRequest(method, url, buf) //nolint:noctx // the user can add this
if err != nil {
return nil, err
}
return req, nil
}
// Do is simpler to http.Do but also unmarshals the response in the provided v
func (c *Client) Do(req *http.Request, v interface{}) error {
if req.Body != nil && req.GetBody == nil {
originalBody, err := io.ReadAll(req.Body)
if err != nil {
return err
}
if err = req.Body.Close(); err != nil {
return err
}
req.GetBody = func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(originalBody)), nil
}
req.Body, _ = req.GetBody()
}
// TODO(cuonglm): finding away to move this back to NewRequest
c.prepareHeaders(req)
for i := 1; i <= c.retries; i++ {
retry, err := c.do(req, v, i)
if retry {
time.Sleep(c.retryInterval)
if req.GetBody != nil {
req.Body, _ = req.GetBody()
}
continue
}
return err
}
return nil
}
func (c *Client) prepareHeaders(req *http.Request) {
if req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", "application/json")
}
if c.token != "" {
req.Header.Set("Authorization", fmt.Sprintf("Token %s", c.token))
}
if shouldAddIdempotencyKey(req) {
req.Header.Set(k6IdempotencyKeyHeader, randomStrHex())
}
req.Header.Set("User-Agent", "k6cloud/"+c.version)
}
func (c *Client) do(req *http.Request, v interface{}, attempt int) (retry bool, err error) {
resp, err := c.client.Do(req)
defer func() {
if resp != nil {
_, _ = io.Copy(io.Discard, resp.Body)
if cerr := resp.Body.Close(); cerr != nil && err == nil {
err = cerr
}
}
}()
if shouldRetry(resp, err, attempt, c.retries) {
return true, err
}
if err != nil {
return false, err
}
if err = CheckResponse(resp); err != nil {
return false, err
}
if v != nil {
if err = json.NewDecoder(resp.Body).Decode(v); errors.Is(err, io.EOF) {
err = nil // Ignore EOF from empty body
}
}
return false, err
}
// CheckResponse checks the parsed response.
// It returns nil if the code is in the successful range,
// otherwise it tries to parse the body and return a parsed error.
func CheckResponse(r *http.Response) error {
if r == nil {
return errUnknown
}
if c := r.StatusCode; c >= 200 && c <= 299 {
return nil
}
data, err := io.ReadAll(r.Body)
if err != nil {
return err
}
var payload struct {
Error ResponseError `json:"error"`
}
if err := json.Unmarshal(data, &payload); err != nil {
if r.StatusCode == http.StatusUnauthorized {
return errNotAuthenticated
}
if r.StatusCode == http.StatusForbidden {
return errNotAuthorized
}
return fmt.Errorf(
"unexpected HTTP error from %s: %d %s",
r.Request.URL,
r.StatusCode,
http.StatusText(r.StatusCode),
)
}
payload.Error.Response = r
return payload.Error
}
func shouldRetry(resp *http.Response, err error, attempt, maxAttempts int) bool {
if attempt >= maxAttempts {
return false
}
if resp == nil || err != nil {
return true
}
if resp.StatusCode >= 500 || resp.StatusCode == http.StatusTooManyRequests {
return true
}
return false
}
func shouldAddIdempotencyKey(req *http.Request) bool {
switch req.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace:
return false
default:
return req.Header.Get(k6IdempotencyKeyHeader) == ""
}
}
// randomStrHex returns a hex string which can be used
// for session token id or idempotency key.
func randomStrHex() string {
// 16 hex characters
b := make([]byte, 8)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}