-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
309 lines (249 loc) · 6.98 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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2023-Present Datadog, Inc.
package cloudcraft
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/DataDog/cloudcraft-go/internal/endpoint"
"github.com/DataDog/cloudcraft-go/internal/meta"
"github.com/DataDog/cloudcraft-go/internal/xerrors"
"github.com/DataDog/cloudcraft-go/internal/xhttp"
)
const (
// ErrInvalidConfig is returned when a Client is created with an invalid
// Config.
ErrInvalidConfig xerrors.Error = "invalid config"
// ErrRequestFailed is returned when a request to the Cloudcraft API fails
// for unknown reasons.
ErrRequestFailed xerrors.Error = "request failed with status code"
// ErrMaxRetriesExceeded is returned when the maximum number of retries is
// exceeded for HTTP requests.
ErrMaxRetriesExceeded xerrors.Error = "maximum number of retries exceeded"
)
type (
// Service is a common struct that can be reused instead of allocating a new
// one for each service on the heap.
service struct {
client *Client
}
// Client is a client for the Cloudcraft API.
Client struct {
// httpClient is the underlying HTTP client used by the API client.
httpClient *http.Client
// retryPolicy specifies the policy used to retry failed requests.
retryPolicy *xhttp.RetryPolicy
// cfg specifies the configuration used by the API client.
cfg *Config
// Cloudcraft API service fields.
Azure *AzureService
AWS *AWSService
Blueprint *BlueprintService
Team *TeamService
User *UserService
// common specifies a common service shared by all services.
common service
}
)
// NewClient returns a new Client given a Config. If Config is nil, NewClient
// will try to look up the configuration from the environment.
func NewClient(cfg *Config) (*Client, error) {
if cfg == nil {
cfg = NewConfigFromEnv()
}
if err := cfg.Validate(); err != nil {
return nil, fmt.Errorf("%w: %w", ErrInvalidConfig, err)
}
baseURL, err := endpoint.Parse(cfg.Scheme, cfg.Host, cfg.Port, cfg.Path)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrInvalidConfig, err)
}
cfg.endpoint = baseURL
if cfg.MaxRetries <= 0 {
cfg.MaxRetries = DefaultMaxRetries
}
if cfg.Timeout <= 0 {
cfg.Timeout = DefaultTimeout
}
client := &Client{
httpClient: xhttp.NewClient(cfg.Timeout),
retryPolicy: &xhttp.RetryPolicy{
IsRetryable: xhttp.DefaultIsRetryable,
MaxRetries: cfg.MaxRetries,
MinRetryDelay: xhttp.DefaultMinRetryDelay,
MaxRetryDelay: xhttp.DefaultMaxRetryDelay,
},
cfg: cfg,
}
client.common.client = client
client.Azure = (*AzureService)(&client.common)
client.AWS = (*AWSService)(&client.common)
client.Blueprint = (*BlueprintService)(&client.common)
client.Team = (*TeamService)(&client.common)
client.User = (*UserService)(&client.common)
return client, nil
}
// SnapshotParams represents query parameters used to customize an Azure or AWS
// account snapshot.
type SnapshotParams struct {
PaperSize string
Projection string
Theme string
Filter []string
Exclude []string
Label bool
Autoconnect bool
Grid bool
Transparent bool
Landscape bool
Scale float32
Width int
Height int
}
// query builds a query string from fields with non-zero values and returns it
// as url.Values.
func (p *SnapshotParams) query() url.Values {
values := url.Values{}
if p.PaperSize != "" {
values.Set("paperSize", p.PaperSize)
}
if p.Projection != "" {
values.Set("projection", p.Projection)
}
if p.Theme != "" {
values.Set("theme", p.Theme)
}
if len(p.Filter) > 0 {
values.Set("filter", strings.Join(p.Filter, ","))
}
if len(p.Exclude) > 0 {
values.Set("exclude", strings.Join(p.Exclude, ","))
}
if p.Label {
values.Set("label", "true")
}
if p.Autoconnect {
values.Set("autoconnect", "true")
}
if p.Grid {
values.Set("grid", "true")
}
if p.Transparent {
values.Set("transparent", "true")
}
if p.Landscape {
values.Set("landscape", "true")
}
if p.Scale != 0 {
values.Set("scale", strconv.FormatFloat(float64(p.Scale), 'f', -1, 32))
}
if p.Width != 0 {
values.Set("width", strconv.Itoa(p.Width))
}
if p.Height != 0 {
values.Set("height", strconv.Itoa(p.Height))
}
return values
}
// Response represents a response from the Cloudcraft API.
type Response struct {
// Header contains the response headers.
Header http.Header
// Body contains the response body as a byte slice.
Body []byte
// Status is the HTTP status code of the response.
Status int
}
// do performs an HTTP request using the underlying HTTP client.
func (c *Client) do(req *http.Request) (*Response, error) { //nolint:gocyclo // Necessary complexity.
var (
attempt int
resp *http.Response
err error
body *bytes.Buffer
)
if req.Body != nil {
body = bytes.NewBuffer(make([]byte, 0))
_, err = io.Copy(body, req.Body)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
req.Body = io.NopCloser(body)
if err = req.Body.Close(); err != nil {
return nil, fmt.Errorf("%w", err)
}
}
for attempt = 0; attempt <= c.retryPolicy.MaxRetries; attempt++ {
if body != nil {
req.Body = io.NopCloser(bytes.NewReader(body.Bytes()))
}
resp, err = c.httpClient.Do(req)
if err != nil || !c.retryPolicy.IsRetryable(resp, err) {
break
}
if resp != nil {
if err = xhttp.DrainResponseBody(resp); err != nil {
_ = resp.Body.Close()
}
}
waitErr := c.retryPolicy.Wait(req.Context(), attempt)
if waitErr != nil {
return nil, fmt.Errorf("%w", waitErr)
}
}
if resp == nil && attempt >= c.retryPolicy.MaxRetries {
return nil, fmt.Errorf("%w: %d", ErrMaxRetriesExceeded, attempt)
}
if err != nil {
select {
case <-req.Context().Done():
return nil, fmt.Errorf("%w", req.Context().Err())
default:
return nil, fmt.Errorf("%w", err)
}
}
defer func() {
if err = xhttp.DrainResponseBody(resp); err != nil {
_ = resp.Body.Close()
}
}()
if resp.StatusCode > http.StatusNoContent {
return nil, fmt.Errorf("%w: %d", ErrRequestFailed, resp.StatusCode)
}
var buffer *bytes.Buffer
if resp.ContentLength > 0 {
buffer = bytes.NewBuffer(make([]byte, 0, resp.ContentLength))
} else {
buffer = bytes.NewBuffer(make([]byte, 0))
}
_, err = io.Copy(buffer, resp.Body)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
return &Response{
Header: resp.Header,
Body: buffer.Bytes(),
Status: resp.StatusCode,
}, nil
}
// request is a convenience function for creating an HTTP request.
func (c *Client) request(
ctx context.Context,
method, uri string,
body io.Reader,
) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, method, uri, body)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+c.cfg.Key)
req.Header.Set("User-Agent", meta.UserAgent)
return req, nil
}