-
Notifications
You must be signed in to change notification settings - Fork 1
/
requestconfig.go
490 lines (435 loc) · 12.7 KB
/
requestconfig.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
package requestconfig
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"math"
"math/rand"
"net/http"
"net/url"
"runtime"
"strconv"
"strings"
"time"
"github.com/Modern-Treasury/modern-treasury-go/v2/internal"
"github.com/Modern-Treasury/modern-treasury-go/v2/internal/apierror"
"github.com/Modern-Treasury/modern-treasury-go/v2/internal/apiform"
"github.com/Modern-Treasury/modern-treasury-go/v2/internal/apiquery"
"github.com/google/uuid"
)
func getDefaultHeaders() map[string]string {
return map[string]string{
"User-Agent": fmt.Sprintf("ModernTreasury/Go %s", internal.PackageVersion),
}
}
func getNormalizedOS() string {
switch runtime.GOOS {
case "ios":
return "iOS"
case "android":
return "Android"
case "darwin":
return "MacOS"
case "window":
return "Windows"
case "freebsd":
return "FreeBSD"
case "openbsd":
return "OpenBSD"
case "linux":
return "Linux"
default:
return fmt.Sprintf("Other:%s", runtime.GOOS)
}
}
func getNormalizedArchitecture() string {
switch runtime.GOARCH {
case "386":
return "x32"
case "amd64":
return "x64"
case "arm":
return "arm"
case "arm64":
return "arm64"
default:
return fmt.Sprintf("other:%s", runtime.GOARCH)
}
}
func getPlatformProperties() map[string]string {
return map[string]string{
"X-Stainless-Lang": "go",
"X-Stainless-Package-Version": internal.PackageVersion,
"X-Stainless-OS": getNormalizedOS(),
"X-Stainless-Arch": getNormalizedArchitecture(),
"X-Stainless-Runtime": "go",
"X-Stainless-Runtime-Version": runtime.Version(),
}
}
func NewRequestConfig(ctx context.Context, method string, u string, body interface{}, dst interface{}, opts ...func(*RequestConfig) error) (*RequestConfig, error) {
var reader io.Reader
contentType := "application/json"
hasSerializationFunc := false
if body, ok := body.(json.Marshaler); ok {
content, err := body.MarshalJSON()
if err != nil {
return nil, err
}
reader = bytes.NewBuffer(content)
hasSerializationFunc = true
}
if body, ok := body.(apiform.Marshaler); ok {
var (
content []byte
err error
)
content, contentType, err = body.MarshalMultipart()
if err != nil {
return nil, err
}
reader = bytes.NewBuffer(content)
hasSerializationFunc = true
}
if body, ok := body.(apiquery.Queryer); ok {
hasSerializationFunc = true
params := body.URLQuery().Encode()
if params != "" {
u = u + "?" + params
}
}
if body, ok := body.([]byte); ok {
reader = bytes.NewBuffer(body)
hasSerializationFunc = true
}
if body, ok := body.(io.Reader); ok {
reader = body
hasSerializationFunc = true
}
// Fallback to json serialization if none of the serialization functions that we expect
// to see is present.
if body != nil && !hasSerializationFunc {
content, err := json.Marshal(body)
if err != nil {
return nil, err
}
reader = bytes.NewBuffer(content)
}
req, err := http.NewRequestWithContext(ctx, method, u, nil)
if err != nil {
return nil, err
}
if reader != nil {
req.Header.Set("Content-Type", contentType)
}
if method != http.MethodGet {
// Note this can be overridden with `WithHeader("Idempotency-Key", myIdempotencyKey)`
req.Header.Set("Idempotency-Key", "stainless-go-"+uuid.New().String())
}
req.Header.Set("Accept", "application/json")
for k, v := range getDefaultHeaders() {
req.Header.Add(k, v)
}
for k, v := range getPlatformProperties() {
req.Header.Add(k, v)
}
cfg := RequestConfig{
MaxRetries: 2,
Context: ctx,
Request: req,
HTTPClient: http.DefaultClient,
Body: reader,
}
cfg.ResponseBodyInto = dst
err = cfg.Apply(opts...)
if err != nil {
return nil, err
}
return &cfg, nil
}
// RequestConfig represents all the state related to one request.
//
// Editing the variables inside RequestConfig directly is unstable api. Prefer
// composing func(\*RequestConfig) error instead if possible.
type RequestConfig struct {
MaxRetries int
RequestTimeout time.Duration
Context context.Context
Request *http.Request
BaseURL *url.URL
HTTPClient *http.Client
Middlewares []middleware
APIKey string
OrganizationID string
WebhookKey string
// If ResponseBodyInto not nil, then we will attempt to deserialize into
// ResponseBodyInto. If Destination is a []byte, then it will return the body as
// is.
ResponseBodyInto interface{}
// ResponseInto copies the \*http.Response of the corresponding request into the
// given address
ResponseInto **http.Response
Body io.Reader
}
// middleware is exactly the same type as the Middleware type found in the [option] package,
// but it is redeclared here for circular dependency issues.
type middleware = func(*http.Request, middlewareNext) (*http.Response, error)
// middlewareNext is exactly the same type as the MiddlewareNext type found in the [option] package,
// but it is redeclared here for circular dependency issues.
type middlewareNext = func(*http.Request) (*http.Response, error)
func applyMiddleware(middleware middleware, next middlewareNext) middlewareNext {
return func(req *http.Request) (res *http.Response, err error) {
return middleware(req, next)
}
}
func shouldRetry(req *http.Request, res *http.Response) bool {
// If there is no way to recover the Body, then we shouldn't retry.
if req.Body != nil && req.GetBody == nil {
return false
}
// If there is no response, that indicates that there is a connection error
// so we retry the request.
if res == nil {
return true
}
// If the header explictly wants a retry behavior, respect that over the
// http status code.
if res.Header.Get("x-should-retry") == "true" {
return true
}
if res.Header.Get("x-should-retry") == "false" {
return false
}
return res.StatusCode == http.StatusRequestTimeout ||
res.StatusCode == http.StatusConflict ||
res.StatusCode == http.StatusTooManyRequests ||
res.StatusCode >= http.StatusInternalServerError
}
func parseRetryAfterHeader(resp *http.Response) (time.Duration, bool) {
if resp == nil {
return 0, false
}
type retryData struct {
header string
units time.Duration
// custom is used when the regular algorithm failed and is optional.
// the returned duration is used verbatim (units is not applied).
custom func(string) (time.Duration, bool)
}
nop := func(string) (time.Duration, bool) { return 0, false }
// the headers are listed in order of preference
retries := []retryData{
{
header: "Retry-After-Ms",
units: time.Millisecond,
custom: nop,
},
{
header: "Retry-After",
units: time.Second,
// retry-after values are expressed in either number of
// seconds or an HTTP-date indicating when to try again
custom: func(ra string) (time.Duration, bool) {
t, err := time.Parse(time.RFC1123, ra)
if err != nil {
return 0, false
}
return time.Until(t), true
},
},
}
for _, retry := range retries {
v := resp.Header.Get(retry.header)
if v == "" {
continue
}
if retryAfter, err := strconv.ParseFloat(v, 64); err == nil {
return time.Duration(retryAfter * float64(retry.units)), true
}
if d, ok := retry.custom(v); ok {
return d, true
}
}
return 0, false
}
func retryDelay(res *http.Response, retryCount int) time.Duration {
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
// just do what it says.
if retryAfterDelay, ok := parseRetryAfterHeader(res); ok && 0 <= retryAfterDelay && retryAfterDelay < time.Minute {
return retryAfterDelay
}
maxDelay := 8 * time.Second
delay := time.Duration(0.5 * float64(time.Second) * math.Pow(2, float64(retryCount)))
if delay > maxDelay {
delay = maxDelay
}
jitter := rand.Int63n(int64(delay / 4))
delay -= time.Duration(jitter)
return delay
}
func (cfg *RequestConfig) Execute() (err error) {
cfg.Request.URL, err = cfg.BaseURL.Parse(strings.TrimLeft(cfg.Request.URL.String(), "/"))
if err != nil {
return err
}
if cfg.Body != nil && cfg.Request.Body == nil {
switch body := cfg.Body.(type) {
case *bytes.Buffer:
b := body.Bytes()
cfg.Request.ContentLength = int64(body.Len())
cfg.Request.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(b)), nil }
cfg.Request.Body, _ = cfg.Request.GetBody()
case *bytes.Reader:
cfg.Request.ContentLength = int64(body.Len())
cfg.Request.GetBody = func() (io.ReadCloser, error) {
_, err := body.Seek(0, 0)
return io.NopCloser(body), err
}
cfg.Request.Body, _ = cfg.Request.GetBody()
default:
if rc, ok := body.(io.ReadCloser); ok {
cfg.Request.Body = rc
} else {
cfg.Request.Body = io.NopCloser(body)
}
}
}
handler := cfg.HTTPClient.Do
for i := len(cfg.Middlewares) - 1; i >= 0; i -= 1 {
handler = applyMiddleware(cfg.Middlewares[i], handler)
}
var res *http.Response
for retryCount := 0; retryCount <= cfg.MaxRetries; retryCount += 1 {
ctx := cfg.Request.Context()
if cfg.RequestTimeout != time.Duration(0) {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, cfg.RequestTimeout)
defer cancel()
}
res, err = handler(cfg.Request.Clone(ctx))
if ctx != nil && ctx.Err() != nil {
return ctx.Err()
}
if !shouldRetry(cfg.Request, res) || retryCount >= cfg.MaxRetries {
break
}
// Prepare next request and wait for the retry delay
if cfg.Request.GetBody != nil {
cfg.Request.Body, err = cfg.Request.GetBody()
if err != nil {
return err
}
}
// Can't actually refresh the body, so we don't attempt to retry here
if cfg.Request.GetBody == nil && cfg.Request.Body != nil {
break
}
time.Sleep(retryDelay(res, retryCount))
}
// Save *http.Response if it is requested to, even if there was an error making the request. This is
// useful in cases where you might want to debug by inspecting the response. Note that if err != nil,
// the response should be generally be empty, but there are edge cases.
if cfg.ResponseInto != nil {
*cfg.ResponseInto = res
}
if responseBodyInto, ok := cfg.ResponseBodyInto.(**http.Response); ok {
*responseBodyInto = res
}
// If there was a connection error in the final request or any other transport error,
// return that early without trying to coerce into an APIError.
if err != nil {
return err
}
if res.StatusCode >= 400 {
contents, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return err
}
// If there is an APIError, re-populate the response body so that debugging
// utilities can conveniently dump the response without issue.
res.Body = io.NopCloser(bytes.NewBuffer(contents))
// Load the contents into the error format if it is provided.
aerr := apierror.Error{Request: cfg.Request, Response: res, StatusCode: res.StatusCode}
err = aerr.UnmarshalJSON(contents)
if err != nil {
return err
}
return &aerr
}
if cfg.ResponseBodyInto == nil {
return nil
}
if _, ok := cfg.ResponseBodyInto.(**http.Response); ok {
return nil
}
contents, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("error reading response body: %w", err)
}
// If we are not json, return plaintext
isJSON := strings.Contains(res.Header.Get("content-type"), "application/json")
if !isJSON {
switch dst := cfg.ResponseBodyInto.(type) {
case *string:
*dst = string(contents)
case **string:
tmp := string(contents)
*dst = &tmp
case *[]byte:
*dst = contents
default:
return fmt.Errorf("expected destination type of 'string' or '[]byte' for responses with content-type that is not 'application/json'")
}
return nil
}
// If the response happens to be a byte array, deserialize the body as-is.
switch dst := cfg.ResponseBodyInto.(type) {
case *[]byte:
*dst = contents
}
err = json.NewDecoder(bytes.NewReader(contents)).Decode(cfg.ResponseBodyInto)
if err != nil {
err = fmt.Errorf("error parsing response json: %w", err)
}
return nil
}
func ExecuteNewRequest(ctx context.Context, method string, u string, body interface{}, dst interface{}, opts ...func(*RequestConfig) error) error {
cfg, err := NewRequestConfig(ctx, method, u, body, dst, opts...)
if err != nil {
return err
}
return cfg.Execute()
}
func (cfg *RequestConfig) Clone(ctx context.Context) *RequestConfig {
if cfg == nil {
return nil
}
req := cfg.Request.Clone(ctx)
var err error
if req.Body != nil {
req.Body, err = req.GetBody()
}
if err != nil {
return nil
}
new := &RequestConfig{
MaxRetries: cfg.MaxRetries,
Context: ctx,
Request: req,
HTTPClient: cfg.HTTPClient,
}
new.Request.Header.Set("Idempotency-Key", "stainless-go-"+uuid.New().String())
return new
}
func (cfg *RequestConfig) Apply(opts ...func(*RequestConfig) error) error {
for _, opt := range opts {
err := opt(cfg)
if err != nil {
return err
}
}
return nil
}