stripe 4.9.0 → 5.28.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/.editorconfig +10 -0
- data/.rubocop.yml +56 -8
- data/.rubocop_todo.yml +8 -25
- data/.travis.yml +4 -8
- data/.vscode/extensions.json +7 -0
- data/.vscode/settings.json +8 -0
- data/CHANGELOG.md +206 -2
- data/CODE_OF_CONDUCT.md +77 -0
- data/Gemfile +10 -13
- data/README.md +178 -58
- data/Rakefile +8 -7
- data/VERSION +1 -1
- data/lib/stripe.rb +41 -195
- data/lib/stripe/api_operations/create.rb +1 -1
- data/lib/stripe/api_operations/delete.rb +28 -2
- data/lib/stripe/api_operations/list.rb +1 -12
- data/lib/stripe/api_operations/nested_resource.rb +38 -28
- data/lib/stripe/api_operations/request.rb +47 -8
- data/lib/stripe/api_operations/save.rb +8 -7
- data/lib/stripe/api_resource.rb +52 -3
- data/lib/stripe/connection_manager.rb +162 -0
- data/lib/stripe/error_object.rb +94 -0
- data/lib/stripe/errors.rb +31 -10
- data/lib/stripe/instrumentation.rb +82 -0
- data/lib/stripe/list_object.rb +41 -7
- data/lib/stripe/multipart_encoder.rb +131 -0
- data/lib/stripe/oauth.rb +4 -3
- data/lib/stripe/object_types.rb +101 -0
- data/lib/stripe/resources.rb +84 -0
- data/lib/stripe/{account.rb → resources/account.rb} +50 -27
- data/lib/stripe/{account_link.rb → resources/account_link.rb} +2 -1
- data/lib/stripe/resources/alipay_account.rb +34 -0
- data/lib/stripe/{apple_pay_domain.rb → resources/apple_pay_domain.rb} +2 -1
- data/lib/stripe/resources/application_fee.rb +14 -0
- data/lib/stripe/resources/application_fee_refund.rb +30 -0
- data/lib/stripe/{balance.rb → resources/balance.rb} +2 -1
- data/lib/stripe/{balance_transaction.rb → resources/balance_transaction.rb} +2 -5
- data/lib/stripe/resources/bank_account.rb +43 -0
- data/lib/stripe/resources/billing_portal/session.rb +12 -0
- data/lib/stripe/{bitcoin_receiver.rb → resources/bitcoin_receiver.rb} +4 -3
- data/lib/stripe/{bitcoin_transaction.rb → resources/bitcoin_transaction.rb} +1 -1
- data/lib/stripe/resources/capability.rb +33 -0
- data/lib/stripe/{card.rb → resources/card.rb} +13 -4
- data/lib/stripe/resources/charge.rb +23 -0
- data/lib/stripe/resources/checkout/session.rb +16 -0
- data/lib/stripe/{country_spec.rb → resources/country_spec.rb} +2 -1
- data/lib/stripe/{coupon.rb → resources/coupon.rb} +3 -2
- data/lib/stripe/resources/credit_note.rb +33 -0
- data/lib/stripe/resources/credit_note_line_item.rb +7 -0
- data/lib/stripe/resources/customer.rb +36 -0
- data/lib/stripe/resources/customer_balance_transaction.rb +30 -0
- data/lib/stripe/resources/discount.rb +7 -0
- data/lib/stripe/resources/dispute.rb +22 -0
- data/lib/stripe/{ephemeral_key.rb → resources/ephemeral_key.rb} +6 -2
- data/lib/stripe/{event.rb → resources/event.rb} +2 -1
- data/lib/stripe/{exchange_rate.rb → resources/exchange_rate.rb} +2 -1
- data/lib/stripe/{file.rb → resources/file.rb} +9 -11
- data/lib/stripe/{file_link.rb → resources/file_link.rb} +3 -2
- data/lib/stripe/resources/invoice.rb +74 -0
- data/lib/stripe/{invoice_item.rb → resources/invoice_item.rb} +3 -2
- data/lib/stripe/{invoice_line_item.rb → resources/invoice_line_item.rb} +1 -1
- data/lib/stripe/resources/issuing/authorization.rb +34 -0
- data/lib/stripe/resources/issuing/card.rb +25 -0
- data/lib/stripe/{issuing → resources/issuing}/card_details.rb +1 -1
- data/lib/stripe/{issuing → resources/issuing}/cardholder.rb +3 -2
- data/lib/stripe/resources/issuing/dispute.rb +25 -0
- data/lib/stripe/{issuing → resources/issuing}/transaction.rb +3 -2
- data/lib/stripe/resources/line_item.rb +7 -0
- data/lib/stripe/resources/login_link.rb +14 -0
- data/lib/stripe/resources/mandate.rb +8 -0
- data/lib/stripe/resources/order.rb +33 -0
- data/lib/stripe/{order_return.rb → resources/order_return.rb} +2 -1
- data/lib/stripe/resources/payment_intent.rb +43 -0
- data/lib/stripe/resources/payment_method.rb +33 -0
- data/lib/stripe/resources/payout.rb +33 -0
- data/lib/stripe/{person.rb → resources/person.rb} +8 -3
- data/lib/stripe/{plan.rb → resources/plan.rb} +2 -1
- data/lib/stripe/resources/price.rb +12 -0
- data/lib/stripe/{product.rb → resources/product.rb} +4 -3
- data/lib/stripe/resources/promotion_code.rb +12 -0
- data/lib/stripe/resources/radar/early_fraud_warning.rb +12 -0
- data/lib/stripe/{radar → resources/radar}/value_list.rb +3 -2
- data/lib/stripe/{radar → resources/radar}/value_list_item.rb +3 -2
- data/lib/stripe/{recipient.rb → resources/recipient.rb} +3 -6
- data/lib/stripe/{recipient_transfer.rb → resources/recipient_transfer.rb} +1 -1
- data/lib/stripe/{refund.rb → resources/refund.rb} +2 -1
- data/lib/stripe/{reporting → resources/reporting}/report_run.rb +3 -2
- data/lib/stripe/{reporting → resources/reporting}/report_type.rb +3 -2
- data/lib/stripe/resources/reversal.rb +29 -0
- data/lib/stripe/resources/review.rb +21 -0
- data/lib/stripe/resources/setup_attempt.rb +10 -0
- data/lib/stripe/resources/setup_intent.rb +33 -0
- data/lib/stripe/{sigma → resources/sigma}/scheduled_query_run.rb +3 -2
- data/lib/stripe/{sku.rb → resources/sku.rb} +4 -3
- data/lib/stripe/resources/source.rb +47 -0
- data/lib/stripe/{source_transaction.rb → resources/source_transaction.rb} +1 -1
- data/lib/stripe/resources/subscription.rb +26 -0
- data/lib/stripe/resources/subscription_item.rb +26 -0
- data/lib/stripe/resources/subscription_schedule.rb +33 -0
- data/lib/stripe/resources/tax_id.rb +26 -0
- data/lib/stripe/resources/tax_rate.rb +12 -0
- data/lib/stripe/resources/terminal/connection_token.rb +12 -0
- data/lib/stripe/{terminal → resources/terminal}/location.rb +4 -2
- data/lib/stripe/{terminal → resources/terminal}/reader.rb +4 -2
- data/lib/stripe/{three_d_secure.rb → resources/three_d_secure.rb} +2 -1
- data/lib/stripe/{token.rb → resources/token.rb} +2 -1
- data/lib/stripe/resources/topup.rb +23 -0
- data/lib/stripe/resources/transfer.rb +27 -0
- data/lib/stripe/resources/usage_record.rb +7 -0
- data/lib/stripe/{usage_record_summary.rb → resources/usage_record_summary.rb} +1 -1
- data/lib/stripe/{webhook_endpoint.rb → resources/webhook_endpoint.rb} +3 -2
- data/lib/stripe/singleton_api_resource.rb +3 -1
- data/lib/stripe/stripe_client.rb +493 -236
- data/lib/stripe/stripe_configuration.rb +178 -0
- data/lib/stripe/stripe_object.rb +75 -61
- data/lib/stripe/stripe_response.rb +53 -21
- data/lib/stripe/util.rb +66 -109
- data/lib/stripe/version.rb +1 -1
- data/lib/stripe/webhook.rb +43 -10
- data/stripe.gemspec +14 -5
- data/test/stripe/account_link_test.rb +4 -4
- data/test/stripe/account_test.rb +193 -32
- data/test/stripe/alipay_account_test.rb +1 -1
- data/test/stripe/api_operations_test.rb +3 -4
- data/test/stripe/api_resource_test.rb +159 -37
- data/test/stripe/apple_pay_domain_test.rb +18 -5
- data/test/stripe/application_fee_refund_test.rb +1 -1
- data/test/stripe/application_fee_test.rb +45 -1
- data/test/stripe/balance_test.rb +1 -1
- data/test/stripe/balance_transaction_test.rb +20 -0
- data/test/stripe/bank_account_test.rb +1 -1
- data/test/stripe/billing_portal/session_test.rb +18 -0
- data/test/stripe/capability_test.rb +45 -0
- data/test/stripe/charge_test.rb +13 -8
- data/test/stripe/checkout/session_test.rb +19 -1
- data/test/stripe/connection_manager_test.rb +167 -0
- data/test/stripe/country_spec_test.rb +1 -1
- data/test/stripe/coupon_test.rb +16 -6
- data/test/stripe/credit_note_test.rb +90 -0
- data/test/stripe/customer_balance_transaction_test.rb +37 -0
- data/test/stripe/customer_card_test.rb +7 -1
- data/test/stripe/customer_test.rb +151 -40
- data/test/stripe/dispute_test.rb +10 -1
- data/test/stripe/ephemeral_key_test.rb +8 -1
- data/test/stripe/errors_test.rb +42 -9
- data/test/stripe/exchange_rate_test.rb +1 -1
- data/test/stripe/file_link_test.rb +1 -1
- data/test/stripe/file_test.rb +19 -5
- data/test/stripe/instrumentation_test.rb +74 -0
- data/test/stripe/invoice_item_test.rb +18 -7
- data/test/stripe/invoice_line_item_test.rb +1 -1
- data/test/stripe/invoice_test.rb +77 -9
- data/test/stripe/issuing/authorization_test.rb +33 -11
- data/test/stripe/issuing/card_test.rb +27 -6
- data/test/stripe/issuing/cardholder_test.rb +1 -1
- data/test/stripe/issuing/dispute_test.rb +23 -14
- data/test/stripe/issuing/transaction_test.rb +1 -1
- data/test/stripe/list_object_test.rb +70 -24
- data/test/stripe/login_link_test.rb +2 -2
- data/test/stripe/mandate_test.rb +14 -0
- data/test/stripe/multipart_encoder_test.rb +130 -0
- data/test/stripe/oauth_test.rb +17 -1
- data/test/stripe/order_return_test.rb +1 -1
- data/test/stripe/order_test.rb +28 -3
- data/test/stripe/payment_intent_test.rb +31 -4
- data/test/stripe/payment_method_test.rb +84 -0
- data/test/stripe/payout_test.rb +23 -1
- data/test/stripe/person_test.rb +1 -1
- data/test/stripe/plan_test.rb +26 -20
- data/test/stripe/price_test.rb +48 -0
- data/test/stripe/product_test.rb +17 -8
- data/test/stripe/promotion_code_test.rb +42 -0
- data/test/stripe/radar/early_fraud_warning_test.rb +22 -0
- data/test/stripe/radar/value_list_item_test.rb +16 -6
- data/test/stripe/radar/value_list_test.rb +16 -6
- data/test/stripe/recipient_test.rb +18 -5
- data/test/stripe/refund_test.rb +1 -1
- data/test/stripe/reporting/report_run_test.rb +1 -1
- data/test/stripe/reporting/report_type_test.rb +1 -1
- data/test/stripe/reversal_test.rb +1 -1
- data/test/stripe/review_test.rb +1 -1
- data/test/stripe/setup_attempt_test.rb +16 -0
- data/test/stripe/setup_intent_test.rb +84 -0
- data/test/stripe/sigma/scheduled_query_run_test.rb +1 -1
- data/test/stripe/sku_test.rb +16 -6
- data/test/stripe/source_test.rb +52 -19
- data/test/stripe/stripe_client_test.rb +546 -78
- data/test/stripe/stripe_configuration_test.rb +131 -0
- data/test/stripe/stripe_object_test.rb +16 -41
- data/test/stripe/stripe_response_test.rb +71 -25
- data/test/stripe/subscription_item_test.rb +38 -7
- data/test/stripe/subscription_schedule_test.rb +19 -1
- data/test/stripe/subscription_test.rb +29 -9
- data/test/stripe/tax_id_test.rb +31 -0
- data/test/stripe/tax_rate_test.rb +43 -0
- data/test/stripe/terminal/connection_token_test.rb +1 -1
- data/test/stripe/terminal/location_test.rb +18 -1
- data/test/stripe/terminal/reader_test.rb +18 -1
- data/test/stripe/three_d_secure_test.rb +1 -1
- data/test/stripe/topup_test.rb +9 -1
- data/test/stripe/transfer_test.rb +46 -1
- data/test/stripe/usage_record_summary_test.rb +15 -5
- data/test/stripe/util_test.rb +1 -1
- data/test/stripe/webhook_endpoint_test.rb +18 -1
- data/test/stripe/webhook_test.rb +48 -9
- data/test/stripe_mock.rb +4 -3
- data/test/stripe_test.rb +102 -33
- data/test/test_helper.rb +16 -12
- metadata +141 -129
- data/lib/stripe/alipay_account.rb +0 -27
- data/lib/stripe/application_fee.rb +0 -23
- data/lib/stripe/application_fee_refund.rb +0 -22
- data/lib/stripe/bank_account.rb +0 -32
- data/lib/stripe/charge.rb +0 -84
- data/lib/stripe/checkout/session.rb +0 -11
- data/lib/stripe/customer.rb +0 -90
- data/lib/stripe/dispute.rb +0 -19
- data/lib/stripe/invoice.rb +0 -48
- data/lib/stripe/issuer_fraud_record.rb +0 -9
- data/lib/stripe/issuing/authorization.rb +0 -22
- data/lib/stripe/issuing/card.rb +0 -18
- data/lib/stripe/issuing/dispute.rb +0 -13
- data/lib/stripe/login_link.rb +0 -11
- data/lib/stripe/order.rb +0 -31
- data/lib/stripe/payment_intent.rb +0 -26
- data/lib/stripe/payout.rb +0 -20
- data/lib/stripe/reversal.rb +0 -22
- data/lib/stripe/review.rb +0 -14
- data/lib/stripe/source.rb +0 -38
- data/lib/stripe/subscription.rb +0 -25
- data/lib/stripe/subscription_item.rb +0 -17
- data/lib/stripe/subscription_schedule.rb +0 -32
- data/lib/stripe/subscription_schedule_revision.rb +0 -25
- data/lib/stripe/terminal/connection_token.rb +0 -11
- data/lib/stripe/topup.rb +0 -16
- data/lib/stripe/transfer.rb +0 -23
- data/lib/stripe/usage_record.rb +0 -14
- data/test/api_stub_helpers.rb +0 -1
- data/test/stripe/account_external_accounts_operations_test.rb +0 -69
- data/test/stripe/account_login_links_operations_test.rb +0 -21
- data/test/stripe/account_persons_operations_test.rb +0 -70
- data/test/stripe/application_fee_refunds_operations_test.rb +0 -56
- data/test/stripe/customer_sources_operations_test.rb +0 -64
- data/test/stripe/file_upload_test.rb +0 -76
- data/test/stripe/issuer_fraud_record_test.rb +0 -20
- data/test/stripe/source_transaction_test.rb +0 -19
- data/test/stripe/subscription_schedule_revision_test.rb +0 -37
- data/test/stripe/subscription_schedule_revisions_operations_test.rb +0 -35
- data/test/stripe/transfer_reversals_operations_test.rb +0 -57
- data/test/stripe/usage_record_test.rb +0 -28
@@ -1,13 +1,15 @@
|
|
1
|
+
# File generated from our OpenAPI spec
|
1
2
|
# frozen_string_literal: true
|
2
3
|
|
3
4
|
module Stripe
|
4
5
|
module Terminal
|
5
|
-
class Location <
|
6
|
+
class Location < APIResource
|
6
7
|
extend Stripe::APIOperations::Create
|
8
|
+
include Stripe::APIOperations::Delete
|
7
9
|
extend Stripe::APIOperations::List
|
8
10
|
include Stripe::APIOperations::Save
|
9
11
|
|
10
|
-
OBJECT_NAME = "terminal.location"
|
12
|
+
OBJECT_NAME = "terminal.location"
|
11
13
|
end
|
12
14
|
end
|
13
15
|
end
|
@@ -1,13 +1,15 @@
|
|
1
|
+
# File generated from our OpenAPI spec
|
1
2
|
# frozen_string_literal: true
|
2
3
|
|
3
4
|
module Stripe
|
4
5
|
module Terminal
|
5
|
-
class Reader <
|
6
|
+
class Reader < APIResource
|
6
7
|
extend Stripe::APIOperations::Create
|
8
|
+
include Stripe::APIOperations::Delete
|
7
9
|
extend Stripe::APIOperations::List
|
8
10
|
include Stripe::APIOperations::Save
|
9
11
|
|
10
|
-
OBJECT_NAME = "terminal.reader"
|
12
|
+
OBJECT_NAME = "terminal.reader"
|
11
13
|
end
|
12
14
|
end
|
13
15
|
end
|
@@ -1,10 +1,11 @@
|
|
1
|
+
# File generated from our OpenAPI spec
|
1
2
|
# frozen_string_literal: true
|
2
3
|
|
3
4
|
module Stripe
|
4
5
|
class ThreeDSecure < APIResource
|
5
6
|
extend Stripe::APIOperations::Create
|
6
7
|
|
7
|
-
OBJECT_NAME = "three_d_secure"
|
8
|
+
OBJECT_NAME = "three_d_secure"
|
8
9
|
|
9
10
|
def self.resource_url
|
10
11
|
"/v1/3d_secure"
|
@@ -0,0 +1,23 @@
|
|
1
|
+
# File generated from our OpenAPI spec
|
2
|
+
# frozen_string_literal: true
|
3
|
+
|
4
|
+
module Stripe
|
5
|
+
class Topup < APIResource
|
6
|
+
extend Stripe::APIOperations::Create
|
7
|
+
extend Stripe::APIOperations::List
|
8
|
+
include Stripe::APIOperations::Save
|
9
|
+
|
10
|
+
OBJECT_NAME = "topup"
|
11
|
+
|
12
|
+
custom_method :cancel, http_verb: :post
|
13
|
+
|
14
|
+
def cancel(params = {}, opts = {})
|
15
|
+
request_stripe_object(
|
16
|
+
method: :post,
|
17
|
+
path: resource_url + "/cancel",
|
18
|
+
params: params,
|
19
|
+
opts: opts
|
20
|
+
)
|
21
|
+
end
|
22
|
+
end
|
23
|
+
end
|
@@ -0,0 +1,27 @@
|
|
1
|
+
# File generated from our OpenAPI spec
|
2
|
+
# frozen_string_literal: true
|
3
|
+
|
4
|
+
module Stripe
|
5
|
+
class Transfer < APIResource
|
6
|
+
extend Stripe::APIOperations::Create
|
7
|
+
extend Stripe::APIOperations::List
|
8
|
+
include Stripe::APIOperations::Save
|
9
|
+
extend Stripe::APIOperations::NestedResource
|
10
|
+
|
11
|
+
OBJECT_NAME = "transfer"
|
12
|
+
|
13
|
+
custom_method :cancel, http_verb: :post
|
14
|
+
|
15
|
+
nested_resource_class_methods :reversal,
|
16
|
+
operations: %i[create retrieve update list]
|
17
|
+
|
18
|
+
def cancel(params = {}, opts = {})
|
19
|
+
request_stripe_object(
|
20
|
+
method: :post,
|
21
|
+
path: resource_url + "/cancel",
|
22
|
+
params: params,
|
23
|
+
opts: opts
|
24
|
+
)
|
25
|
+
end
|
26
|
+
end
|
27
|
+
end
|
@@ -1,12 +1,13 @@
|
|
1
|
+
# File generated from our OpenAPI spec
|
1
2
|
# frozen_string_literal: true
|
2
3
|
|
3
4
|
module Stripe
|
4
5
|
class WebhookEndpoint < APIResource
|
5
6
|
extend Stripe::APIOperations::Create
|
6
|
-
include Stripe::APIOperations::Save
|
7
7
|
include Stripe::APIOperations::Delete
|
8
8
|
extend Stripe::APIOperations::List
|
9
|
+
include Stripe::APIOperations::Save
|
9
10
|
|
10
|
-
OBJECT_NAME = "webhook_endpoint"
|
11
|
+
OBJECT_NAME = "webhook_endpoint"
|
11
12
|
end
|
12
13
|
end
|
@@ -4,7 +4,9 @@ module Stripe
|
|
4
4
|
class SingletonAPIResource < APIResource
|
5
5
|
def self.resource_url
|
6
6
|
if self == SingletonAPIResource
|
7
|
-
raise NotImplementedError,
|
7
|
+
raise NotImplementedError,
|
8
|
+
"SingletonAPIResource is an abstract class. You should " \
|
9
|
+
"perform actions on its subclasses (Balance, etc.)"
|
8
10
|
end
|
9
11
|
# Namespaces are separated in object names with periods (.) and in URLs
|
10
12
|
# with forward slashes (/), so replace the former with the latter.
|
data/lib/stripe/stripe_client.rb
CHANGED
@@ -1,98 +1,143 @@
|
|
1
1
|
# frozen_string_literal: true
|
2
2
|
|
3
|
+
require "stripe/instrumentation"
|
4
|
+
|
3
5
|
module Stripe
|
4
6
|
# StripeClient executes requests against the Stripe API and allows a user to
|
5
7
|
# recover both a resource a call returns as well as a response object that
|
6
8
|
# contains information on the HTTP call.
|
7
9
|
class StripeClient
|
8
|
-
|
10
|
+
# A set of all known thread contexts across all threads and a mutex to
|
11
|
+
# synchronize global access to them.
|
12
|
+
@thread_contexts_with_connection_managers = []
|
13
|
+
@thread_contexts_with_connection_managers_mutex = Mutex.new
|
14
|
+
@last_connection_manager_gc = Util.monotonic_time
|
9
15
|
|
10
|
-
# Initializes a new StripeClient
|
11
|
-
#
|
12
|
-
|
13
|
-
|
16
|
+
# Initializes a new `StripeClient`.
|
17
|
+
#
|
18
|
+
# Takes a connection manager object for backwards compatibility only, and
|
19
|
+
# that use is DEPRECATED.
|
20
|
+
def initialize(_connection_manager = nil)
|
14
21
|
@system_profiler = SystemProfiler.new
|
15
22
|
@last_request_metrics = nil
|
16
23
|
end
|
17
24
|
|
25
|
+
# Gets a currently active `StripeClient`. Set for the current thread when
|
26
|
+
# `StripeClient#request` is being run so that API operations being executed
|
27
|
+
# inside of that block can find the currently active client. It's reset to
|
28
|
+
# the original value (hopefully `nil`) after the block ends.
|
29
|
+
#
|
30
|
+
# For internal use only. Does not provide a stable API and may be broken
|
31
|
+
# with future non-major changes.
|
18
32
|
def self.active_client
|
19
|
-
|
33
|
+
current_thread_context.active_client || default_client
|
20
34
|
end
|
21
35
|
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
|
26
|
-
#
|
27
|
-
#
|
28
|
-
|
29
|
-
|
30
|
-
#
|
31
|
-
#
|
32
|
-
|
33
|
-
|
34
|
-
|
35
|
-
|
36
|
-
|
37
|
-
|
38
|
-
|
39
|
-
#
|
40
|
-
|
41
|
-
|
42
|
-
builder.adapter :net_http
|
43
|
-
else
|
44
|
-
builder.adapter :net_http_persistent
|
45
|
-
end
|
36
|
+
# Finishes any active connections by closing their TCP connection and
|
37
|
+
# clears them from internal tracking in all connection managers across all
|
38
|
+
# threads.
|
39
|
+
#
|
40
|
+
# For internal use only. Does not provide a stable API and may be broken
|
41
|
+
# with future non-major changes.
|
42
|
+
def self.clear_all_connection_managers
|
43
|
+
# Just a quick path for when configuration is being set for the first
|
44
|
+
# time before any connections have been opened. There is technically some
|
45
|
+
# potential for thread raciness here, but not in a practical sense.
|
46
|
+
return if @thread_contexts_with_connection_managers.empty?
|
47
|
+
|
48
|
+
@thread_contexts_with_connection_managers_mutex.synchronize do
|
49
|
+
@thread_contexts_with_connection_managers.each do |thread_context|
|
50
|
+
# Note that the thread context itself is not destroyed, but we clear
|
51
|
+
# its connection manager and remove our reference to it. If it ever
|
52
|
+
# makes a new request we'll give it a new connection manager and
|
53
|
+
# it'll go back into `@thread_contexts_with_connection_managers`.
|
54
|
+
thread_context.default_connection_manager.clear
|
55
|
+
thread_context.default_connection_manager = nil
|
46
56
|
end
|
57
|
+
@thread_contexts_with_connection_managers.clear
|
58
|
+
end
|
59
|
+
end
|
47
60
|
|
48
|
-
|
49
|
-
|
50
|
-
|
51
|
-
|
52
|
-
conn.ssl.verify = false
|
61
|
+
# A default client for the current thread.
|
62
|
+
def self.default_client
|
63
|
+
current_thread_context.default_client ||= StripeClient.new
|
64
|
+
end
|
53
65
|
|
54
|
-
|
55
|
-
|
56
|
-
|
57
|
-
|
58
|
-
|
59
|
-
|
66
|
+
# A default connection manager for the current thread.
|
67
|
+
def self.default_connection_manager
|
68
|
+
current_thread_context.default_connection_manager ||= begin
|
69
|
+
connection_manager = ConnectionManager.new
|
70
|
+
|
71
|
+
@thread_contexts_with_connection_managers_mutex.synchronize do
|
72
|
+
maybe_gc_connection_managers
|
73
|
+
@thread_contexts_with_connection_managers << current_thread_context
|
60
74
|
end
|
61
75
|
|
62
|
-
|
76
|
+
connection_manager
|
63
77
|
end
|
64
78
|
end
|
65
79
|
|
66
|
-
# Checks if an error is a problem that we should retry on. This includes
|
67
|
-
# socket errors that may represent an intermittent problem and some
|
68
|
-
# HTTP statuses.
|
69
|
-
def self.should_retry?(
|
80
|
+
# Checks if an error is a problem that we should retry on. This includes
|
81
|
+
# both socket errors that may represent an intermittent problem and some
|
82
|
+
# special HTTP statuses.
|
83
|
+
def self.should_retry?(error, method:, num_retries:)
|
70
84
|
return false if num_retries >= Stripe.max_network_retries
|
71
85
|
|
72
|
-
|
73
|
-
|
74
|
-
|
75
|
-
|
76
|
-
|
77
|
-
|
78
|
-
|
79
|
-
|
80
|
-
|
81
|
-
|
82
|
-
|
86
|
+
case error
|
87
|
+
when Net::OpenTimeout, Net::ReadTimeout
|
88
|
+
# Retry on timeout-related problems (either on open or read).
|
89
|
+
true
|
90
|
+
when EOFError, Errno::ECONNREFUSED, Errno::ECONNRESET,
|
91
|
+
Errno::EHOSTUNREACH, Errno::ETIMEDOUT, SocketError
|
92
|
+
# Destination refused the connection, the connection was reset, or a
|
93
|
+
# variety of other connection failures. This could occur from a single
|
94
|
+
# saturated server, so retry in case it's intermittent.
|
95
|
+
true
|
96
|
+
when Stripe::StripeError
|
97
|
+
# The API may ask us not to retry (e.g. if doing so would be a no-op),
|
98
|
+
# or advise us to retry (e.g. in cases of lock timeouts). Defer to
|
99
|
+
# those instructions if given.
|
100
|
+
return false if error.http_headers["stripe-should-retry"] == "false"
|
101
|
+
return true if error.http_headers["stripe-should-retry"] == "true"
|
102
|
+
|
103
|
+
# 409 Conflict
|
104
|
+
return true if error.http_status == 409
|
105
|
+
|
106
|
+
# 429 Too Many Requests
|
107
|
+
#
|
108
|
+
# There are a few different problems that can lead to a 429. The most
|
109
|
+
# common is rate limiting, on which we *don't* want to retry because
|
110
|
+
# that'd likely contribute to more contention problems. However, some
|
111
|
+
# 429s are lock timeouts, which is when a request conflicted with
|
112
|
+
# another request or an internal process on some particular object.
|
113
|
+
# These 429s are safe to retry.
|
114
|
+
return true if error.http_status == 429 && error.code == "lock_timeout"
|
115
|
+
|
116
|
+
# 500 Internal Server Error
|
117
|
+
#
|
118
|
+
# We only bother retrying these for non-POST requests. POSTs end up
|
119
|
+
# being cached by the idempotency layer so there's no purpose in
|
120
|
+
# retrying them.
|
121
|
+
return true if error.http_status == 500 && method != :post
|
122
|
+
|
123
|
+
# 503 Service Unavailable
|
124
|
+
error.http_status == 503
|
125
|
+
else
|
126
|
+
false
|
83
127
|
end
|
84
|
-
|
85
|
-
false
|
86
128
|
end
|
87
129
|
|
88
130
|
def self.sleep_time(num_retries)
|
89
131
|
# Apply exponential backoff with initial_network_retry_delay on the
|
90
|
-
# number of num_retries so far as inputs. Do not allow the number to
|
91
|
-
# max_network_retry_delay.
|
92
|
-
sleep_seconds = [
|
93
|
-
|
94
|
-
|
95
|
-
|
132
|
+
# number of num_retries so far as inputs. Do not allow the number to
|
133
|
+
# exceed max_network_retry_delay.
|
134
|
+
sleep_seconds = [
|
135
|
+
Stripe.initial_network_retry_delay * (2**(num_retries - 1)),
|
136
|
+
Stripe.max_network_retry_delay,
|
137
|
+
].min
|
138
|
+
|
139
|
+
# Apply some jitter by randomizing the value in the range of
|
140
|
+
# (sleep_seconds / 2) to (sleep_seconds).
|
96
141
|
sleep_seconds *= (0.5 * (1 + rand))
|
97
142
|
|
98
143
|
# But never sleep less than the base sleep seconds.
|
@@ -101,145 +146,267 @@ module Stripe
|
|
101
146
|
sleep_seconds
|
102
147
|
end
|
103
148
|
|
149
|
+
# Gets the connection manager in use for the current `StripeClient`.
|
150
|
+
#
|
151
|
+
# This method is DEPRECATED and for backwards compatibility only.
|
152
|
+
def connection_manager
|
153
|
+
self.class.default_connection_manager
|
154
|
+
end
|
155
|
+
extend Gem::Deprecate
|
156
|
+
deprecate :connection_manager, :none, 2020, 9
|
157
|
+
|
104
158
|
# Executes the API call within the given block. Usage looks like:
|
105
159
|
#
|
106
160
|
# client = StripeClient.new
|
107
161
|
# charge, resp = client.request { Charge.create }
|
108
162
|
#
|
109
163
|
def request
|
110
|
-
|
111
|
-
|
112
|
-
|
164
|
+
old_stripe_client = self.class.current_thread_context.active_client
|
165
|
+
self.class.current_thread_context.active_client = self
|
166
|
+
|
167
|
+
if self.class.current_thread_context.last_responses&.key?(object_id)
|
168
|
+
raise "calls to StripeClient#request cannot be nested within a thread"
|
169
|
+
end
|
170
|
+
|
171
|
+
self.class.current_thread_context.last_responses ||= {}
|
172
|
+
self.class.current_thread_context.last_responses[object_id] = nil
|
113
173
|
|
114
174
|
begin
|
115
175
|
res = yield
|
116
|
-
[res,
|
176
|
+
[res, self.class.current_thread_context.last_responses[object_id]]
|
117
177
|
ensure
|
118
|
-
|
178
|
+
self.class.current_thread_context.active_client = old_stripe_client
|
179
|
+
self.class.current_thread_context.last_responses.delete(object_id)
|
119
180
|
end
|
120
181
|
end
|
121
182
|
|
122
183
|
def execute_request(method, path,
|
123
184
|
api_base: nil, api_key: nil, headers: {}, params: {})
|
185
|
+
raise ArgumentError, "method should be a symbol" \
|
186
|
+
unless method.is_a?(Symbol)
|
187
|
+
raise ArgumentError, "path should be a string" \
|
188
|
+
unless path.is_a?(String)
|
189
|
+
|
124
190
|
api_base ||= Stripe.api_base
|
125
191
|
api_key ||= Stripe.api_key
|
126
192
|
params = Util.objects_to_ids(params)
|
127
193
|
|
128
194
|
check_api_key!(api_key)
|
129
195
|
|
130
|
-
|
196
|
+
body_params = nil
|
131
197
|
query_params = nil
|
132
|
-
case method
|
198
|
+
case method
|
133
199
|
when :get, :head, :delete
|
134
200
|
query_params = params
|
135
201
|
else
|
136
|
-
|
202
|
+
body_params = params
|
137
203
|
end
|
138
204
|
|
139
|
-
|
140
|
-
# parameters in `query_params` and query parameters that are appended
|
141
|
-
# onto the end of the given path. In this case, Faraday will silently
|
142
|
-
# discard the URL's parameters which may break a request.
|
143
|
-
#
|
144
|
-
# Here we decode any parameters that were added onto the end of a path
|
145
|
-
# and add them to `query_params` so that all parameters end up in one
|
146
|
-
# place and all of them are correctly included in the final request.
|
147
|
-
u = URI.parse(path)
|
148
|
-
unless u.query.nil?
|
149
|
-
query_params ||= {}
|
150
|
-
query_params = Hash[URI.decode_www_form(u.query)].merge(query_params)
|
151
|
-
|
152
|
-
# Reset the path minus any query parameters that were specified.
|
153
|
-
path = u.path
|
154
|
-
end
|
205
|
+
query_params, path = merge_query_params(query_params, path)
|
155
206
|
|
156
207
|
headers = request_headers(api_key, method)
|
157
208
|
.update(Util.normalize_headers(headers))
|
158
|
-
params_encoder = FaradayStripeEncoder.new
|
159
209
|
url = api_url(path, api_base)
|
160
210
|
|
211
|
+
# Merge given query parameters with any already encoded in the path.
|
212
|
+
query = query_params ? Util.encode_parameters(query_params) : nil
|
213
|
+
|
214
|
+
# Encoding body parameters is a little more complex because we may have
|
215
|
+
# to send a multipart-encoded body. `body_log` is produced separately as
|
216
|
+
# a log-friendly variant of the encoded form. File objects are displayed
|
217
|
+
# as such instead of as their file contents.
|
218
|
+
body, body_log =
|
219
|
+
body_params ? encode_body(body_params, headers) : [nil, nil]
|
220
|
+
|
161
221
|
# stores information on the request we're about to make so that we don't
|
162
222
|
# have to pass as many parameters around for logging.
|
163
223
|
context = RequestLogContext.new
|
164
224
|
context.account = headers["Stripe-Account"]
|
165
225
|
context.api_key = api_key
|
166
226
|
context.api_version = headers["Stripe-Version"]
|
167
|
-
context.body =
|
227
|
+
context.body = body_log
|
168
228
|
context.idempotency_key = headers["Idempotency-Key"]
|
169
229
|
context.method = method
|
170
230
|
context.path = path
|
171
|
-
context.
|
172
|
-
|
173
|
-
|
174
|
-
|
175
|
-
|
176
|
-
|
177
|
-
|
178
|
-
req.options.params_encoder = params_encoder
|
179
|
-
req.options.timeout = Stripe.read_timeout
|
180
|
-
req.params = query_params unless query_params.nil?
|
181
|
-
end
|
231
|
+
context.query = query
|
232
|
+
|
233
|
+
http_resp = execute_request_with_rescues(method, api_base, context) do
|
234
|
+
self.class.default_connection_manager.execute_request(method, url,
|
235
|
+
body: body,
|
236
|
+
headers: headers,
|
237
|
+
query: query)
|
182
238
|
end
|
183
239
|
|
184
240
|
begin
|
185
|
-
resp = StripeResponse.
|
241
|
+
resp = StripeResponse.from_net_http(http_resp)
|
186
242
|
rescue JSON::ParserError
|
187
|
-
raise general_api_error(http_resp.
|
243
|
+
raise general_api_error(http_resp.code.to_i, http_resp.body)
|
244
|
+
end
|
245
|
+
|
246
|
+
# If being called from `StripeClient#request`, put the last response in
|
247
|
+
# thread-local memory so that it can be returned to the user. Don't store
|
248
|
+
# anything otherwise so that we don't leak memory.
|
249
|
+
if self.class.current_thread_context.last_responses&.key?(object_id)
|
250
|
+
self.class.current_thread_context.last_responses[object_id] = resp
|
188
251
|
end
|
189
252
|
|
190
|
-
# Allows StripeClient#request to return a response object to a caller.
|
191
|
-
@last_response = resp
|
192
253
|
[resp, api_key]
|
193
254
|
end
|
194
255
|
|
195
|
-
|
256
|
+
#
|
257
|
+
# private
|
258
|
+
#
|
196
259
|
|
197
|
-
#
|
198
|
-
#
|
199
|
-
|
200
|
-
|
201
|
-
#
|
260
|
+
# Time (in seconds) that a connection manager has not been used before it's
|
261
|
+
# eligible for garbage collection.
|
262
|
+
CONNECTION_MANAGER_GC_LAST_USED_EXPIRY = 120
|
263
|
+
|
264
|
+
# How often to check (in seconds) for connection managers that haven't been
|
265
|
+
# used in a long time and which should be garbage collected.
|
266
|
+
CONNECTION_MANAGER_GC_PERIOD = 60
|
267
|
+
|
268
|
+
ERROR_MESSAGE_CONNECTION =
|
269
|
+
"Unexpected error communicating when trying to connect to " \
|
270
|
+
"Stripe (%s). You may be seeing this message because your DNS is not " \
|
271
|
+
"working or you don't have an internet connection. To check, try " \
|
272
|
+
"running `host stripe.com` from the command line."
|
273
|
+
ERROR_MESSAGE_SSL =
|
274
|
+
"Could not establish a secure connection to Stripe (%s), you " \
|
275
|
+
"may need to upgrade your OpenSSL version. To check, try running " \
|
276
|
+
"`openssl s_client -connect api.stripe.com:443` from the command " \
|
277
|
+
"line."
|
278
|
+
|
279
|
+
# Common error suffix sared by both connect and read timeout messages.
|
280
|
+
ERROR_MESSAGE_TIMEOUT_SUFFIX =
|
281
|
+
"Please check your internet connection and try again. " \
|
282
|
+
"If this problem persists, you should check Stripe's service " \
|
283
|
+
"status at https://status.stripe.com, or let us know at " \
|
284
|
+
"support@stripe.com."
|
285
|
+
|
286
|
+
ERROR_MESSAGE_TIMEOUT_CONNECT = (
|
287
|
+
"Timed out connecting to Stripe (%s). " +
|
288
|
+
ERROR_MESSAGE_TIMEOUT_SUFFIX
|
289
|
+
).freeze
|
290
|
+
|
291
|
+
ERROR_MESSAGE_TIMEOUT_READ = (
|
292
|
+
"Timed out communicating with Stripe (%s). " +
|
293
|
+
ERROR_MESSAGE_TIMEOUT_SUFFIX
|
294
|
+
).freeze
|
295
|
+
|
296
|
+
# Maps types of exceptions that we're likely to see during a network
|
297
|
+
# request to more user-friendly messages that we put in front of people.
|
298
|
+
# The original error message is also appended onto the final exception for
|
299
|
+
# full transparency.
|
300
|
+
NETWORK_ERROR_MESSAGES_MAP = {
|
301
|
+
EOFError => ERROR_MESSAGE_CONNECTION,
|
302
|
+
Errno::ECONNREFUSED => ERROR_MESSAGE_CONNECTION,
|
303
|
+
Errno::ECONNRESET => ERROR_MESSAGE_CONNECTION,
|
304
|
+
Errno::EHOSTUNREACH => ERROR_MESSAGE_CONNECTION,
|
305
|
+
Errno::ETIMEDOUT => ERROR_MESSAGE_TIMEOUT_CONNECT,
|
306
|
+
SocketError => ERROR_MESSAGE_CONNECTION,
|
307
|
+
|
308
|
+
Net::OpenTimeout => ERROR_MESSAGE_TIMEOUT_CONNECT,
|
309
|
+
Net::ReadTimeout => ERROR_MESSAGE_TIMEOUT_READ,
|
310
|
+
|
311
|
+
OpenSSL::SSL::SSLError => ERROR_MESSAGE_SSL,
|
312
|
+
}.freeze
|
313
|
+
private_constant :NETWORK_ERROR_MESSAGES_MAP
|
314
|
+
|
315
|
+
# A record representing any data that `StripeClient` puts into
|
316
|
+
# `Thread.current`. Making it a class likes this gives us a little extra
|
317
|
+
# type safety and lets us document what each field does.
|
202
318
|
#
|
203
|
-
#
|
204
|
-
#
|
319
|
+
# For internal use only. Does not provide a stable API and may be broken
|
320
|
+
# with future non-major changes.
|
321
|
+
class ThreadContext
|
322
|
+
# A `StripeClient` that's been flagged as currently active within a
|
323
|
+
# thread by `StripeClient#request`. A client stays active until the
|
324
|
+
# completion of the request block.
|
325
|
+
attr_accessor :active_client
|
326
|
+
|
327
|
+
# A default `StripeClient` object for the thread. Used in all cases where
|
328
|
+
# the user hasn't specified their own.
|
329
|
+
attr_accessor :default_client
|
330
|
+
|
331
|
+
# A default `ConnectionManager` for the thread. Normally shared between
|
332
|
+
# all `StripeClient` objects on a particular thread, and created so as to
|
333
|
+
# minimize the number of open connections that an application needs.
|
334
|
+
attr_accessor :default_connection_manager
|
335
|
+
|
336
|
+
# A temporary map of object IDs to responses from last executed API
|
337
|
+
# calls. Used to return a responses from calls to `StripeClient#request`.
|
338
|
+
#
|
339
|
+
# Stored in the thread data to make the use of a single `StripeClient`
|
340
|
+
# object safe across multiple threads. Stored as a map so that multiple
|
341
|
+
# `StripeClient` objects can run concurrently on the same thread.
|
342
|
+
#
|
343
|
+
# Responses are only left in as long as they're needed, which means
|
344
|
+
# they're removed as soon as a call leaves `StripeClient#request`, and
|
345
|
+
# because that's wrapped in an `ensure` block, they should never leave
|
346
|
+
# garbage in `Thread.current`.
|
347
|
+
attr_accessor :last_responses
|
348
|
+
end
|
349
|
+
|
350
|
+
# Access data stored for `StripeClient` within the thread's current
|
351
|
+
# context. Returns `ThreadContext`.
|
205
352
|
#
|
206
|
-
#
|
207
|
-
#
|
208
|
-
|
353
|
+
# For internal use only. Does not provide a stable API and may be broken
|
354
|
+
# with future non-major changes.
|
355
|
+
def self.current_thread_context
|
356
|
+
Thread.current[:stripe_client__internal_use_only] ||= ThreadContext.new
|
357
|
+
end
|
358
|
+
|
359
|
+
# Garbage collects connection managers that haven't been used in some time,
|
360
|
+
# with the idea being that we want to remove old connection managers that
|
361
|
+
# belong to dead threads and the like.
|
209
362
|
#
|
210
|
-
#
|
211
|
-
#
|
212
|
-
#
|
213
|
-
|
214
|
-
|
215
|
-
|
363
|
+
# Prefixed with `maybe_` because garbage collection will only run
|
364
|
+
# periodically so that we're not constantly engaged in busy work. If
|
365
|
+
# connection managers live a little passed their useful age it's not
|
366
|
+
# harmful, so it's not necessary to get them right away.
|
367
|
+
#
|
368
|
+
# For testability, returns `nil` if it didn't run and the number of
|
369
|
+
# connection managers that were garbage collected otherwise.
|
370
|
+
#
|
371
|
+
# IMPORTANT: This method is not thread-safe and expects to be called inside
|
372
|
+
# a lock on `@thread_contexts_with_connection_managers_mutex`.
|
373
|
+
#
|
374
|
+
# For internal use only. Does not provide a stable API and may be broken
|
375
|
+
# with future non-major changes.
|
376
|
+
def self.maybe_gc_connection_managers
|
377
|
+
next_gc_time = @last_connection_manager_gc + CONNECTION_MANAGER_GC_PERIOD
|
378
|
+
return nil if next_gc_time > Util.monotonic_time
|
379
|
+
|
380
|
+
last_used_threshold =
|
381
|
+
Util.monotonic_time - CONNECTION_MANAGER_GC_LAST_USED_EXPIRY
|
382
|
+
|
383
|
+
pruned_thread_contexts = []
|
384
|
+
@thread_contexts_with_connection_managers.each do |thread_context|
|
385
|
+
connection_manager = thread_context.default_connection_manager
|
386
|
+
next if connection_manager.last_used > last_used_threshold
|
387
|
+
|
388
|
+
connection_manager.clear
|
389
|
+
thread_context.default_connection_manager = nil
|
390
|
+
pruned_thread_contexts << thread_context
|
216
391
|
end
|
217
392
|
|
218
|
-
|
219
|
-
|
220
|
-
def encode(hash)
|
221
|
-
@cache.fetch(hash) do |k|
|
222
|
-
@cache[k] = Util.encode_parameters(hash)
|
223
|
-
end
|
224
|
-
end
|
393
|
+
@thread_contexts_with_connection_managers -= pruned_thread_contexts
|
394
|
+
@last_connection_manager_gc = Util.monotonic_time
|
225
395
|
|
226
|
-
|
227
|
-
def decode(_str)
|
228
|
-
raise NotImplementedError, "#{self.class.name} does not implement #decode"
|
229
|
-
end
|
396
|
+
pruned_thread_contexts.count
|
230
397
|
end
|
231
398
|
|
232
|
-
def api_url(url = "", api_base = nil)
|
399
|
+
private def api_url(url = "", api_base = nil)
|
233
400
|
(api_base || Stripe.api_base) + url
|
234
401
|
end
|
235
402
|
|
236
|
-
def check_api_key!(api_key)
|
403
|
+
private def check_api_key!(api_key)
|
237
404
|
unless api_key
|
238
405
|
raise AuthenticationError, "No API key provided. " \
|
239
406
|
'Set your API key using "Stripe.api_key = <API-KEY>". ' \
|
240
407
|
"You can generate API keys from the Stripe web interface. " \
|
241
|
-
"See https://stripe.com/api for details, or email
|
242
|
-
"if you have any questions."
|
408
|
+
"See https://stripe.com/api for details, or email " \
|
409
|
+
"support@stripe.com if you have any questions."
|
243
410
|
end
|
244
411
|
|
245
412
|
return unless api_key =~ /\s/
|
@@ -250,49 +417,98 @@ module Stripe
|
|
250
417
|
"email support@stripe.com if you have any questions.)"
|
251
418
|
end
|
252
419
|
|
253
|
-
|
420
|
+
# Encodes a set of body parameters using multipart if `Content-Type` is set
|
421
|
+
# for that, or standard form-encoding otherwise. Returns the encoded body
|
422
|
+
# and a version of the encoded body that's safe to be logged.
|
423
|
+
private def encode_body(body_params, headers)
|
424
|
+
body = nil
|
425
|
+
flattened_params = Util.flatten_params(body_params)
|
426
|
+
|
427
|
+
if headers["Content-Type"] == MultipartEncoder::MULTIPART_FORM_DATA
|
428
|
+
body, content_type = MultipartEncoder.encode(flattened_params)
|
429
|
+
|
430
|
+
# Set a new content type that also includes the multipart boundary.
|
431
|
+
# See `MultipartEncoder` for details.
|
432
|
+
headers["Content-Type"] = content_type
|
433
|
+
|
434
|
+
# `#to_s` any complex objects like files and the like to build output
|
435
|
+
# that's more condusive to logging.
|
436
|
+
flattened_params =
|
437
|
+
flattened_params.map { |k, v| [k, v.is_a?(String) ? v : v.to_s] }.to_h
|
438
|
+
else
|
439
|
+
body = Util.encode_parameters(body_params)
|
440
|
+
end
|
441
|
+
|
442
|
+
# We don't use `Util.encode_parameters` partly as an optimization (to not
|
443
|
+
# redo work we've already done), and partly because the encoded forms of
|
444
|
+
# certain characters introduce a lot of visual noise and it's nice to
|
445
|
+
# have a clearer format for logs.
|
446
|
+
body_log = flattened_params.map { |k, v| "#{k}=#{v}" }.join("&")
|
447
|
+
|
448
|
+
[body, body_log]
|
449
|
+
end
|
450
|
+
|
451
|
+
private def execute_request_with_rescues(method, api_base, context)
|
254
452
|
num_retries = 0
|
453
|
+
|
255
454
|
begin
|
256
|
-
request_start =
|
455
|
+
request_start = nil
|
456
|
+
user_data = nil
|
457
|
+
|
257
458
|
log_request(context, num_retries)
|
459
|
+
user_data = notify_request_begin(context)
|
460
|
+
|
461
|
+
request_start = Util.monotonic_time
|
258
462
|
resp = yield
|
259
|
-
|
260
|
-
|
463
|
+
request_duration = Util.monotonic_time - request_start
|
464
|
+
|
465
|
+
http_status = resp.code.to_i
|
466
|
+
context = context.dup_from_response_headers(resp)
|
467
|
+
|
468
|
+
handle_error_response(resp, context) if http_status >= 400
|
469
|
+
|
470
|
+
log_response(context, request_start, http_status, resp.body)
|
471
|
+
notify_request_end(context, request_duration, http_status,
|
472
|
+
num_retries, user_data)
|
261
473
|
|
262
474
|
if Stripe.enable_telemetry? && context.request_id
|
263
|
-
request_duration_ms = (
|
264
|
-
@last_request_metrics =
|
475
|
+
request_duration_ms = (request_duration * 1000).to_i
|
476
|
+
@last_request_metrics =
|
477
|
+
StripeRequestMetrics.new(context.request_id, request_duration_ms)
|
265
478
|
end
|
266
479
|
|
267
480
|
# We rescue all exceptions from a request so that we have an easy spot to
|
268
|
-
# implement our retry logic across the board. We'll re-raise if it's a
|
269
|
-
# of exception that we didn't expect to handle.
|
481
|
+
# implement our retry logic across the board. We'll re-raise if it's a
|
482
|
+
# type of exception that we didn't expect to handle.
|
270
483
|
rescue StandardError => e
|
271
484
|
# If we modify context we copy it into a new variable so as not to
|
272
485
|
# taint the original on a retry.
|
273
486
|
error_context = context
|
487
|
+
http_status = nil
|
488
|
+
request_duration = Util.monotonic_time - request_start if request_start
|
274
489
|
|
275
|
-
if e.
|
276
|
-
error_context = context.
|
490
|
+
if e.is_a?(Stripe::StripeError)
|
491
|
+
error_context = context.dup_from_response_headers(e.http_headers)
|
492
|
+
http_status = resp.code.to_i
|
277
493
|
log_response(error_context, request_start,
|
278
|
-
e.
|
494
|
+
e.http_status, e.http_body)
|
279
495
|
else
|
280
496
|
log_response_error(error_context, request_start, e)
|
281
497
|
end
|
498
|
+
notify_request_end(context, request_duration, http_status, num_retries,
|
499
|
+
user_data)
|
282
500
|
|
283
|
-
if self.class.should_retry?(e, num_retries)
|
501
|
+
if self.class.should_retry?(e, method: method, num_retries: num_retries)
|
284
502
|
num_retries += 1
|
285
503
|
sleep self.class.sleep_time(num_retries)
|
286
504
|
retry
|
287
505
|
end
|
288
506
|
|
289
507
|
case e
|
290
|
-
when
|
291
|
-
|
292
|
-
|
293
|
-
|
294
|
-
handle_network_error(e, error_context, num_retries, api_base)
|
295
|
-
end
|
508
|
+
when Stripe::StripeError
|
509
|
+
raise
|
510
|
+
when *NETWORK_ERROR_MESSAGES_MAP.keys
|
511
|
+
handle_network_error(e, error_context, num_retries, api_base)
|
296
512
|
|
297
513
|
# Only handle errors when we know we can do so, and re-raise otherwise.
|
298
514
|
# This should be pretty infrequent.
|
@@ -304,7 +520,42 @@ module Stripe
|
|
304
520
|
resp
|
305
521
|
end
|
306
522
|
|
307
|
-
def
|
523
|
+
private def notify_request_begin(context)
|
524
|
+
return unless Instrumentation.any_subscribers?(:request_begin)
|
525
|
+
|
526
|
+
event = Instrumentation::RequestBeginEvent.new(
|
527
|
+
method: context.method,
|
528
|
+
path: context.path,
|
529
|
+
user_data: {}
|
530
|
+
)
|
531
|
+
Stripe::Instrumentation.notify(:request_begin, event)
|
532
|
+
|
533
|
+
# This field may be set in the `request_begin` callback. If so, we'll
|
534
|
+
# forward it onto `request_end`.
|
535
|
+
event.user_data
|
536
|
+
end
|
537
|
+
|
538
|
+
private def notify_request_end(context, duration, http_status, num_retries,
|
539
|
+
user_data)
|
540
|
+
return if !Instrumentation.any_subscribers?(:request_end) &&
|
541
|
+
!Instrumentation.any_subscribers?(:request)
|
542
|
+
|
543
|
+
event = Instrumentation::RequestEndEvent.new(
|
544
|
+
duration: duration,
|
545
|
+
http_status: http_status,
|
546
|
+
method: context.method,
|
547
|
+
num_retries: num_retries,
|
548
|
+
path: context.path,
|
549
|
+
user_data: user_data || {}
|
550
|
+
)
|
551
|
+
Stripe::Instrumentation.notify(:request_end, event)
|
552
|
+
|
553
|
+
# The name before `request_begin` was also added. Provided for backwards
|
554
|
+
# compatibility.
|
555
|
+
Stripe::Instrumentation.notify(:request, event)
|
556
|
+
end
|
557
|
+
|
558
|
+
private def general_api_error(status, body)
|
308
559
|
APIError.new("Invalid response object from API: #{body.inspect} " \
|
309
560
|
"(HTTP response code was #{status})",
|
310
561
|
http_status: status, http_body: body)
|
@@ -314,21 +565,21 @@ module Stripe
|
|
314
565
|
# end of a User-Agent string where it'll be fairly prominent in places like
|
315
566
|
# the Dashboard. Note that this formatting has been implemented to match
|
316
567
|
# other libraries, and shouldn't be changed without universal consensus.
|
317
|
-
def format_app_info(info)
|
568
|
+
private def format_app_info(info)
|
318
569
|
str = info[:name]
|
319
570
|
str = "#{str}/#{info[:version]}" unless info[:version].nil?
|
320
571
|
str = "#{str} (#{info[:url]})" unless info[:url].nil?
|
321
572
|
str
|
322
573
|
end
|
323
574
|
|
324
|
-
def handle_error_response(http_resp, context)
|
575
|
+
private def handle_error_response(http_resp, context)
|
325
576
|
begin
|
326
|
-
resp = StripeResponse.
|
577
|
+
resp = StripeResponse.from_net_http(http_resp)
|
327
578
|
error_data = resp.data[:error]
|
328
579
|
|
329
580
|
raise StripeError, "Indeterminate error" unless error_data
|
330
581
|
rescue JSON::ParserError, StripeError
|
331
|
-
raise general_api_error(http_resp
|
582
|
+
raise general_api_error(http_resp.code.to_i, http_resp.body)
|
332
583
|
end
|
333
584
|
|
334
585
|
error = if error_data.is_a?(String)
|
@@ -341,7 +592,29 @@ module Stripe
|
|
341
592
|
raise(error)
|
342
593
|
end
|
343
594
|
|
344
|
-
|
595
|
+
# Works around an edge case where we end up with both query parameters from
|
596
|
+
# parameteers and query parameters that were appended onto the end of the
|
597
|
+
# given path.
|
598
|
+
#
|
599
|
+
# Decode any parameters that were added onto the end of a path and add them
|
600
|
+
# to a unified query parameter hash so that all parameters end up in one
|
601
|
+
# place and all of them are correctly included in the final request.
|
602
|
+
private def merge_query_params(query_params, path)
|
603
|
+
u = URI.parse(path)
|
604
|
+
|
605
|
+
# Return original results if there was nothing to be found.
|
606
|
+
return query_params, path if u.query.nil?
|
607
|
+
|
608
|
+
query_params ||= {}
|
609
|
+
query_params = Hash[URI.decode_www_form(u.query)].merge(query_params)
|
610
|
+
|
611
|
+
# Reset the path minus any query parameters that were specified.
|
612
|
+
path = u.path
|
613
|
+
|
614
|
+
[query_params, path]
|
615
|
+
end
|
616
|
+
|
617
|
+
private def specific_api_error(resp, error_data, context)
|
345
618
|
Util.log_error("Stripe API error",
|
346
619
|
status: resp.http_status,
|
347
620
|
error_code: error_data[:code],
|
@@ -365,35 +638,32 @@ module Stripe
|
|
365
638
|
when 400, 404
|
366
639
|
case error_data[:type]
|
367
640
|
when "idempotency_error"
|
368
|
-
IdempotencyError.new(error_data[:message], opts)
|
641
|
+
IdempotencyError.new(error_data[:message], **opts)
|
369
642
|
else
|
370
643
|
InvalidRequestError.new(
|
371
644
|
error_data[:message], error_data[:param],
|
372
|
-
opts
|
645
|
+
**opts
|
373
646
|
)
|
374
647
|
end
|
375
648
|
when 401
|
376
|
-
AuthenticationError.new(error_data[:message], opts)
|
649
|
+
AuthenticationError.new(error_data[:message], **opts)
|
377
650
|
when 402
|
378
|
-
# TODO: modify CardError constructor to make code a keyword argument
|
379
|
-
# so we don't have to delete it from opts
|
380
|
-
opts.delete(:code)
|
381
651
|
CardError.new(
|
382
|
-
error_data[:message], error_data[:param],
|
383
|
-
opts
|
652
|
+
error_data[:message], error_data[:param],
|
653
|
+
**opts
|
384
654
|
)
|
385
655
|
when 403
|
386
|
-
PermissionError.new(error_data[:message], opts)
|
656
|
+
PermissionError.new(error_data[:message], **opts)
|
387
657
|
when 429
|
388
|
-
RateLimitError.new(error_data[:message], opts)
|
658
|
+
RateLimitError.new(error_data[:message], **opts)
|
389
659
|
else
|
390
|
-
APIError.new(error_data[:message], opts)
|
660
|
+
APIError.new(error_data[:message], **opts)
|
391
661
|
end
|
392
662
|
end
|
393
663
|
|
394
664
|
# Attempts to look at a response's error code and return an OAuth error if
|
395
665
|
# one matches. Will return `nil` if the code isn't recognized.
|
396
|
-
def specific_oauth_error(resp, error_code, context)
|
666
|
+
private def specific_oauth_error(resp, error_code, context)
|
397
667
|
description = resp.data[:error_description] || error_code
|
398
668
|
|
399
669
|
Util.log_error("Stripe OAuth error",
|
@@ -403,62 +673,57 @@ module Stripe
|
|
403
673
|
idempotency_key: context.idempotency_key,
|
404
674
|
request_id: context.request_id)
|
405
675
|
|
406
|
-
args =
|
676
|
+
args = {
|
407
677
|
http_status: resp.http_status, http_body: resp.http_body,
|
408
678
|
json_body: resp.data, http_headers: resp.http_headers,
|
409
|
-
}
|
679
|
+
}
|
410
680
|
|
411
681
|
case error_code
|
412
|
-
when "invalid_client"
|
413
|
-
|
414
|
-
when "
|
415
|
-
|
416
|
-
when "
|
417
|
-
|
682
|
+
when "invalid_client"
|
683
|
+
OAuth::InvalidClientError.new(error_code, description, **args)
|
684
|
+
when "invalid_grant"
|
685
|
+
OAuth::InvalidGrantError.new(error_code, description, **args)
|
686
|
+
when "invalid_request"
|
687
|
+
OAuth::InvalidRequestError.new(error_code, description, **args)
|
688
|
+
when "invalid_scope"
|
689
|
+
OAuth::InvalidScopeError.new(error_code, description, **args)
|
690
|
+
when "unsupported_grant_type"
|
691
|
+
OAuth::UnsupportedGrantTypeError.new(error_code, description, **args)
|
692
|
+
when "unsupported_response_type"
|
693
|
+
OAuth::UnsupportedResponseTypeError.new(error_code, description, **args)
|
418
694
|
else
|
419
695
|
# We'd prefer that all errors are typed, but we create a generic
|
420
696
|
# OAuthError in case we run into a code that we don't recognize.
|
421
|
-
OAuth::OAuthError.new(
|
697
|
+
OAuth::OAuthError.new(error_code, description, **args)
|
422
698
|
end
|
423
699
|
end
|
424
700
|
|
425
|
-
def handle_network_error(
|
701
|
+
private def handle_network_error(error, context, num_retries,
|
702
|
+
api_base = nil)
|
426
703
|
Util.log_error("Stripe network error",
|
427
|
-
error_message:
|
704
|
+
error_message: error.message,
|
428
705
|
idempotency_key: context.idempotency_key,
|
429
706
|
request_id: context.request_id)
|
430
707
|
|
431
|
-
|
432
|
-
|
433
|
-
|
434
|
-
"You may be seeing this message because your DNS is not working. " \
|
435
|
-
"To check, try running 'host stripe.com' from the command line."
|
436
|
-
|
437
|
-
when Faraday::SSLError
|
438
|
-
message = "Could not establish a secure connection to Stripe, you may " \
|
439
|
-
"need to upgrade your OpenSSL version. To check, try running " \
|
440
|
-
"'openssl s_client -connect api.stripe.com:443' from the " \
|
441
|
-
"command line."
|
442
|
-
|
443
|
-
when Faraday::TimeoutError
|
444
|
-
api_base ||= Stripe.api_base
|
445
|
-
message = "Could not connect to Stripe (#{api_base}). " \
|
446
|
-
"Please check your internet connection and try again. " \
|
447
|
-
"If this problem persists, you should check Stripe's service status at " \
|
448
|
-
"https://twitter.com/stripestatus, or let us know at support@stripe.com."
|
449
|
-
|
450
|
-
else
|
451
|
-
message = "Unexpected error communicating with Stripe. " \
|
452
|
-
"If this problem persists, let us know at support@stripe.com."
|
708
|
+
errors, message = NETWORK_ERROR_MESSAGES_MAP.detect do |(e, _)|
|
709
|
+
error.is_a?(e)
|
710
|
+
end
|
453
711
|
|
712
|
+
if errors.nil?
|
713
|
+
message = "Unexpected error #{error.class.name} communicating " \
|
714
|
+
"with Stripe. Please let us know at support@stripe.com."
|
454
715
|
end
|
455
716
|
|
717
|
+
api_base ||= Stripe.api_base
|
718
|
+
message = message % api_base
|
719
|
+
|
456
720
|
message += " Request was retried #{num_retries} times." if num_retries > 0
|
457
721
|
|
458
|
-
raise APIConnectionError,
|
722
|
+
raise APIConnectionError,
|
723
|
+
message + "\n\n(Network error: #{error.message})"
|
459
724
|
end
|
460
725
|
|
461
|
-
def request_headers(api_key, method)
|
726
|
+
private def request_headers(api_key, method)
|
462
727
|
user_agent = "Stripe/v1 RubyBindings/#{Stripe::VERSION}"
|
463
728
|
unless Stripe.app_info.nil?
|
464
729
|
user_agent += " " + format_app_info(Stripe.app_info)
|
@@ -471,7 +736,9 @@ module Stripe
|
|
471
736
|
}
|
472
737
|
|
473
738
|
if Stripe.enable_telemetry? && !@last_request_metrics.nil?
|
474
|
-
headers["X-Stripe-Client-Telemetry"] = JSON.generate(
|
739
|
+
headers["X-Stripe-Client-Telemetry"] = JSON.generate(
|
740
|
+
last_request_metrics: @last_request_metrics.payload
|
741
|
+
)
|
475
742
|
end
|
476
743
|
|
477
744
|
# It is only safe to retry network failures on post and delete
|
@@ -498,7 +765,7 @@ module Stripe
|
|
498
765
|
headers
|
499
766
|
end
|
500
767
|
|
501
|
-
def log_request(context, num_retries)
|
768
|
+
private def log_request(context, num_retries)
|
502
769
|
Util.log_info("Request to Stripe API",
|
503
770
|
account: context.account,
|
504
771
|
api_version: context.api_version,
|
@@ -509,15 +776,14 @@ module Stripe
|
|
509
776
|
Util.log_debug("Request details",
|
510
777
|
body: context.body,
|
511
778
|
idempotency_key: context.idempotency_key,
|
512
|
-
|
779
|
+
query: context.query)
|
513
780
|
end
|
514
|
-
private :log_request
|
515
781
|
|
516
|
-
def log_response(context, request_start, status, body)
|
782
|
+
private def log_response(context, request_start, status, body)
|
517
783
|
Util.log_info("Response from Stripe API",
|
518
784
|
account: context.account,
|
519
785
|
api_version: context.api_version,
|
520
|
-
elapsed:
|
786
|
+
elapsed: Util.monotonic_time - request_start,
|
521
787
|
idempotency_key: context.idempotency_key,
|
522
788
|
method: context.method,
|
523
789
|
path: context.path,
|
@@ -533,19 +799,19 @@ module Stripe
|
|
533
799
|
Util.log_debug("Dashboard link for request",
|
534
800
|
idempotency_key: context.idempotency_key,
|
535
801
|
request_id: context.request_id,
|
536
|
-
url: Util.request_id_dashboard_url(context.request_id,
|
802
|
+
url: Util.request_id_dashboard_url(context.request_id,
|
803
|
+
context.api_key))
|
537
804
|
end
|
538
|
-
private :log_response
|
539
805
|
|
540
|
-
def log_response_error(context, request_start,
|
806
|
+
private def log_response_error(context, request_start, error)
|
807
|
+
elapsed = request_start ? Util.monotonic_time - request_start : nil
|
541
808
|
Util.log_error("Request error",
|
542
|
-
elapsed:
|
543
|
-
error_message:
|
809
|
+
elapsed: elapsed,
|
810
|
+
error_message: error.message,
|
544
811
|
idempotency_key: context.idempotency_key,
|
545
812
|
method: context.method,
|
546
813
|
path: context.path)
|
547
814
|
end
|
548
|
-
private :log_response_error
|
549
815
|
|
550
816
|
# RequestLogContext stores information about a request that's begin made so
|
551
817
|
# that we can log certain information. It's useful because it means that we
|
@@ -558,7 +824,7 @@ module Stripe
|
|
558
824
|
attr_accessor :idempotency_key
|
559
825
|
attr_accessor :method
|
560
826
|
attr_accessor :path
|
561
|
-
attr_accessor :
|
827
|
+
attr_accessor :query
|
562
828
|
attr_accessor :request_id
|
563
829
|
|
564
830
|
# The idea with this method is that we might want to update some of
|
@@ -567,18 +833,7 @@ module Stripe
|
|
567
833
|
# with for a request. For example, we should trust whatever came back in
|
568
834
|
# a `Stripe-Version` header beyond what configuration information that we
|
569
835
|
# might have had available.
|
570
|
-
def
|
571
|
-
return self if resp.nil?
|
572
|
-
|
573
|
-
# Faraday's API is a little unusual. Normally it'll produce a response
|
574
|
-
# object with a `headers` method, but on error what it puts into
|
575
|
-
# `e.response` is an untyped `Hash`.
|
576
|
-
headers = if resp.is_a?(Faraday::Response)
|
577
|
-
resp.headers
|
578
|
-
else
|
579
|
-
resp[:headers]
|
580
|
-
end
|
581
|
-
|
836
|
+
def dup_from_response_headers(headers)
|
582
837
|
context = dup
|
583
838
|
context.account = headers["Stripe-Account"]
|
584
839
|
context.api_version = headers["Stripe-Version"]
|
@@ -628,7 +883,8 @@ module Stripe
|
|
628
883
|
end
|
629
884
|
|
630
885
|
def user_agent
|
631
|
-
lang_version = "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL}
|
886
|
+
lang_version = "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL} " \
|
887
|
+
"(#{RUBY_RELEASE_DATE})"
|
632
888
|
|
633
889
|
{
|
634
890
|
application: Stripe.app_info,
|
@@ -644,7 +900,8 @@ module Stripe
|
|
644
900
|
end
|
645
901
|
end
|
646
902
|
|
647
|
-
# StripeRequestMetrics tracks metadata to be reported to stripe for metrics
|
903
|
+
# StripeRequestMetrics tracks metadata to be reported to stripe for metrics
|
904
|
+
# collection
|
648
905
|
class StripeRequestMetrics
|
649
906
|
# The Stripe request ID of the response.
|
650
907
|
attr_accessor :request_id
|