-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
202 lines (169 loc) · 5.12 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
// Package aiven provides a client for interacting with the Aiven API.
package aiven
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"reflect"
"strings"
"time"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/go-retryablehttp"
"github.com/kelseyhightower/envconfig"
"github.com/rs/zerolog"
)
var errTokenIsRequired = errors.New(
"token is required. See https://api.aiven.io/doc/#section/Get-started/Authentication",
)
// Doer aka http.Client
type Doer interface {
Do(req *http.Request) (*http.Response, error)
}
// NewClient creates a new Aiven client.
func NewClient(opts ...Option) (Client, error) {
d := new(aivenClient)
err := envconfig.Process("", d)
if err != nil {
return nil, err
}
// User settings
for _, opt := range opts {
opt(d)
}
// When DoerOpt is not applied
if d.doer == nil {
c := retryablehttp.NewClient()
c.RetryMax = d.RetryMax
c.RetryWaitMin = d.RetryWaitMin
c.RetryWaitMax = d.RetryWaitMax
c.CheckRetry = checkRetry
// Disables retryablehttp logger which outputs a lot of debug information
c.Logger = nil
// By default, when retryablehttp gets 500 (or any error),
// it doesn't return the body which might contain useful information.
// Instead, it returns `giving up after %d attempt(s)` for the given url and method.
c.ErrorHandler = retryablehttp.PassthroughErrorHandler
d.doer = c.StandardClient()
}
if d.Debug {
out := zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}
d.logger = zerolog.New(out).With().Timestamp().Logger()
}
if d.Token == "" {
return nil, errTokenIsRequired
}
// Removes trailing / so it is easier later Host + URL
d.Host = strings.TrimSuffix(d.Host, "/")
// Formats the user agent
d.UserAgent = fmt.Sprintf(
"go-client-codegen/%s %s",
strings.TrimLeft(Version(), "v"),
strings.TrimSpace(d.UserAgent),
)
return newClient(d), nil
}
// Retry settings explanation:
// Default values (retryWaitMin = 1s, retryWaitMax = 30s, retryMax = 4)
// Changed values (retryWaitMin = 2s, retryWaitMax = 15s, retryMax = 6)
//
// Default values | Changed values
// Run Seconds | Run Seconds
// 0 0.000 | 0 0.000
// 1 1.000 | 1 2.000
// 2 3.000 | 2 6.000
// 3 7.000 | 3 14.000
// 4 15.000 | 4 15.000 (capped at retryWaitMax)
//
// | 5 15.000 (capped at retryWaitMax)
// | 6 15.000 (capped at retryWaitMax)
//
// Maximum wait time if all attempts fail:
// Default values: 26 seconds
// Changed values: 67 seconds
type aivenClient struct {
Host string `envconfig:"AIVEN_WEB_URL" default:"https://api.aiven.io"`
UserAgent string `envconfig:"AIVEN_USER_AGENT" default:"aiven-go-client/v3"`
Token string `envconfig:"AIVEN_TOKEN"`
Debug bool `envconfig:"AIVEN_DEBUG"`
RetryMax int `envconfig:"AIVEN_CLIENT_RETRY_MAX" default:"6"`
RetryWaitMin time.Duration `envconfig:"AIVEN_CLIENT_RETRY_WAIT_MIN" default:"2s"`
RetryWaitMax time.Duration `envconfig:"AIVEN_CLIENT_RETRY_WAIT_MAX" default:"15s"`
logger zerolog.Logger
doer Doer
}
// OperationIDKey is the key used to store the operation ID in the context.
type OperationIDKey struct{}
func (d *aivenClient) Do(ctx context.Context, operationID, method, path string, in any, query ...[2]string) ([]byte, error) {
ctx = context.WithValue(ctx, OperationIDKey{}, operationID)
var rsp *http.Response
var err error
if d.Debug {
start := time.Now()
defer func() {
end := time.Since(start)
var event *zerolog.Event
if err != nil {
event = d.logger.Error().Err(err)
} else {
event = d.logger.Info().Str("status", rsp.Status)
}
event.Ctx(ctx).
Stringer("duration", end).
Str("operationID", operationID).
Str("method", method).
Str("path", path).
Str("query", fmtQuery(query...)).
Send()
}()
}
rsp, err = d.do(ctx, method, path, in, query...)
if err != nil {
return nil, err
}
defer func() {
err = multierror.Append(rsp.Body.Close()).ErrorOrNil()
}()
return fromResponse(operationID, rsp)
}
func (d *aivenClient) do(ctx context.Context, method, path string, in any, query ...[2]string) (*http.Response, error) {
var body io.Reader
if !(in == nil || isEmpty(in)) {
b, err := json.Marshal(in)
if err != nil {
return nil, err
}
body = bytes.NewBuffer(b)
}
req, err := http.NewRequestWithContext(ctx, method, d.Host+path, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", d.UserAgent)
req.Header.Set("Authorization", "aivenv1 "+d.Token)
req.URL.RawQuery = fmtQuery(query...)
return d.doer.Do(req)
}
func isEmpty(a any) bool {
v := reflect.ValueOf(a)
return v.IsZero() || v.Kind() == reflect.Ptr && v.IsNil()
}
func fmtQuery(query ...[2]string) string {
q := make(url.Values)
for _, v := range query {
q.Add(v[0], v[1])
}
if !q.Has("limit") {
// TODO: BAD hack to get around pagination in most cases
// we should implement this properly at some point but for now
// that should be its own issue
q.Add("limit", "999")
}
return q.Encode()
}