/
client.go
283 lines (237 loc) · 9.07 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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
// Copyright (C) 2020 Storj Labs, Inc.
// See LICENSE for copying information.
package stripe
import (
"bytes"
"context"
"errors"
"math"
"math/rand"
"net/http"
"time"
"github.com/stripe/stripe-go/v75"
"github.com/stripe/stripe-go/v75/charge"
"github.com/stripe/stripe-go/v75/client"
"github.com/stripe/stripe-go/v75/customer"
"github.com/stripe/stripe-go/v75/customerbalancetransaction"
"github.com/stripe/stripe-go/v75/form"
"github.com/stripe/stripe-go/v75/invoice"
"github.com/stripe/stripe-go/v75/invoiceitem"
"github.com/stripe/stripe-go/v75/paymentmethod"
"github.com/stripe/stripe-go/v75/promotioncode"
"go.uber.org/zap"
"storj.io/common/time2"
)
// Client Stripe client interface.
type Client interface {
Customers() Customers
PaymentMethods() PaymentMethods
Invoices() Invoices
InvoiceItems() InvoiceItems
CustomerBalanceTransactions() CustomerBalanceTransactions
Charges() Charges
PromoCodes() PromoCodes
CreditNotes() CreditNotes
}
// Customers Stripe Customers interface.
type Customers interface {
New(params *stripe.CustomerParams) (*stripe.Customer, error)
Get(id string, params *stripe.CustomerParams) (*stripe.Customer, error)
Update(id string, params *stripe.CustomerParams) (*stripe.Customer, error)
List(listParams *stripe.CustomerListParams) *customer.Iter
}
// PaymentMethods Stripe PaymentMethods interface.
type PaymentMethods interface {
List(listParams *stripe.PaymentMethodListParams) *paymentmethod.Iter
New(params *stripe.PaymentMethodParams) (*stripe.PaymentMethod, error)
Attach(id string, params *stripe.PaymentMethodAttachParams) (*stripe.PaymentMethod, error)
Detach(id string, params *stripe.PaymentMethodDetachParams) (*stripe.PaymentMethod, error)
}
// Invoices Stripe Invoices interface.
type Invoices interface {
New(params *stripe.InvoiceParams) (*stripe.Invoice, error)
List(listParams *stripe.InvoiceListParams) *invoice.Iter
Update(id string, params *stripe.InvoiceParams) (*stripe.Invoice, error)
FinalizeInvoice(id string, params *stripe.InvoiceFinalizeInvoiceParams) (*stripe.Invoice, error)
Pay(id string, params *stripe.InvoicePayParams) (*stripe.Invoice, error)
Del(id string, params *stripe.InvoiceParams) (*stripe.Invoice, error)
Get(id string, params *stripe.InvoiceParams) (*stripe.Invoice, error)
MarkUncollectible(id string, params *stripe.InvoiceMarkUncollectibleParams) (*stripe.Invoice, error)
VoidInvoice(id string, params *stripe.InvoiceVoidInvoiceParams) (*stripe.Invoice, error)
}
// InvoiceItems Stripe InvoiceItems interface.
type InvoiceItems interface {
New(params *stripe.InvoiceItemParams) (*stripe.InvoiceItem, error)
Update(id string, params *stripe.InvoiceItemParams) (*stripe.InvoiceItem, error)
List(listParams *stripe.InvoiceItemListParams) *invoiceitem.Iter
Del(id string, params *stripe.InvoiceItemParams) (*stripe.InvoiceItem, error)
}
// Charges Stripe Charges interface.
type Charges interface {
List(listParams *stripe.ChargeListParams) *charge.Iter
}
// PromoCodes is the Stripe PromoCodes interface.
type PromoCodes interface {
List(params *stripe.PromotionCodeListParams) *promotioncode.Iter
}
// CustomerBalanceTransactions Stripe CustomerBalanceTransactions interface.
type CustomerBalanceTransactions interface {
New(params *stripe.CustomerBalanceTransactionParams) (*stripe.CustomerBalanceTransaction, error)
List(listParams *stripe.CustomerBalanceTransactionListParams) *customerbalancetransaction.Iter
}
// CreditNotes Stripe CreditNotes interface.
type CreditNotes interface {
New(params *stripe.CreditNoteParams) (*stripe.CreditNote, error)
}
type stripeClient struct {
client *client.API
}
func (s *stripeClient) Customers() Customers {
return s.client.Customers
}
func (s *stripeClient) PaymentMethods() PaymentMethods {
return s.client.PaymentMethods
}
func (s *stripeClient) Invoices() Invoices {
return s.client.Invoices
}
func (s *stripeClient) InvoiceItems() InvoiceItems {
return s.client.InvoiceItems
}
func (s *stripeClient) CustomerBalanceTransactions() CustomerBalanceTransactions {
return s.client.CustomerBalanceTransactions
}
func (s *stripeClient) Charges() Charges {
return s.client.Charges
}
func (s *stripeClient) PromoCodes() PromoCodes {
return s.client.PromotionCodes
}
func (s *stripeClient) CreditNotes() CreditNotes {
return s.client.CreditNotes
}
// NewStripeClient creates Stripe client from configuration.
func NewStripeClient(log *zap.Logger, config Config) Client {
sClient := client.New(config.StripeSecretKey,
&stripe.Backends{
API: NewBackendWrapper(log, stripe.APIBackend, config.Retries),
Connect: NewBackendWrapper(log, stripe.ConnectBackend, config.Retries),
Uploads: NewBackendWrapper(log, stripe.UploadsBackend, config.Retries),
},
)
return &stripeClient{client: sClient}
}
// RetryConfig contains the configuration for an exponential backoff strategy when retrying Stripe API calls.
type RetryConfig struct {
InitialBackoff time.Duration `help:"the duration of the first retry interval" default:"20ms"`
MaxBackoff time.Duration `help:"the maximum duration of any retry interval" default:"5s"`
Multiplier float64 `help:"the factor by which the retry interval will be multiplied on each iteration" default:"2"`
MaxRetries int64 `help:"the maximum number of times to retry a request" default:"10"`
}
// BackendWrapper is a wrapper for the Stripe backend that uses an exponential backoff strategy for retrying Stripe API calls.
type BackendWrapper struct {
backend stripe.Backend
retryCfg RetryConfig
clock time2.Clock
}
// NewBackendWrapper creates a new wrapper for a Stripe backend.
func NewBackendWrapper(log *zap.Logger, backendType stripe.SupportedBackend, retryCfg RetryConfig) *BackendWrapper {
backendConfig := &stripe.BackendConfig{
LeveledLogger: log.Sugar(),
// Disable internal retries since we have our own retry+backoff strategy.
MaxNetworkRetries: stripe.Int64(0),
}
return &BackendWrapper{
retryCfg: retryCfg,
backend: stripe.GetBackendWithConfig(backendType, backendConfig),
}
}
// TestSwapBackend replaces the wrapped backend with the one specified for use in testing.
func (w *BackendWrapper) TestSwapBackend(backend stripe.Backend) {
w.backend = backend
}
// TestSwapClock replaces the internal clock with the one specified for use in testing.
func (w *BackendWrapper) TestSwapClock(clock time2.Clock) {
w.clock = clock
}
// Call implements the stripe.Backend interface.
func (w *BackendWrapper) Call(method, path, key string, params stripe.ParamsContainer, v stripe.LastResponseSetter) error {
return w.withRetries(params, func() error {
return w.backend.Call(method, path, key, params, v)
})
}
// CallStreaming implements the stripe.Backend interface.
func (w *BackendWrapper) CallStreaming(method, path, key string, params stripe.ParamsContainer, v stripe.StreamingLastResponseSetter) error {
return w.withRetries(params, func() error {
return w.backend.CallStreaming(method, path, key, params, v)
})
}
// CallRaw implements the stripe.Backend interface.
func (w *BackendWrapper) CallRaw(method, path, key string, body *form.Values, params *stripe.Params, v stripe.LastResponseSetter) error {
return w.withRetries(params, func() error {
return w.backend.CallRaw(method, path, key, body, params, v)
})
}
// CallMultipart implements the stripe.Backend interface.
func (w *BackendWrapper) CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *stripe.Params, v stripe.LastResponseSetter) error {
return w.withRetries(params, func() error {
return w.backend.CallMultipart(method, path, key, boundary, body, params, v)
})
}
// SetMaxNetworkRetries sets the maximum number of times to retry failed requests.
func (w *BackendWrapper) SetMaxNetworkRetries(max int64) {
w.retryCfg.MaxRetries = max
}
// withRetries executes the provided Stripe API call using an exponential backoff strategy
// for retrying in the case of failure.
func (w *BackendWrapper) withRetries(params stripe.ParamsContainer, call func() error) error {
ctx := context.Background()
if params != nil {
innerParams := params.GetParams()
if innerParams != nil && innerParams.Context != nil {
ctx = innerParams.Context
}
}
if err := ctx.Err(); err != nil {
return err
}
for retry := int64(0); ; retry++ {
err := call()
if err == nil {
return nil
}
if !w.shouldRetry(retry, err) {
return err
}
minBackoff := float64(w.retryCfg.InitialBackoff)
maxBackoff := math.Min(
float64(w.retryCfg.MaxBackoff),
minBackoff*math.Pow(w.retryCfg.Multiplier, float64(retry)),
)
backoff := minBackoff + rand.Float64()*(maxBackoff-minBackoff)
if !w.clock.Sleep(ctx, time.Duration(backoff)) {
return ctx.Err()
}
}
}
// shouldRetry returns whether a Stripe API call should be retried.
func (w *BackendWrapper) shouldRetry(retry int64, err error) bool {
if retry >= w.retryCfg.MaxRetries {
return false
}
var stripeErr *stripe.Error
if !errors.As(err, &stripeErr) {
return false
}
resp := stripeErr.LastResponse
if resp == nil {
return false
}
switch resp.Header.Get("Stripe-Should-Retry") {
case "true":
return true
case "false":
return false
}
return resp.StatusCode == http.StatusTooManyRequests
}