-
Notifications
You must be signed in to change notification settings - Fork 460
/
stripe.go
1610 lines (1366 loc) · 49 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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package stripe provides the binding for Stripe REST APIs.
package stripe
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"os/exec"
"reflect"
"regexp"
"runtime"
"strings"
"sync"
"time"
"github.com/stripe/stripe-go/v81/form"
)
//
// Public constants
//
const (
// APIVersion is the currently supported API version
APIVersion string = apiVersion
// 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"
// ClientVersion is the version of the stripe-go library being used.
ClientVersion string = clientversion
// ConnectURL is the URL for OAuth.
ConnectURL string = "https://connect.stripe.com"
// ConnectBackend is a constant representing the connect service backend for
// OAuth.
ConnectBackend SupportedBackend = "connect"
// DefaultMaxNetworkRetries is the default maximum number of retries made
// by a Stripe client.
DefaultMaxNetworkRetries int64 = 2
MeterEventsBackend SupportedBackend = "meterevents"
MeterEventsURL = "https://meter-events.stripe.com"
// 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://files.stripe.com"
)
//
// Public variables
//
// EnableTelemetry is a global override for enabling client telemetry, which
// sends request performance metrics to Stripe via the `X-Stripe-Client-Telemetry`
// header. If set to true, all clients will send telemetry metrics. Defaults to
// true.
//
// Telemetry can also be disabled on a per-client basis by instead creating a
// `BackendConfig` with `EnableTelemetry: false`.
var EnableTelemetry = true
// Key is the Stripe API key used globally in the binding.
var Key string
//
// Public types
//
// APIResponse encapsulates some common features of a response from the
// Stripe API.
type APIResponse struct {
// Header contain a map of all HTTP header keys to values. Its behavior and
// caveats are identical to that of http.Header.
Header http.Header
// IdempotencyKey contains the idempotency key used with this request.
// Idempotency keys are a Stripe-specific concept that helps guarantee that
// requests that fail and need to be retried are not duplicated.
IdempotencyKey string
// RawJSON contains the response body as raw bytes.
RawJSON []byte
// RequestID contains a string that uniquely identifies the Stripe request.
// Used for debugging or support purposes.
RequestID string
// Status is a status code and message. e.g. "200 OK"
Status string
// StatusCode is a status code as integer. e.g. 200
StatusCode int
duration *time.Duration
}
// StreamingAPIResponse encapsulates some common features of a response from the
// Stripe API whose body can be streamed. This is used for "file downloads", and
// the `Body` property is an io.ReadCloser, so the user can stream it to another
// location such as a file or network request without buffering the entire body
// into memory.
type StreamingAPIResponse struct {
Header http.Header
IdempotencyKey string
Body io.ReadCloser
RequestID string
Status string
StatusCode int
duration *time.Duration
}
func newAPIResponse(res *http.Response, resBody []byte, requestDuration *time.Duration) *APIResponse {
return &APIResponse{
Header: res.Header,
IdempotencyKey: res.Header.Get("Idempotency-Key"),
RawJSON: resBody,
RequestID: res.Header.Get("Request-Id"),
Status: res.Status,
StatusCode: res.StatusCode,
duration: requestDuration,
}
}
func newStreamingAPIResponse(res *http.Response, body io.ReadCloser, requestDuration *time.Duration) *StreamingAPIResponse {
return &StreamingAPIResponse{
Header: res.Header,
IdempotencyKey: res.Header.Get("Idempotency-Key"),
Body: body,
RequestID: res.Header.Get("Request-Id"),
Status: res.Status,
StatusCode: res.StatusCode,
duration: requestDuration,
}
}
// APIResource is a type assigned to structs that may come from Stripe API
// endpoints and contains facilities common to all of them.
type APIResource struct {
LastResponse *APIResponse `json:"-"`
}
// APIStream is a type assigned to streaming responses that may come from Stripe API
type APIStream struct {
LastResponse *StreamingAPIResponse
}
// SetLastResponse sets the HTTP response that returned the API resource.
func (r *APIResource) SetLastResponse(response *APIResponse) {
r.LastResponse = response
}
// SetLastResponse sets the HTTP response that returned the API resource.
func (r *APIStream) SetLastResponse(response *StreamingAPIResponse) {
r.LastResponse = response
}
// 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 LastResponseSetter) error
CallStreaming(method, path, key string, params ParamsContainer, v StreamingLastResponseSetter) error
CallRaw(method, path, key string, body *form.Values, params *Params, v LastResponseSetter) error
CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *Params, v LastResponseSetter) error
SetMaxNetworkRetries(maxNetworkRetries int64)
}
type RawRequestBackend interface {
RawRequest(method, path, key, content string, params *RawParams) (*APIResponse, error)
}
// BackendConfig is used to configure a new Stripe backend.
type BackendConfig struct {
// EnableTelemetry allows request metrics (request id and duration) to be sent
// to Stripe in subsequent requests via the `X-Stripe-Client-Telemetry` header.
//
// This value is a pointer to allow us to differentiate an unset versus
// empty value. Use stripe.Bool for an easy way to set this value.
//
// Defaults to false.
EnableTelemetry *bool
// 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
// LeveledLogger is the logger that the backend will use to log errors,
// warnings, and informational messages.
//
// LeveledLoggerInterface is implemented by LeveledLogger, and one can be
// initialized at the desired level of logging. LeveledLoggerInterface
// also provides out-of-the-box compatibility with a Logrus Logger, but may
// require a thin shim for use with other logging libraries that use less
// standard conventions like Zap.
//
// Defaults to DefaultLeveledLogger.
//
// To set a logger that logs nothing, set this to a stripe.LeveledLogger
// with a Level of LevelNull (simply setting this field to nil will not
// work).
LeveledLogger LeveledLoggerInterface
// MaxNetworkRetries sets maximum number of times that the library will
// retry requests that appear to have failed due to an intermittent
// problem.
//
// This value is a pointer to allow us to differentiate an unset versus
// empty value. Use stripe.Int64 for an easy way to set this value.
//
// Defaults to DefaultMaxNetworkRetries (2).
MaxNetworkRetries *int64
// URL is the base URL to use for API paths.
//
// This value is a pointer to allow us to differentiate an unset versus
// empty value. Use stripe.String for an easy way to set this value.
//
// If left empty, it'll be set to the default for the SupportedBackend.
URL *string
}
// BackendImplementation is the internal implementation for making HTTP calls
// to Stripe.
//
// The public use of this struct is deprecated. It will be unexported in a
// future version.
type BackendImplementation struct {
Type SupportedBackend
URL string
HTTPClient *http.Client
LeveledLogger LeveledLoggerInterface
MaxNetworkRetries int64
enableTelemetry bool
// networkRetriesSleep indicates whether the backend should use the normal
// sleep between retries.
//
// See also SetNetworkRetriesSleep.
networkRetriesSleep bool
requestMetricsBuffer chan requestMetrics
}
type metricsResponseSetter struct {
LastResponseSetter
backend *BackendImplementation
params *Params
}
func (s *metricsResponseSetter) SetLastResponse(response *APIResponse) {
var usage []string
if s.params != nil {
usage = s.params.usage
}
s.backend.maybeEnqueueTelemetryMetrics(response.RequestID, response.duration, usage)
s.LastResponseSetter.SetLastResponse(response)
}
func (s *metricsResponseSetter) UnmarshalJSON(b []byte) error {
return json.Unmarshal(b, s.LastResponseSetter)
}
type streamingLastResponseSetterWrapper struct {
StreamingLastResponseSetter
f func(*StreamingAPIResponse)
}
func (l *streamingLastResponseSetterWrapper) SetLastResponse(response *StreamingAPIResponse) {
l.f(response)
l.StreamingLastResponseSetter.SetLastResponse(response)
}
func (l *streamingLastResponseSetterWrapper) UnmarshalJSON(b []byte) error {
return json.Unmarshal(b, l.StreamingLastResponseSetter)
}
func extractParams(params ParamsContainer) (*form.Values, *Params, error) {
var formValues *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()
if !reflectValue.Elem().FieldByName("Metadata").IsZero() {
if commonParams.Metadata != nil {
return nil, nil, fmt.Errorf("You cannot specify both the (deprecated) .Params.Metadata and .Metadata in %s", reflectValue.Elem().Type().Name())
}
}
if !reflectValue.Elem().FieldByName("Expand").IsZero() {
if commonParams.Expand != nil {
return nil, nil, fmt.Errorf("You cannot specify both the (deprecated) .Params.Expand and .Expand in %s", reflectValue.Elem().Type().Name())
}
}
formValues = &form.Values{}
form.AppendTo(formValues, params)
}
}
return formValues, commonParams, nil
}
// Call is the Backend.Call implementation for invoking Stripe APIs.
func (s *BackendImplementation) Call(method, path, key string, params ParamsContainer, v LastResponseSetter) error {
body, commonParams, err := extractParams(params)
if err != nil {
return err
}
return s.CallRaw(method, path, key, body, commonParams, v)
}
// CallStreaming is the Backend.Call implementation for invoking Stripe APIs
// without buffering the response into memory.
func (s *BackendImplementation) CallStreaming(method, path, key string, params ParamsContainer, v StreamingLastResponseSetter) error {
formValues, commonParams, err := extractParams(params)
if err != nil {
return err
}
var body string
if formValues != nil && !formValues.Empty() {
body = formValues.Encode()
// On `GET`, move the payload into the URL
if method == http.MethodGet {
path += "?" + body
body = ""
}
}
bodyBuffer := bytes.NewBufferString(body)
req, err := s.NewRequest(method, path, key, "application/x-www-form-urlencoded", commonParams)
if err != nil {
return err
}
responseSetter := streamingLastResponseSetterWrapper{
v,
func(response *StreamingAPIResponse) {
var usage []string
if commonParams != nil {
usage = commonParams.usage
}
s.maybeEnqueueTelemetryMetrics(response.RequestID, response.duration, usage)
},
}
if err := s.DoStreaming(req, bodyBuffer, &responseSetter); err != nil {
return err
}
return nil
}
// CallMultipart is the Backend.CallMultipart implementation for invoking Stripe APIs.
func (s *BackendImplementation) CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *Params, v LastResponseSetter) error {
contentType := "multipart/form-data; boundary=" + boundary
req, err := s.NewRequest(method, path, key, contentType, params)
if err != nil {
return err
}
if err := s.Do(req, body, v); err != nil {
return err
}
return nil
}
// the stripe API only accepts GET / POST / DELETE
func validateMethod(method string) error {
if method != http.MethodPost && method != http.MethodGet && method != http.MethodDelete {
return fmt.Errorf("method must be POST, GET, or DELETE. Received %s", method)
}
return nil
}
// RawRequest is the Backend.RawRequest implementation for invoking Stripe APIs.
func (s *BackendImplementation) RawRequest(method, path, key, content string, params *RawParams) (*APIResponse, error) {
var bodyBuffer = bytes.NewBuffer(nil)
var commonParams *Params
var err error
var contentType string
err = validateMethod(method)
if err != nil {
return nil, err
}
paramsIsNil := params == nil || reflect.ValueOf(params).IsNil()
var apiMode APIMode
if strings.HasPrefix(path, "/v1") {
apiMode = V1APIMode
} else if strings.HasPrefix(path, "/v2") {
apiMode = V2APIMode
} else {
return nil, fmt.Errorf("Unknown path prefix %s", path)
}
_, commonParams, err = extractParams(params)
if err != nil {
return nil, err
}
if apiMode == V1APIMode {
contentType = "application/x-www-form-urlencoded"
} else if apiMode == V2APIMode {
contentType = "application/json"
} else {
return nil, fmt.Errorf("Unknown API mode %s", apiMode)
}
bodyBuffer.WriteString(content)
req, err := s.NewRequest(method, path, key, contentType, commonParams)
if err != nil {
return nil, err
}
if !paramsIsNil {
if params.StripeContext != "" {
req.Header.Set("Stripe-Context", params.StripeContext)
}
}
handleResponse := func(res *http.Response, err error) (interface{}, error) {
return s.handleResponseBufferingErrors(res, err)
}
resp, result, requestDuration, err := s.requestWithRetriesAndTelemetry(req, bodyBuffer, handleResponse)
if err != nil {
return nil, err
}
requestID := resp.Header.Get("Request-Id")
s.maybeEnqueueTelemetryMetrics(requestID, requestDuration, []string{"raw_request"})
body, err := ioutil.ReadAll(result.(io.ReadCloser))
if err != nil {
return nil, err
}
return newAPIResponse(resp, body, requestDuration), nil
}
// CallRaw is the implementation for invoking Stripe APIs internally without a backend.
func (s *BackendImplementation) CallRaw(method, path, key string, form *form.Values, params *Params, v LastResponseSetter) error {
var body string
if form != nil && !form.Empty() {
body = form.Encode()
err := validateMethod(method)
if err != nil {
return err
}
// On `GET` / `DELETE`, move the payload into the URL
if method != http.MethodPost {
path += "?" + body
body = ""
}
}
bodyBuffer := bytes.NewBufferString(body)
req, err := s.NewRequest(method, path, key, "application/x-www-form-urlencoded", params)
if err != nil {
return err
}
responseSetter := metricsResponseSetter{
LastResponseSetter: v,
backend: s,
params: params,
}
if err := s.Do(req, bodyBuffer, &responseSetter); 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 *BackendImplementation) NewRequest(method, path, key, contentType string, params *Params) (*http.Request, error) {
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
path = s.URL + path
// Body is set later by `Do`.
req, err := http.NewRequest(method, path, nil)
if err != nil {
s.LeveledLogger.Errorf("Cannot create Stripe request: %v", err)
return nil, err
}
authorization := "Bearer " + key
req.Header.Add("Authorization", authorization)
req.Header.Add("Content-Type", contentType)
req.Header.Add("Stripe-Version", APIVersion)
req.Header.Add("User-Agent", encodedUserAgent)
req.Header.Add("X-Stripe-Client-User-Agent", getEncodedStripeUserAgent())
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 {
// Use Set to override the default value possibly set before
req.Header.Set(k, line)
}
}
}
return req, nil
}
func (s *BackendImplementation) maybeSetTelemetryHeader(req *http.Request) {
if s.enableTelemetry {
select {
case metrics := <-s.requestMetricsBuffer:
metricsJSON, err := json.Marshal(&requestTelemetry{LastRequestMetrics: metrics})
if err == nil {
req.Header.Set("X-Stripe-Client-Telemetry", string(metricsJSON))
} else {
s.LeveledLogger.Warnf("Unable to encode client telemetry: %v", err)
}
default:
// There are no metrics available, so don't send any.
// This default case needs to be here to prevent Do from blocking on an
// empty requestMetricsBuffer.
}
}
}
func (s *BackendImplementation) maybeEnqueueTelemetryMetrics(requestID string, requestDuration *time.Duration, usage []string) {
if !s.enableTelemetry || requestID == "" {
return
}
// If there's no duration to report and no usage to report, don't bother
if requestDuration == nil && len(usage) == 0 {
return
}
metrics := requestMetrics{
RequestID: requestID,
}
if requestDuration != nil {
requestDurationMS := int(*requestDuration / time.Millisecond)
metrics.RequestDurationMS = &requestDurationMS
}
if len(usage) > 0 {
metrics.Usage = usage
}
select {
case s.requestMetricsBuffer <- metrics:
default:
}
}
func resetBodyReader(body *bytes.Buffer, req *http.Request) {
// This might look a little strange, but we set the request's body
// outside of `NewRequest` so that we can get a fresh version every
// time.
//
// The background is that back in the era of old style HTTP, it was
// safe to reuse `Request` objects, but with the addition of HTTP/2,
// it's now only sometimes safe. Reusing a `Request` with a body will
// break.
//
// See some details here:
//
// https://github.com/golang/go/issues/19653#issuecomment-341539160
//
// And our original bug report here:
//
// https://github.com/stripe/stripe-go/issues/642
//
// To workaround the problem, we put a fresh `Body` onto the `Request`
// every time we execute it, and this seems to empirically resolve the
// problem.
if body != nil {
// We can safely reuse the same buffer that we used to encode our body,
// but return a new reader to it everytime so that each read is from
// the beginning.
reader := bytes.NewReader(body.Bytes())
req.Body = nopReadCloser{reader}
// And also add the same thing to `Request.GetBody`, which allows
// `net/http` to get a new body in cases like a redirect. This is
// usually not used, but it doesn't hurt to set it in case it's
// needed. See:
//
// https://github.com/stripe/stripe-go/issues/710
//
req.GetBody = func() (io.ReadCloser, error) {
reader := bytes.NewReader(body.Bytes())
return nopReadCloser{reader}, nil
}
}
}
// requestWithRetriesAndTelemetry uses s.HTTPClient to make an HTTP request,
// and handles retries, telemetry, and emitting log statements. It attempts to
// avoid processing the *result* of the HTTP request. It receives a
// "handleResponse" func from the caller, and it defers to that to determine
// whether the request was a failure or success, and to convert the
// response/error into the appropriate type of error or an appropriate result
// type.
func (s *BackendImplementation) requestWithRetriesAndTelemetry(
req *http.Request,
body *bytes.Buffer,
handleResponse func(*http.Response, error) (interface{}, error),
) (*http.Response, interface{}, *time.Duration, error) {
s.LeveledLogger.Infof("Requesting %v %v%v", req.Method, req.URL.Host, req.URL.Path)
s.maybeSetTelemetryHeader(req)
var resp *http.Response
var err error
var requestDuration time.Duration
var result interface{}
for retry := 0; ; {
start := time.Now()
resetBodyReader(body, req)
resp, err = s.HTTPClient.Do(req)
requestDuration = time.Since(start)
s.LeveledLogger.Infof("Request completed in %v (retry: %v)", requestDuration, retry)
result, err = handleResponse(resp, err)
// If the response was okay, or an error that shouldn't be retried,
// we're done, and it's safe to leave the retry loop.
shouldRetry, noRetryReason := s.shouldRetry(err, req, resp, retry)
if !shouldRetry {
s.LeveledLogger.Infof("Not retrying request: %v", noRetryReason)
break
}
sleepDuration := s.sleepTime(retry)
retry++
s.LeveledLogger.Warnf("Initiating retry %v for request %v %v%v after sleeping %v",
retry, req.Method, req.URL.Host, req.URL.Path, sleepDuration)
time.Sleep(sleepDuration)
}
if err != nil {
return nil, nil, nil, err
}
return resp, result, &requestDuration, nil
}
func (s *BackendImplementation) logError(statusCode int, err error) {
if stripeErr, ok := err.(*Error); ok {
// The Stripe API makes a distinction between errors that were
// caused by invalid parameters or something else versus those
// that occurred *despite* valid parameters, the latter coming
// back with status 402.
//
// On a 402, log to info so as to not make an integration's log
// noisy with error messages that they don't have much control
// over.
//
// Note I use the constant 402 instead of an `http.Status*`
// constant because technically 402 is "Payment required". The
// Stripe API doesn't comply to the letter of the specification
// and uses it in a broader sense.
if statusCode == 402 {
s.LeveledLogger.Infof("User-compelled request error from Stripe (status %v): %v",
statusCode, stripeErr.redact())
} else {
s.LeveledLogger.Errorf("Request error from Stripe (status %v): %v",
statusCode, stripeErr.redact())
}
} else {
s.LeveledLogger.Errorf("Error decoding error from Stripe: %v", err)
}
}
func (s *BackendImplementation) handleResponseBufferingErrors(res *http.Response, err error) (io.ReadCloser, error) {
// Some sort of connection error
if err != nil {
s.LeveledLogger.Errorf("Request failed with error: %v", err)
return res.Body, err
}
// Successful response, return the body ReadCloser
if res.StatusCode < 400 {
return res.Body, err
}
// Failure: try and parse the json of the response
// when logging the error
var resBody []byte
resBody, err = ioutil.ReadAll(res.Body)
res.Body.Close()
if err == nil {
err = s.ResponseToError(res, resBody)
} else {
s.logError(res.StatusCode, err)
}
return res.Body, err
}
// DoStreaming is used by CallStreaming to execute an API request. It uses the
// backend's HTTP client to execure the request. In successful cases, it sets
// a StreamingLastResponse onto v, but in unsuccessful cases handles unmarshaling
// errors returned by the API.
func (s *BackendImplementation) DoStreaming(req *http.Request, body *bytes.Buffer, v StreamingLastResponseSetter) error {
handleResponse := func(res *http.Response, err error) (interface{}, error) {
return s.handleResponseBufferingErrors(res, err)
}
resp, result, requestDuration, err := s.requestWithRetriesAndTelemetry(req, body, handleResponse)
if err != nil {
return err
}
v.SetLastResponse(newStreamingAPIResponse(resp, result.(io.ReadCloser), requestDuration))
return 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 *BackendImplementation) Do(req *http.Request, body *bytes.Buffer, v LastResponseSetter) error {
handleResponse := func(res *http.Response, err error) (interface{}, error) {
var resBody []byte
if err == nil {
resBody, err = ioutil.ReadAll(res.Body)
res.Body.Close()
}
if err != nil {
s.LeveledLogger.Errorf("Request failed with error: %v", err)
} else if res.StatusCode >= 400 {
err = s.ResponseToError(res, resBody)
s.logError(res.StatusCode, err)
}
return resBody, err
}
res, result, requestDuration, err := s.requestWithRetriesAndTelemetry(req, body, handleResponse)
if err != nil {
return err
}
resBody := result.([]byte)
s.LeveledLogger.Debugf("Response: %s", string(resBody))
err = s.UnmarshalJSONVerbose(res.StatusCode, resBody, v)
v.SetLastResponse(newAPIResponse(res, resBody, requestDuration))
return err
}
// ResponseToError converts a stripe response to an Error.
func (s *BackendImplementation) ResponseToError(res *http.Response, resBody []byte) error {
var raw rawError
if s.Type == ConnectBackend {
// If this is an OAuth request, deserialize as Error because OAuth errors
// are a different shape from the standard API errors.
var topLevelError Error
if err := s.UnmarshalJSONVerbose(res.StatusCode, resBody, &topLevelError); err != nil {
return err
}
raw.Error = &topLevelError
} else {
if err := s.UnmarshalJSONVerbose(res.StatusCode, resBody, &raw); err != nil {
return err
}
}
// no error in resBody
if raw.Error == nil {
err := errors.New(string(resBody))
return err
}
raw.Error.HTTPStatusCode = res.StatusCode
raw.Error.RequestID = res.Header.Get("Request-Id")
var typedError error
switch raw.Error.Type {
case ErrorTypeAPI:
typedError = &APIError{stripeErr: raw.Error}
case ErrorTypeCard:
cardErr := &CardError{stripeErr: raw.Error}
// `DeclineCode` was traditionally only available on `CardError`, but
// we ended up moving it to the top-level error as well. However, keep
// it on `CardError` for backwards compatibility.
if raw.Error.DeclineCode != "" {
cardErr.DeclineCode = raw.Error.DeclineCode
}
typedError = cardErr
case ErrorTypeIdempotency:
typedError = &IdempotencyError{stripeErr: raw.Error}
case ErrorTypeInvalidRequest:
typedError = &InvalidRequestError{stripeErr: raw.Error}
}
raw.Error.Err = typedError
raw.Error.SetLastResponse(newAPIResponse(res, resBody, nil))
return raw.Error
}
// SetMaxNetworkRetries sets max number of retries on failed requests
//
// This function is deprecated. Please use GetBackendWithConfig instead.
func (s *BackendImplementation) SetMaxNetworkRetries(maxNetworkRetries int64) {
s.MaxNetworkRetries = maxNetworkRetries
}
// SetNetworkRetriesSleep allows the normal sleep between network retries to be
// enabled or disabled.
//
// This function is available for internal testing only and should never be
// used in production.
func (s *BackendImplementation) SetNetworkRetriesSleep(sleep bool) {
s.networkRetriesSleep = sleep
}
// UnmarshalJSONVerbose unmarshals JSON, but in case of a failure logs and
// produces a more descriptive error.
func (s *BackendImplementation) UnmarshalJSONVerbose(statusCode int, body []byte, v interface{}) error {
err := json.Unmarshal(body, v)
if err != nil {
// If we got invalid JSON back then something totally unexpected is
// happening (caused by a bug on the server side). Put a sample of the
// response body into the error message so we can get a better feel for
// what the problem was.
bodySample := string(body)
if len(bodySample) > 500 {
bodySample = bodySample[0:500] + " ..."
}
// Make sure a multi-line response ends up all on one line
bodySample = strings.Replace(bodySample, "\n", "\\n", -1)
newErr := fmt.Errorf("Couldn't deserialize JSON (response status: %v, body sample: '%s'): %v",
statusCode, bodySample, err)
s.LeveledLogger.Errorf("%s", newErr.Error())
return newErr
}
return nil
}
// Regular expressions used to match a few error types that we know we don't
// want to retry. Unfortunately these errors aren't typed so we match on the
// error's message.
var (
redirectsErrorRE = regexp.MustCompile(`stopped after \d+ redirects\z`)
schemeErrorRE = regexp.MustCompile(`unsupported protocol scheme`)
)
// 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.
//
// Returns a boolean indicating whether a client should retry. If false, a
// second string parameter is also returned with a short message indicating why
// no retry should occur. This can be used for logging/informational purposes.
func (s *BackendImplementation) shouldRetry(err error, req *http.Request, resp *http.Response, numRetries int) (bool, string) {
if numRetries >= int(s.MaxNetworkRetries) {
return false, "max retries exceeded"
}
stripeErr, _ := err.(*Error)
// Don't retry if the context was canceled or its deadline was exceeded.
if req.Context() != nil && req.Context().Err() != nil {
switch req.Context().Err() {
case context.Canceled:
return false, "context canceled"
case context.DeadlineExceeded:
return false, "context deadline exceeded"
default:
return false, fmt.Sprintf("unknown context error: %v", req.Context().Err())
}
}
// We retry most errors that come out of HTTP requests except for a curated
// list that we know not to be retryable. This list is probably not
// exhaustive, so it'd be okay to add new errors to it. It'd also be okay to
// flip this to an inverted strategy of retrying only errors that we know
// to be retryable in a future refactor, if a good methodology is found for
// identifying that full set of errors.
if stripeErr == nil && err != nil {
if urlErr, ok := err.(*url.Error); ok {
// Don't retry too many redirects.
if redirectsErrorRE.MatchString(urlErr.Error()) {
return false, urlErr.Error()
}
// Don't retry invalid protocol scheme.
if schemeErrorRE.MatchString(urlErr.Error()) {
return false, urlErr.Error()
}
// Don't retry TLS certificate validation problems.
if _, ok := urlErr.Err.(x509.UnknownAuthorityError); ok {
return false, urlErr.Error()
}
}
// Do retry every other type of non-Stripe error.
return true, ""
}
// The API may ask us not to retry (e.g. if doing so would be a no-op), or
// advise us to retry (e.g. in cases of lock timeouts). Defer to those
// instructions if given.
if resp.Header.Get("Stripe-Should-Retry") == "false" {
return false, "`Stripe-Should-Retry` header returned `false`"
}
if resp.Header.Get("Stripe-Should-Retry") == "true" {
return true, ""