-
Notifications
You must be signed in to change notification settings - Fork 460
/
stripe.go
847 lines (701 loc) · 22.6 KB
/
stripe.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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
// Package stripe provides the binding for Stripe REST APIs.
package stripe
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"net/http"
"net/url"
"os"
"os/exec"
"reflect"
"runtime"
"strings"
"sync"
"time"
"github.com/stripe/stripe-go/form"
)
//
// Public constants
//
const (
// APIBackend is a constant representing the API service backend.
APIBackend SupportedBackend = "api"
// APIURL is the URL of the API service backend.
APIURL string = "https://api.stripe.com/v1"
// UnknownPlatform is the string returned as the system name if we couldn't get
// one from `uname`.
UnknownPlatform string = "unknown platform"
// UploadsBackend is a constant representing the uploads service backend.
UploadsBackend SupportedBackend = "uploads"
// UploadsURL is the URL of the uploads service backend.
UploadsURL string = "https://uploads.stripe.com/v1"
)
//
// Public variables
//
// Key is the Stripe API key used globally in the binding.
var Key string
// LogLevel is the logging level for this library.
// 0: no logging
// 1: errors only
// 2: errors + informational (default)
// 3: errors + informational + debug
var LogLevel = 2
// Logger controls how stripe performs logging at a package level. It is useful
// to customise if you need it prefixed for your application to meet other
// requirements.
//
// This Logger will be inherited by any backends created by default, but will
// be overridden if a backend is created with GetBackendWithConfig.
var Logger Printfer
//
// Public types
//
// AppInfo contains information about the "app" which this integration belongs
// to. This should be reserved for plugins that wish to identify themselves
// with Stripe.
type AppInfo struct {
Name string `json:"name"`
PartnerID string `json:"partner_id"`
URL string `json:"url"`
Version string `json:"version"`
}
// formatUserAgent formats an AppInfo in a way that's suitable to be appended
// to a User-Agent string. Note that this format is shared between all
// libraries so if it's changed, it should be changed everywhere.
func (a *AppInfo) formatUserAgent() string {
str := a.Name
if a.Version != "" {
str += "/" + a.Version
}
if a.URL != "" {
str += " (" + a.URL + ")"
}
return str
}
// Backend is an interface for making calls against a Stripe service.
// This interface exists to enable mocking for during testing if needed.
type Backend interface {
Call(method, path, key string, params ParamsContainer, v interface{}) error
CallRaw(method, path, key string, body *form.Values, params *Params, v interface{}) error
CallMultipart(method, path, key, boundary string, body io.Reader, params *Params, v interface{}) error
SetMaxNetworkRetries(maxNetworkRetries int)
}
// BackendConfig is used to configure a new Stripe backend.
type BackendConfig struct {
// HTTPClient is an HTTP client instance to use when making API requests.
//
// If left unset, it'll be set to a default HTTP client for the package.
HTTPClient *http.Client
// LogLevel is the logging level of the library and defined by:
//
// 0: no logging
// 1: errors only
// 2: errors + informational (default)
// 3: errors + informational + debug
//
// Defaults to 0 (no logging), so please make sure to set this if you want
// to see logging output in your custom configuration.
LogLevel int
// Logger is where this backend will write its logs.
//
// If left unset, it'll be set to Logger.
Logger Printfer
// MaxNetworkRetries sets maximum number of times that the library will
// retry requests that appear to have failed due to an intermittent
// problem.
//
// Defaults to 0.
MaxNetworkRetries int
// URL is the base URL to use for API paths.
//
// If left empty, it'll be set to the default for the SupportedBackend.
URL string
}
// BackendConfiguration is the internal implementation for making HTTP calls to
// Stripe.
//
// The public use of this struct is deprecated. It will be renamed and changed
// to unexported in a future version.
type BackendConfiguration struct {
Type SupportedBackend
URL string
HTTPClient *http.Client
MaxNetworkRetries int
LogLevel int
Logger Printfer
}
// Call is the Backend.Call implementation for invoking Stripe APIs.
func (s *BackendConfiguration) Call(method, path, key string, params ParamsContainer, v interface{}) error {
var body *form.Values
var commonParams *Params
if params != nil {
// This is a little unfortunate, but Go makes it impossible to compare
// an interface value to nil without the use of the reflect package and
// its true disciples insist that this is a feature and not a bug.
//
// Here we do invoke reflect because (1) we have to reflect anyway to
// use encode with the form package, and (2) the corresponding removal
// of boilerplate that this enables makes the small performance penalty
// worth it.
reflectValue := reflect.ValueOf(params)
if reflectValue.Kind() == reflect.Ptr && !reflectValue.IsNil() {
commonParams = params.GetParams()
body = &form.Values{}
form.AppendTo(body, params)
}
}
return s.CallRaw(method, path, key, body, commonParams, v)
}
// CallMultipart is the Backend.CallMultipart implementation for invoking Stripe APIs.
func (s *BackendConfiguration) CallMultipart(method, path, key, boundary string, body io.Reader, params *Params, v interface{}) error {
contentType := "multipart/form-data; boundary=" + boundary
req, err := s.NewRequest(method, path, key, contentType, body, params)
if err != nil {
return err
}
if err := s.Do(req, v); err != nil {
return err
}
return nil
}
// CallRaw is the implementation for invoking Stripe APIs internally without a backend.
func (s *BackendConfiguration) CallRaw(method, path, key string, form *form.Values, params *Params, v interface{}) error {
var body io.Reader
if form != nil && !form.Empty() {
data := form.Encode()
if method == http.MethodGet {
path += "?" + data
} else {
body = bytes.NewBufferString(data)
}
}
req, err := s.NewRequest(method, path, key, "application/x-www-form-urlencoded", body, params)
if err != nil {
return err
}
if err := s.Do(req, v); err != nil {
return err
}
return nil
}
// NewRequest is used by Call to generate an http.Request. It handles encoding
// parameters and attaching the appropriate headers.
func (s *BackendConfiguration) NewRequest(method, path, key, contentType string, body io.Reader, params *Params) (*http.Request, error) {
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
path = s.URL + path
req, err := http.NewRequest(method, path, body)
if err != nil {
if s.LogLevel > 0 {
s.Logger.Printf("Cannot create Stripe request: %v\n", err)
}
return nil, err
}
authorization := "Bearer " + key
req.Header.Add("Authorization", authorization)
req.Header.Add("Stripe-Version", apiversion)
req.Header.Add("User-Agent", encodedUserAgent)
req.Header.Add("Content-Type", contentType)
req.Header.Add("X-Stripe-Client-User-Agent", encodedStripeUserAgent)
if params != nil {
if params.Context != nil {
req = req.WithContext(params.Context)
}
if params.IdempotencyKey != nil {
idempotencyKey := strings.TrimSpace(*params.IdempotencyKey)
if len(idempotencyKey) > 255 {
return nil, errors.New("cannot use an idempotency key longer than 255 characters")
}
req.Header.Add("Idempotency-Key", idempotencyKey)
} else if isHTTPWriteMethod(method) {
req.Header.Add("Idempotency-Key", NewIdempotencyKey())
}
if params.StripeAccount != nil {
req.Header.Add("Stripe-Account", strings.TrimSpace(*params.StripeAccount))
}
for k, v := range params.Headers {
for _, line := range v {
req.Header.Add(k, line)
}
}
}
return req, nil
}
// Do is used by Call to execute an API request and parse the response. It uses
// the backend's HTTP client to execute the request and unmarshals the response
// into v. It also handles unmarshaling errors returned by the API.
func (s *BackendConfiguration) Do(req *http.Request, v interface{}) error {
if s.LogLevel > 1 {
s.Logger.Printf("Requesting %v %v%v\n", req.Method, req.URL.Host, req.URL.Path)
}
var res *http.Response
var err error
for retry := 0; ; {
start := time.Now()
res, err = s.HTTPClient.Do(req)
if s.LogLevel > 2 {
s.Logger.Printf("Request completed in %v (retry: %v)\n",
time.Since(start), retry)
}
// If the response was okay, we're done, and it's safe to break out of
// the retry loop.
if !s.shouldRetry(err, res, retry) {
break
}
resBody, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
if s.LogLevel > 0 {
s.Logger.Printf("Cannot read response: %v\n", err)
}
return err
}
if s.LogLevel > 0 {
s.Logger.Printf("Request failed with: %s (error: %v)\n", string(resBody), err)
}
sleepDuration := sleepTime(retry)
retry++
if s.LogLevel > 1 {
s.Logger.Printf("Initiating retry %v for request %v %v%v after sleeping %v\n",
retry, req.Method, req.URL.Host, req.URL.Path, sleepDuration)
}
time.Sleep(sleepDuration)
}
if err != nil {
if s.LogLevel > 0 {
s.Logger.Printf("Request failed: %v\n", err)
}
return err
}
defer res.Body.Close()
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
if s.LogLevel > 0 {
s.Logger.Printf("Cannot read response: %v\n", err)
}
return err
}
if res.StatusCode >= 400 {
return s.ResponseToError(res, resBody)
}
if s.LogLevel > 2 {
s.Logger.Printf("Response: %s\n", string(resBody))
}
if v != nil {
return json.Unmarshal(resBody, v)
}
return nil
}
// ResponseToError converts a stripe response to an Error.
func (s *BackendConfiguration) ResponseToError(res *http.Response, resBody []byte) error {
// for some odd reason, the Erro structure doesn't unmarshal
// initially I thought it was because it's a struct inside of a struct
// but even after trying that, it still didn't work
// so unmarshalling to a map for now and parsing the results manually
// but should investigate later
var errMap map[string]interface{}
err := json.Unmarshal(resBody, &errMap)
if err != nil {
return err
}
e, ok := errMap["error"]
if !ok {
err := errors.New(string(resBody))
if s.LogLevel > 0 {
s.Logger.Printf("Unparsable error returned from Stripe: %v\n", err)
}
return err
}
root := e.(map[string]interface{})
stripeErr := &Error{
Type: ErrorType(root["type"].(string)),
Msg: root["message"].(string),
HTTPStatusCode: res.StatusCode,
RequestID: res.Header.Get("Request-Id"),
}
if code, ok := root["code"]; ok {
stripeErr.Code = ErrorCode(code.(string))
}
if param, ok := root["param"]; ok {
stripeErr.Param = param.(string)
}
if charge, ok := root["charge"]; ok {
stripeErr.ChargeID = charge.(string)
}
switch stripeErr.Type {
case ErrorTypeAPI:
stripeErr.Err = &APIError{stripeErr: stripeErr}
case ErrorTypeAPIConnection:
stripeErr.Err = &APIConnectionError{stripeErr: stripeErr}
case ErrorTypeAuthentication:
stripeErr.Err = &AuthenticationError{stripeErr: stripeErr}
case ErrorTypeCard:
cardErr := &CardError{stripeErr: stripeErr}
stripeErr.Err = cardErr
if declineCode, ok := root["decline_code"]; ok {
cardErr.DeclineCode = declineCode.(string)
}
case ErrorTypeInvalidRequest:
stripeErr.Err = &InvalidRequestError{stripeErr: stripeErr}
case ErrorTypePermission:
stripeErr.Err = &PermissionError{stripeErr: stripeErr}
case ErrorTypeRateLimit:
stripeErr.Err = &RateLimitError{stripeErr: stripeErr}
}
if s.LogLevel > 0 {
s.Logger.Printf("Error encountered from Stripe: %v\n", stripeErr)
}
return stripeErr
}
// SetMaxNetworkRetries sets max number of retries on failed requests
//
// This function is deprecated. Please use GetBackendWithConfig instead.
func (s *BackendConfiguration) SetMaxNetworkRetries(maxNetworkRetries int) {
s.MaxNetworkRetries = maxNetworkRetries
}
// Checks if an error is a problem that we should retry on. This includes both
// socket errors that may represent an intermittent problem and some special
// HTTP statuses.
func (s *BackendConfiguration) shouldRetry(err error, resp *http.Response, numRetries int) bool {
if numRetries >= s.MaxNetworkRetries {
return false
}
if err != nil {
return true
}
if resp.StatusCode == http.StatusConflict {
return true
}
return false
}
// Backends are the currently supported endpoints.
type Backends struct {
API, Uploads Backend
mu sync.RWMutex
}
// Printfer is an interface to be implemented by Logger.
type Printfer interface {
Printf(format string, v ...interface{})
}
// SupportedBackend is an enumeration of supported Stripe endpoints.
// Currently supported values are "api" and "uploads".
type SupportedBackend string
//
// Public functions
//
// Bool returns a pointer to the bool value passed in.
func Bool(v bool) *bool {
return &v
}
// BoolValue returns the value of the bool pointer passed in or
// false if the pointer is nil.
func BoolValue(v *bool) bool {
if v != nil {
return *v
}
return false
}
// Float64 returns a pointer to the float64 value passed in.
func Float64(v float64) *float64 {
return &v
}
// Float64Value returns the value of the float64 pointer passed in or
// 0 if the pointer is nil.
func Float64Value(v *float64) float64 {
if v != nil {
return *v
}
return 0
}
// FormatURLPath takes a format string (of the kind used in the fmt package)
// representing a URL path with a number of parameters that belong in the path
// and returns a formatted string.
//
// This is mostly a pass through to Sprintf. It exists to make it
// it impossible to accidentally provide a parameter type that would be
// formatted improperly; for example, a string pointer instead of a string.
//
// It also URL-escapes every given parameter. This usually isn't necessary for
// a standard Stripe ID, but is needed in places where user-provided IDs are
// allowed, like in coupons or plans. We apply it broadly for extra safety.
func FormatURLPath(format string, params ...string) string {
// Convert parameters to interface{} and URL-escape them
untypedParams := make([]interface{}, len(params))
for i, param := range params {
untypedParams[i] = interface{}(url.QueryEscape(param))
}
return fmt.Sprintf(format, untypedParams...)
}
// GetBackend returns one of the library's supported backends based off of the
// given argument.
//
// It returns an existing default backend if one's already been created.
func GetBackend(backendType SupportedBackend) Backend {
var backend Backend
backends.mu.RLock()
switch backendType {
case APIBackend:
backend = backends.API
case UploadsBackend:
backend = backends.Uploads
}
backends.mu.RUnlock()
if backend != nil {
return backend
}
backend = GetBackendWithConfig(
backendType,
&BackendConfig{
HTTPClient: httpClient,
LogLevel: LogLevel,
Logger: Logger,
MaxNetworkRetries: 0,
URL: "", // Set by GetBackendWithConfiguation when empty
},
)
backends.mu.Lock()
defer backends.mu.Unlock()
switch backendType {
case APIBackend:
backends.API = backend
case UploadsBackend:
backends.Uploads = backend
}
return backend
}
// GetBackendWithConfig is the same as GetBackend except that it can be given a
// configuration struct that will configure certain aspects of the backend
// that's return.
func GetBackendWithConfig(backendType SupportedBackend, config *BackendConfig) Backend {
if config.HTTPClient == nil {
config.HTTPClient = httpClient
}
if config.Logger == nil {
config.Logger = Logger
}
switch backendType {
case APIBackend:
if config.URL == "" {
config.URL = apiURL
}
// Add the /v1/ prefix because all client packages expect it. We should
// probably change this to just make it explicit wherever it's needed
// to fulfill the principle of least astonishment.
config.URL += "/v1"
return newBackendConfiguration(backendType, config)
case UploadsBackend:
if config.URL == "" {
config.URL = uploadsURL
}
// Add the /v1/ prefix because all client packages expect it. We should
// probably change this to just make it explicit wherever it's needed
// to fulfill the principle of least astonishment.
config.URL += "/v1"
return newBackendConfiguration(backendType, config)
}
return nil
}
// Int64 returns a pointer to the int64 value passed in.
func Int64(v int64) *int64 {
return &v
}
// Int64Value returns the value of the int64 pointer passed in or
// 0 if the pointer is nil.
func Int64Value(v *int64) int64 {
if v != nil {
return *v
}
return 0
}
// NewBackends creates a new set of backends with the given HTTP client. You
// should only need to use this for testing purposes or on App Engine.
func NewBackends(httpClient *http.Client) *Backends {
config := &BackendConfig{HTTPClient: httpClient}
return &Backends{
API: GetBackendWithConfig(APIBackend, config),
Uploads: GetBackendWithConfig(UploadsBackend, config),
}
}
// ParseID attempts to parse a string scalar from a given JSON value which is
// still encoded as []byte. If the value was a string, it returns the string
// along with true as the second return value. If not, false is returned as the
// second return value.
//
// The purpose of this function is to detect whether a given value in a
// response from the Stripe API is a string ID or an expanded object.
func ParseID(data []byte) (string, bool) {
s := string(data)
if !strings.HasPrefix(s, "\"") {
return "", false
}
if !strings.HasSuffix(s, "\"") {
return "", false
}
return s[1 : len(s)-1], true
}
// SetAppInfo sets app information. See AppInfo.
func SetAppInfo(info *AppInfo) {
if info != nil && info.Name == "" {
panic(fmt.Errorf("App info name cannot be empty"))
}
appInfo = info
// This is run in init, but we need to reinitialize it now that we have
// some app info.
initUserAgent()
}
// SetBackend sets the backend used in the binding.
func SetBackend(backend SupportedBackend, b Backend) {
switch backend {
case APIBackend:
backends.API = b
case UploadsBackend:
backends.Uploads = b
}
}
// SetHTTPClient overrides the default HTTP client.
// This is useful if you're running in a Google AppEngine environment
// where the http.DefaultClient is not available.
func SetHTTPClient(client *http.Client) {
httpClient = client
}
// String returns a pointer to the string value passed in.
func String(v string) *string {
return &v
}
// StringValue returns the value of the string pointer passed in or
// "" if the pointer is nil.
func StringValue(v *string) string {
if v != nil {
return *v
}
return ""
}
//
// Private constants
//
const apiURL = "https://api.stripe.com"
// apiversion is the currently supported API version
const apiversion = "2018-07-27"
// clientversion is the binding version
const clientversion = "38.2.0"
// defaultHTTPTimeout is the default timeout on the http.Client used by the library.
// This is chosen to be consistent with the other Stripe language libraries and
// to coordinate with other timeouts configured in the Stripe infrastructure.
const defaultHTTPTimeout = 80 * time.Second
// maxNetworkRetriesDelay and minNetworkRetriesDelay defines sleep time in milliseconds between
// tries to send HTTP request again after network failure.
const maxNetworkRetriesDelay = 5000 * time.Millisecond
const minNetworkRetriesDelay = 500 * time.Millisecond
const uploadsURL = "https://uploads.stripe.com"
//
// Private types
//
// stripeClientUserAgent contains information about the current runtime which
// is serialized and sent in the `X-Stripe-Client-User-Agent` as additional
// debugging information.
type stripeClientUserAgent struct {
Application *AppInfo `json:"application"`
BindingsVersion string `json:"bindings_version"`
Language string `json:"lang"`
LanguageVersion string `json:"lang_version"`
Publisher string `json:"publisher"`
Uname string `json:"uname"`
}
//
// Private variables
//
var appInfo *AppInfo
var backends Backends
var encodedStripeUserAgent string
var encodedUserAgent string
var httpClient = &http.Client{Timeout: defaultHTTPTimeout}
//
// Private functions
//
// getUname tries to get a uname from the system, but not that hard. It tries
// to execute `uname -a`, but swallows any errors in case that didn't work
// (i.e. non-Unix non-Mac system or some other reason).
func getUname() string {
path, err := exec.LookPath("uname")
if err != nil {
return UnknownPlatform
}
cmd := exec.Command(path, "-a")
var out bytes.Buffer
cmd.Stderr = nil // goes to os.DevNull
cmd.Stdout = &out
err = cmd.Run()
if err != nil {
return UnknownPlatform
}
return out.String()
}
func init() {
Logger = log.New(os.Stderr, "", log.LstdFlags)
initUserAgent()
}
func initUserAgent() {
encodedUserAgent = "Stripe/v1 GoBindings/" + clientversion
if appInfo != nil {
encodedUserAgent += " " + appInfo.formatUserAgent()
}
stripeUserAgent := &stripeClientUserAgent{
Application: appInfo,
BindingsVersion: clientversion,
Language: "go",
LanguageVersion: runtime.Version(),
Publisher: "stripe",
Uname: getUname(),
}
marshaled, err := json.Marshal(stripeUserAgent)
// Encoding this struct should never be a problem, so we're okay to panic
// in case it is for some reason.
if err != nil {
panic(err)
}
encodedStripeUserAgent = string(marshaled)
}
func isHTTPWriteMethod(method string) bool {
return method == http.MethodPost || method == http.MethodPut || method == http.MethodPatch || method == http.MethodDelete
}
// newBackendConfiguration returns a new Backend based off a given type and
// fully initialized BackendConfig struct.
//
// The vast majority of the time you should be calling GetBackendWithConfig
// instead of this function.
func newBackendConfiguration(backendType SupportedBackend, config *BackendConfig) Backend {
return &BackendConfiguration{
HTTPClient: config.HTTPClient,
LogLevel: config.LogLevel,
Logger: config.Logger,
MaxNetworkRetries: config.MaxNetworkRetries,
Type: backendType,
URL: config.URL,
}
}
// sleepTime calculates sleeping/delay time in milliseconds between failure and a new one request.
func sleepTime(numRetries int) time.Duration {
// Apply exponential backoff with minNetworkRetriesDelay on the
// number of num_retries so far as inputs.
delay := minNetworkRetriesDelay + minNetworkRetriesDelay*time.Duration(numRetries*numRetries)
// Do not allow the number to exceed maxNetworkRetriesDelay.
if delay > maxNetworkRetriesDelay {
delay = maxNetworkRetriesDelay
}
// Apply some jitter by randomizing the value in the range of 75%-100%.
jitter := rand.Int63n(int64(delay / 4))
delay -= time.Duration(jitter)
// But never sleep less than the base sleep seconds.
if delay < minNetworkRetriesDelay {
delay = minNetworkRetriesDelay
}
return delay
}