-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.go
More file actions
273 lines (232 loc) · 6.8 KB
/
client.go
File metadata and controls
273 lines (232 loc) · 6.8 KB
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// Package client implements a client for a build service
package client
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"time"
"github.com/grafana/k6build"
"github.com/grafana/k6build/pkg/api"
)
// ErrInvalidConfiguration signals an error in the configuration
var ErrInvalidConfiguration = errors.New("invalid configuration")
const (
defaultAuthType = "Bearer"
buildPath = "build"
resolvePath = "resolve"
// DefaultRetries number of retries for requests
DefaultRetries = 3
// DefaultBackoff initial backoff time between retries. It is incremented exponentially between retries.
DefaultBackoff = 1 * time.Second
)
// BuildServiceClientConfig defines the configuration for accessing a remote build service
type BuildServiceClientConfig struct {
// URL to build service
URL string
// Authorization credentials passed in the Authorization: <type> <credentials> header
// See AuthorizationType
Authorization string
// AuthorizationType type of credentials in the Authorization: <type> <credentials> header
// For example, "Bearer", "Token", "Basic". Defaults to "Bearer"
AuthorizationType string
// Headers custom request headers
Headers map[string]string
// HTTPClient custom http client
HTTPClient *http.Client
// Retries number of retries for requests. Default to 3
Retries int
// Backoff initial backoff time between retries. Default to 1s
// It is incremented exponentially between retries: 1s, 2s, 4s...
Backoff time.Duration
}
// NewBuildServiceClient returns a new client for a remote build service
func NewBuildServiceClient(config BuildServiceClientConfig) (k6build.BuildService, error) {
if config.URL == "" {
return nil, ErrInvalidConfiguration
}
srvURL, err := url.Parse(config.URL)
if err != nil {
return nil, fmt.Errorf("invalid server %w", err)
}
client := config.HTTPClient
if client == nil {
client = http.DefaultClient
}
return &BuildClient{
srvURL: srvURL,
auth: config.Authorization,
authType: config.AuthorizationType,
headers: config.Headers,
client: client,
retries: config.Retries,
backoff: config.Backoff,
}, nil
}
// BuildClient defines a client of a build service
type BuildClient struct {
srvURL *url.URL
authType string
auth string
headers map[string]string
client *http.Client
retries int
backoff time.Duration
}
// Build request building an artifact to a build service
// The build service is expected to return a k6build.Artifact
// In case of error, the returned error is expected to match any of the errors
// defined in the api package and calling errors.Unwrap(err) will provide
// the cause, if available.
func (r *BuildClient) Build(
ctx context.Context,
platform string,
k6Constrains string,
deps []k6build.Dependency,
) (k6build.Artifact, error) {
buildRequest := api.BuildRequest{
Platform: platform,
K6Constrains: k6Constrains,
Dependencies: deps,
}
buildResponse := api.BuildResponse{}
err := r.doRequest(ctx, buildPath, &buildRequest, &buildResponse)
if err != nil {
if buildResponse.Error != nil {
return k6build.Artifact{}, buildResponse.Error
}
return k6build.Artifact{}, err
}
if buildResponse.Error != nil {
return k6build.Artifact{}, buildResponse.Error
}
return buildResponse.Artifact, nil
}
// Resolve returns the versions that satisfy the given dependencies or an error if they cannot be
// satisfied
func (r *BuildClient) Resolve(
ctx context.Context,
k6Constrains string,
deps []k6build.Dependency,
) (map[string]string, error) {
resolveRequest := api.ResolveRequest{
K6Constrains: k6Constrains,
Dependencies: deps,
}
resolveResponse := api.ResolveResponse{}
err := r.doRequest(ctx, resolvePath, &resolveRequest, &resolveResponse)
if err != nil {
if resolveResponse.Error != nil {
return nil, resolveResponse.Error
}
return nil, err
}
if resolveResponse.Error != nil {
return nil, resolveResponse.Error
}
return resolveResponse.Dependencies, nil
}
//nolint:funlen // TODO: consider refactoring
func (r *BuildClient) doRequest(ctx context.Context, path string, request any, response any) error {
marshaled := &bytes.Buffer{}
err := json.NewEncoder(marshaled).Encode(request)
if err != nil {
return k6build.NewWrappedError(api.ErrInvalidRequest, err)
}
reqURL := r.srvURL.JoinPath(path)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL.String(), marshaled)
if err != nil {
return k6build.NewWrappedError(api.ErrRequestFailed, err)
}
req.Header.Add("Content-Type", "application/json")
// add authorization header "Authorization: <type> <auth>"
if r.auth != "" {
authType := r.authType
if authType == "" {
authType = defaultAuthType
}
req.Header.Add("Authorization", fmt.Sprintf("%s %s", authType, r.auth))
}
// add custom headers
for h, v := range r.headers {
req.Header.Add(h, v)
}
var (
resp *http.Response
backoff = r.backoff
retries = r.retries
)
if retries == 0 {
retries = DefaultRetries
}
if backoff == 0 {
backoff = DefaultBackoff
}
// preserve body for retries
body, err := io.ReadAll(req.Body)
if err != nil {
return k6build.NewWrappedError(api.ErrRequestFailed, err)
}
// close the original body, we don't need it anymore
err = req.Body.Close()
if err != nil {
return k6build.NewWrappedError(api.ErrRequestFailed, err)
}
// try at least once
for {
req.Body = io.NopCloser(bytes.NewReader(body)) // reset the body
resp, err = r.client.Do(req)
if retries == 0 || !shouldRetry(err, resp) {
break
}
time.Sleep(backoff)
// increase backoff exponentially for next retry
backoff *= 2
retries--
}
if err != nil {
return k6build.NewWrappedError(api.ErrRequestFailed, err)
}
defer func() {
_ = resp.Body.Close()
}()
switch resp.StatusCode {
case http.StatusOK:
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
return k6build.NewWrappedError(api.ErrRequestFailed, err)
}
case http.StatusInternalServerError:
// try to decode response, it should be there, but don't report error if not
_ = json.NewDecoder(resp.Body).Decode(&response)
return k6build.NewWrappedError(api.ErrRequestFailed, errors.New(resp.Status))
default:
// don't even try to decode response
return k6build.NewWrappedError(api.ErrRequestFailed, errors.New(resp.Status))
}
return nil
}
// shouldRetry returns true if the error or response indicates that the request should be retried
func shouldRetry(err error, resp *http.Response) bool {
if err != nil {
if errors.Is(err, io.EOF) { // assuming EOF is due to connection interrupted by network error
return true
}
var ne net.Error
if errors.As(err, &ne) {
return ne.Timeout()
}
return false
}
if resp.StatusCode == http.StatusServiceUnavailable ||
resp.StatusCode == http.StatusBadGateway ||
resp.StatusCode == http.StatusGatewayTimeout {
return true
}
return false
}