/
client.go
263 lines (217 loc) · 5.62 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
// Package client provides a client over the REST HTTP API of Calyptia Cloud.
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"github.com/peterhellberg/link"
"gopkg.in/yaml.v2"
"github.com/calyptia/api/types"
)
const (
// DefaultBaseURL of the API.
DefaultBaseURL = "https://cloud-api.calyptia.com"
uintBase = 10
CalyptiaEnvAPIURL = "CALYPTIA_API_URL"
//nolint: gosec // no credential leaks just a variable.
CalyptiaEnvAPIToken = "CALYPTIA_API_TOKEN"
)
// Client is the client over the REST HTTP API of Calyptia Cloud.
type Client struct {
BaseURL string
// Tip: Use oauth2.NewClient(context.Context, *oauth2.TokenSource)
Client *http.Client
userAgent string
projectToken string
agentToken string
coreInstanceToken string
}
// New default client.
func New() *Client {
return &Client{
BaseURL: DefaultBaseURL,
Client: http.DefaultClient,
}
}
// NewFromEnv creates a new client using default environment variables.
func NewFromEnv() *Client {
c := New()
// Update the BaseURL if environment variable is set
if apiURL := os.Getenv(CalyptiaEnvAPIURL); apiURL != "" {
c.BaseURL = apiURL
}
// Set the ProjectToken if environment variable is set
if token := os.Getenv(CalyptiaEnvAPIToken); token != "" {
c.SetProjectToken(token)
}
return c
}
// SetUserAgent sets the "User-Agent" header of the client.
func (c *Client) SetUserAgent(s string) {
c.userAgent = s
}
// SetProjectToken sets the "X-Project-Token" header of the client.
func (c *Client) SetProjectToken(s string) {
c.projectToken = s
}
// SetAgentToken sets the "X-Agent-Token" header of the client.
func (c *Client) SetAgentToken(s string) {
c.agentToken = s
}
// SetCoreInstanceToken sets the "X-Aggregator-Token" header of the client.
func (c *Client) SetCoreInstanceToken(s string) {
c.coreInstanceToken = s
}
func (c *Client) setRequestHeaders(req *http.Request) {
if c.projectToken != "" {
req.Header.Set("X-Project-Token", c.projectToken)
}
if c.agentToken != "" {
req.Header.Set("X-Agent-Token", c.agentToken)
}
if c.coreInstanceToken != "" {
req.Header.Set("X-Aggregator-Token", c.coreInstanceToken)
}
if c.userAgent != "" {
req.Header.Set("User-Agent", c.userAgent)
}
}
func decodeResponse(resp *http.Response, dest interface{}) error {
var err error
switch resp.Header.Get("Content-Type") {
default:
fallthrough
case "application/json":
err = json.NewDecoder(resp.Body).Decode(dest)
if err != nil {
return fmt.Errorf("could not json decode response: %w", err)
}
case "application/yaml":
err = yaml.NewDecoder(resp.Body).Decode(dest)
if err != nil {
return fmt.Errorf("could not yaml decode response: %w", err)
}
case "text/plain":
strp, ok := dest.(*string)
if !ok {
return fmt.Errorf("must decode plain text response into string")
}
r, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("read response body text: %w", err)
}
*strp = string(r)
}
return nil
}
func (c *Client) do(ctx context.Context, method, path string, v, dest interface{}, oo ...opt) error {
var options opts
for _, o := range oo {
o(&options)
}
var body io.Reader
if b, ok := v.(io.Reader); ok {
body = b
} else if b, ok := v.([]byte); ok {
body = bytes.NewReader(b)
} else if v != nil {
b, err := json.Marshal(v)
if err != nil {
return err
}
body = bytes.NewReader(b)
}
endpoint := strings.TrimSuffix(c.BaseURL, "/") + path
req, err := http.NewRequestWithContext(ctx, method, endpoint, body)
if err != nil {
return err
}
if body != nil {
req.Header.Set("Content-Type", "application/json; charset=utf-8")
}
c.setRequestHeaders(req)
resp, err := c.Client.Do(req)
if err != nil {
return err
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode >= http.StatusBadRequest {
e := &types.Error{}
err = json.NewDecoder(resp.Body).Decode(&e)
if err != nil {
return fmt.Errorf("could not json decode error response: status_code=%d: %w", resp.StatusCode, err)
}
return e
}
if s := resp.Header.Get("Link"); s != "" && options.cursor != nil {
before, err := nextLinkBefore(s)
if err != nil {
return err
}
if before != "" {
*options.cursor = &before
}
}
if dest != nil {
return decodeResponse(resp, dest)
}
return nil
}
type opts struct {
cursor **string
}
type opt func(*opts)
func withCursor(s **string) opt {
return func(o *opts) {
o.cursor = s
}
}
// nextLinkBefore parses the given `Link` header
// and extracts the `?before=` query string parameter
// from the URI.
// It can return an empty string.
func nextLinkBefore(s string) (string, error) {
for _, l := range link.Parse(s) {
if l.Rel != "next" {
continue
}
u, err := url.Parse(l.URI)
if err != nil {
return "", fmt.Errorf("could not parse link header uri: %w", err)
}
if !u.Query().Has("before") {
continue
}
return u.Query().Get("before"), nil
}
return "", nil
}
func disableRedirect(c *http.Client) func() {
old := c.CheckRedirect
c.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
return func() {
c.CheckRedirect = old
}
}
// chunksSizeByID is the max URL lentgh (2048) minus the endpoint lentgh (around 100) by UUID lentgh (36).
// This makes sure the full URL with the query strings params does not exceed the max URL length.
//
//nolint:gomnd // documented already
const chunksSizeByID = (2048 - 100) / 36
func makeChunks[T any](ss []T, size int) [][]T {
chunks := make([][]T, 0, (len(ss)/size)+1)
for size < len(ss) {
ss, chunks = ss[size:], append(chunks, ss[0:size:size])
}
return append(chunks, ss)
}