stripe 3.2.0 → 5.16.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +5 -5
- data/.editorconfig +10 -0
- data/.gitignore +3 -0
- data/.rubocop.yml +80 -0
- data/.rubocop_todo.yml +33 -0
- data/.travis.yml +9 -7
- data/.vscode/extensions.json +7 -0
- data/.vscode/settings.json +8 -0
- data/CHANGELOG.md +876 -0
- data/CODE_OF_CONDUCT.md +77 -0
- data/Gemfile +21 -21
- data/History.txt +1 -678
- data/README.md +195 -53
- data/Rakefile +18 -12
- data/VERSION +1 -1
- data/bin/stripe-console +5 -3
- data/lib/stripe/api_operations/create.rb +3 -1
- data/lib/stripe/api_operations/delete.rb +26 -2
- data/lib/stripe/api_operations/list.rb +3 -12
- data/lib/stripe/api_operations/nested_resource.rb +72 -0
- data/lib/stripe/api_operations/request.rb +33 -15
- data/lib/stripe/api_operations/save.rb +18 -9
- data/lib/stripe/api_resource.rb +60 -10
- data/lib/stripe/connection_manager.rb +159 -0
- data/lib/stripe/error_object.rb +94 -0
- data/lib/stripe/errors.rb +39 -19
- data/lib/stripe/instrumentation.rb +82 -0
- data/lib/stripe/list_object.rb +54 -22
- data/lib/stripe/multipart_encoder.rb +131 -0
- data/lib/stripe/oauth.rb +22 -14
- data/lib/stripe/object_types.rb +96 -0
- data/lib/stripe/{account.rb → resources/account.rb} +72 -34
- data/lib/stripe/resources/account_link.rb +9 -0
- data/lib/stripe/resources/alipay_account.rb +34 -0
- data/lib/stripe/{apple_pay_domain.rb → resources/apple_pay_domain.rb} +4 -2
- data/lib/stripe/resources/application_fee.rb +13 -0
- data/lib/stripe/resources/application_fee_refund.rb +30 -0
- data/lib/stripe/{balance.rb → resources/balance.rb} +3 -1
- data/lib/stripe/{balance_transaction.rb → resources/balance_transaction.rb} +3 -5
- data/lib/stripe/resources/bank_account.rb +42 -0
- data/lib/stripe/{bitcoin_receiver.rb → resources/bitcoin_receiver.rb} +6 -5
- data/lib/stripe/resources/bitcoin_transaction.rb +15 -0
- data/lib/stripe/resources/capability.rb +33 -0
- data/lib/stripe/resources/card.rb +37 -0
- data/lib/stripe/resources/charge.rb +22 -0
- data/lib/stripe/resources/checkout/session.rb +12 -0
- data/lib/stripe/{country_spec.rb → resources/country_spec.rb} +3 -5
- data/lib/stripe/{coupon.rb → resources/coupon.rb} +4 -2
- data/lib/stripe/resources/credit_note.rb +32 -0
- data/lib/stripe/resources/credit_note_line_item.rb +7 -0
- data/lib/stripe/resources/customer.rb +35 -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 +21 -0
- data/lib/stripe/resources/ephemeral_key.rb +19 -0
- data/lib/stripe/{event.rb → resources/event.rb} +3 -1
- data/lib/stripe/resources/exchange_rate.rb +9 -0
- data/lib/stripe/resources/file.rb +34 -0
- data/lib/stripe/resources/file_link.rb +11 -0
- data/lib/stripe/resources/invoice.rb +73 -0
- data/lib/stripe/{invoice_item.rb → resources/invoice_item.rb} +4 -2
- data/lib/stripe/{invoice_line_item.rb → resources/invoice_line_item.rb} +3 -1
- data/lib/stripe/resources/issuing/authorization.rb +33 -0
- data/lib/stripe/resources/issuing/card.rb +24 -0
- data/lib/stripe/resources/issuing/card_details.rb +9 -0
- data/lib/stripe/resources/issuing/cardholder.rb +13 -0
- data/lib/stripe/resources/issuing/dispute.rb +13 -0
- data/lib/stripe/resources/issuing/transaction.rb +12 -0
- data/lib/stripe/resources/login_link.rb +14 -0
- data/lib/stripe/resources/mandate.rb +7 -0
- data/lib/stripe/resources/order.rb +32 -0
- data/lib/stripe/{order_return.rb → resources/order_return.rb} +3 -5
- data/lib/stripe/resources/payment_intent.rb +42 -0
- data/lib/stripe/resources/payment_method.rb +32 -0
- data/lib/stripe/resources/payout.rb +22 -0
- data/lib/stripe/resources/person.rb +31 -0
- data/lib/stripe/{plan.rb → resources/plan.rb} +3 -1
- data/lib/stripe/{product.rb → resources/product.rb} +5 -3
- data/lib/stripe/resources/radar/early_fraud_warning.rb +11 -0
- data/lib/stripe/resources/radar/value_list.rb +14 -0
- data/lib/stripe/resources/radar/value_list_item.rb +13 -0
- data/lib/stripe/{recipient.rb → resources/recipient.rb} +5 -6
- data/lib/stripe/resources/recipient_transfer.rb +7 -0
- data/lib/stripe/{refund.rb → resources/refund.rb} +3 -1
- data/lib/stripe/resources/reporting/report_run.rb +12 -0
- data/lib/stripe/resources/reporting/report_type.rb +12 -0
- data/lib/stripe/resources/reversal.rb +29 -0
- data/lib/stripe/resources/review.rb +20 -0
- data/lib/stripe/resources/setup_intent.rb +32 -0
- data/lib/stripe/resources/sigma/scheduled_query_run.rb +15 -0
- data/lib/stripe/{sku.rb → resources/sku.rb} +5 -3
- data/lib/stripe/resources/source.rb +46 -0
- data/lib/stripe/resources/source_transaction.rb +7 -0
- data/lib/stripe/resources/subscription.rb +25 -0
- data/lib/stripe/resources/subscription_item.rb +25 -0
- data/lib/stripe/resources/subscription_schedule.rb +32 -0
- data/lib/stripe/resources/tax_id.rb +26 -0
- data/lib/stripe/resources/tax_rate.rb +11 -0
- data/lib/stripe/resources/terminal/connection_token.rb +11 -0
- data/lib/stripe/resources/terminal/location.rb +14 -0
- data/lib/stripe/resources/terminal/reader.rb +14 -0
- data/lib/stripe/{three_d_secure.rb → resources/three_d_secure.rb} +3 -1
- data/lib/stripe/{token.rb → resources/token.rb} +3 -1
- data/lib/stripe/resources/topup.rb +22 -0
- data/lib/stripe/resources/transfer.rb +26 -0
- data/lib/stripe/resources/usage_record.rb +7 -0
- data/lib/stripe/resources/usage_record_summary.rb +7 -0
- data/lib/stripe/resources/webhook_endpoint.rb +12 -0
- data/lib/stripe/resources.rb +79 -0
- data/lib/stripe/singleton_api_resource.rb +10 -4
- data/lib/stripe/stripe_client.rb +658 -337
- data/lib/stripe/stripe_object.rb +248 -126
- data/lib/stripe/stripe_response.rb +55 -21
- data/lib/stripe/util.rb +145 -187
- data/lib/stripe/version.rb +3 -1
- data/lib/stripe/webhook.rb +27 -16
- data/lib/stripe.rb +139 -90
- data/stripe.gemspec +26 -14
- data/test/openapi/README.md +9 -0
- data/test/stripe/account_link_test.rb +18 -0
- data/test/stripe/account_test.rb +311 -101
- data/test/stripe/alipay_account_test.rb +21 -1
- data/test/stripe/api_operations_test.rb +57 -8
- data/test/stripe/api_resource_test.rb +359 -271
- data/test/stripe/apple_pay_domain_test.rb +26 -11
- data/test/stripe/application_fee_refund_test.rb +10 -8
- data/test/stripe/application_fee_test.rb +49 -3
- data/test/stripe/balance_test.rb +4 -2
- data/test/stripe/balance_transaction_test.rb +20 -0
- data/test/stripe/bank_account_test.rb +11 -11
- data/test/stripe/capability_test.rb +45 -0
- data/test/stripe/charge_test.rb +25 -18
- data/test/stripe/checkout/session_test.rb +41 -0
- data/test/stripe/connection_manager_test.rb +163 -0
- data/test/stripe/country_spec_test.rb +6 -4
- data/test/stripe/coupon_test.rb +29 -10
- 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 +13 -17
- data/test/stripe/customer_test.rb +161 -49
- data/test/stripe/dispute_test.rb +19 -8
- data/test/stripe/ephemeral_key_test.rb +23 -14
- data/test/stripe/errors_test.rb +32 -9
- data/test/stripe/exchange_rate_test.rb +20 -0
- data/test/stripe/file_link_test.rb +41 -0
- data/test/stripe/file_test.rb +87 -0
- data/test/stripe/instrumentation_test.rb +74 -0
- data/test/stripe/invoice_item_test.rb +31 -18
- data/test/stripe/invoice_line_item_test.rb +3 -1
- data/test/stripe/invoice_test.rb +158 -39
- data/test/stripe/issuing/authorization_test.rb +72 -0
- data/test/stripe/issuing/card_test.rb +62 -0
- data/test/stripe/issuing/cardholder_test.rb +53 -0
- data/test/stripe/issuing/dispute_test.rb +45 -0
- data/test/stripe/issuing/transaction_test.rb +48 -0
- data/test/stripe/list_object_test.rb +120 -88
- data/test/stripe/login_link_test.rb +16 -14
- data/test/stripe/mandate_test.rb +14 -0
- data/test/stripe/multipart_encoder_test.rb +130 -0
- data/test/stripe/oauth_test.rb +69 -50
- data/test/stripe/order_return_test.rb +7 -5
- data/test/stripe/order_test.rb +39 -14
- data/test/stripe/payment_intent_test.rb +107 -0
- data/test/stripe/payment_method_test.rb +84 -0
- data/test/stripe/payout_test.rb +18 -9
- data/test/stripe/person_test.rb +46 -0
- data/test/stripe/plan_test.rb +67 -19
- data/test/stripe/product_test.rb +28 -14
- data/test/stripe/radar/early_fraud_warning_test.rb +22 -0
- data/test/stripe/radar/value_list_item_test.rb +48 -0
- data/test/stripe/radar/value_list_test.rb +61 -0
- data/test/stripe/recipient_test.rb +27 -13
- data/test/stripe/refund_test.rb +11 -9
- data/test/stripe/reporting/report_run_test.rb +33 -0
- data/test/stripe/reporting/report_type_test.rb +22 -0
- data/test/stripe/reversal_test.rb +12 -10
- data/test/stripe/review_test.rb +27 -0
- data/test/stripe/setup_intent_test.rb +84 -0
- data/test/stripe/sigma/scheduled_query_run_test.rb +22 -0
- data/test/stripe/sku_test.rb +24 -12
- data/test/stripe/source_test.rb +70 -19
- data/test/stripe/stripe_client_test.rb +867 -326
- data/test/stripe/stripe_object_test.rb +284 -182
- data/test/stripe/stripe_response_test.rb +73 -24
- data/test/stripe/subscription_item_test.rb +47 -15
- data/test/stripe/subscription_schedule_test.rb +82 -0
- data/test/stripe/subscription_test.rb +41 -19
- 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 +16 -0
- data/test/stripe/terminal/location_test.rb +68 -0
- data/test/stripe/terminal/reader_test.rb +62 -0
- data/test/stripe/three_d_secure_test.rb +4 -2
- data/test/stripe/topup_test.rb +62 -0
- data/test/stripe/transfer_test.rb +55 -8
- data/test/stripe/usage_record_summary_test.rb +29 -0
- data/test/stripe/util_test.rb +173 -84
- data/test/stripe/webhook_endpoint_test.rb +59 -0
- data/test/stripe/webhook_test.rb +21 -17
- data/test/stripe_mock.rb +78 -0
- data/test/stripe_test.rb +6 -15
- data/test/test_data.rb +28 -26
- data/test/test_helper.rb +48 -29
- metadata +183 -70
- data/lib/stripe/alipay_account.rb +0 -22
- data/lib/stripe/application_fee.rb +0 -22
- data/lib/stripe/application_fee_refund.rb +0 -20
- data/lib/stripe/bank_account.rb +0 -30
- data/lib/stripe/bitcoin_transaction.rb +0 -11
- data/lib/stripe/card.rb +0 -27
- data/lib/stripe/charge.rb +0 -82
- data/lib/stripe/customer.rb +0 -79
- data/lib/stripe/dispute.rb +0 -17
- data/lib/stripe/ephemeral_key.rb +0 -18
- data/lib/stripe/file_upload.rb +0 -33
- data/lib/stripe/invoice.rb +0 -29
- data/lib/stripe/login_link.rb +0 -9
- data/lib/stripe/order.rb +0 -29
- data/lib/stripe/payout.rb +0 -18
- data/lib/stripe/recipient_transfer.rb +0 -6
- data/lib/stripe/reversal.rb +0 -20
- data/lib/stripe/source.rb +0 -23
- data/lib/stripe/subscription.rb +0 -33
- data/lib/stripe/subscription_item.rb +0 -14
- data/lib/stripe/transfer.rb +0 -18
- data/test/api_stub_helpers.rb +0 -0
- data/test/stripe/bitcoin_receiver_test.rb +0 -67
- data/test/stripe/bitcoin_transaction_test.rb +0 -19
- data/test/stripe/file_upload_test.rb +0 -66
- data/test/stripe/recipient_card_test.rb +0 -44
data/lib/stripe/stripe_client.rb
CHANGED
@@ -1,89 +1,144 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "stripe/instrumentation"
|
4
|
+
|
1
5
|
module Stripe
|
2
6
|
# StripeClient executes requests against the Stripe API and allows a user to
|
3
7
|
# recover both a resource a call returns as well as a response object that
|
4
8
|
# contains information on the HTTP call.
|
5
9
|
class StripeClient
|
6
|
-
|
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
|
7
15
|
|
8
|
-
# Initializes a new StripeClient
|
9
|
-
#
|
10
|
-
|
11
|
-
|
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)
|
12
21
|
@system_profiler = SystemProfiler.new
|
22
|
+
@last_request_metrics = nil
|
13
23
|
end
|
14
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.
|
15
32
|
def self.active_client
|
16
|
-
|
33
|
+
current_thread_context.active_client || default_client
|
17
34
|
end
|
18
35
|
|
19
|
-
|
20
|
-
|
21
|
-
|
22
|
-
|
23
|
-
#
|
24
|
-
#
|
25
|
-
|
26
|
-
|
27
|
-
#
|
28
|
-
#
|
29
|
-
|
30
|
-
|
31
|
-
|
32
|
-
|
33
|
-
|
34
|
-
|
35
|
-
|
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
|
36
56
|
end
|
57
|
+
@thread_contexts_with_connection_managers.clear
|
58
|
+
end
|
59
|
+
end
|
37
60
|
|
38
|
-
|
39
|
-
|
40
|
-
|
41
|
-
|
42
|
-
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
|
43
65
|
|
44
|
-
|
45
|
-
|
46
|
-
|
47
|
-
|
48
|
-
|
49
|
-
|
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
|
50
74
|
end
|
51
75
|
|
52
|
-
|
76
|
+
connection_manager
|
53
77
|
end
|
54
78
|
end
|
55
79
|
|
56
|
-
# Checks if an error is a problem that we should retry on. This includes
|
57
|
-
# socket errors that may represent an intermittent problem and some
|
58
|
-
# HTTP statuses.
|
59
|
-
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:)
|
60
84
|
return false if num_retries >= Stripe.max_network_retries
|
61
85
|
|
62
|
-
|
63
|
-
|
64
|
-
|
65
|
-
|
66
|
-
|
67
|
-
|
68
|
-
|
69
|
-
|
70
|
-
|
71
|
-
|
72
|
-
|
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
|
73
127
|
end
|
74
|
-
|
75
|
-
false
|
76
128
|
end
|
77
129
|
|
78
130
|
def self.sleep_time(num_retries)
|
79
131
|
# Apply exponential backoff with initial_network_retry_delay on the
|
80
|
-
# number of num_retries so far as inputs. Do not allow the number to
|
81
|
-
# max_network_retry_delay.
|
82
|
-
sleep_seconds = [
|
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
|
83
138
|
|
84
|
-
# Apply some jitter by randomizing the value in the range of
|
85
|
-
# / 2) to (sleep_seconds).
|
86
|
-
sleep_seconds
|
139
|
+
# Apply some jitter by randomizing the value in the range of
|
140
|
+
# (sleep_seconds / 2) to (sleep_seconds).
|
141
|
+
sleep_seconds *= (0.5 * (1 + rand))
|
87
142
|
|
88
143
|
# But never sleep less than the base sleep seconds.
|
89
144
|
sleep_seconds = [Stripe.initial_network_retry_delay, sleep_seconds].max
|
@@ -91,142 +146,369 @@ module Stripe
|
|
91
146
|
sleep_seconds
|
92
147
|
end
|
93
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
|
+
|
94
158
|
# Executes the API call within the given block. Usage looks like:
|
95
159
|
#
|
96
160
|
# client = StripeClient.new
|
97
161
|
# charge, resp = client.request { Charge.create }
|
98
162
|
#
|
99
|
-
def request
|
100
|
-
|
101
|
-
|
102
|
-
|
163
|
+
def request
|
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
|
103
173
|
|
104
174
|
begin
|
105
|
-
res =
|
106
|
-
[res,
|
175
|
+
res = yield
|
176
|
+
[res, self.class.current_thread_context.last_responses[object_id]]
|
107
177
|
ensure
|
108
|
-
|
178
|
+
self.class.current_thread_context.active_client = old_stripe_client
|
179
|
+
self.class.current_thread_context.last_responses.delete(object_id)
|
109
180
|
end
|
110
181
|
end
|
111
182
|
|
112
183
|
def execute_request(method, path,
|
113
|
-
|
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)
|
114
189
|
|
115
190
|
api_base ||= Stripe.api_base
|
116
191
|
api_key ||= Stripe.api_key
|
192
|
+
params = Util.objects_to_ids(params)
|
117
193
|
|
118
194
|
check_api_key!(api_key)
|
119
195
|
|
120
|
-
|
121
|
-
|
122
|
-
|
123
|
-
case method.to_s.downcase.to_sym
|
196
|
+
body_params = nil
|
197
|
+
query_params = nil
|
198
|
+
case method
|
124
199
|
when :get, :head, :delete
|
125
|
-
|
126
|
-
url += "#{URI.parse(url).query ? '&' : '?'}#{Util.encode_parameters(params)}" if params && params.any?
|
127
|
-
payload = nil
|
200
|
+
query_params = params
|
128
201
|
else
|
129
|
-
|
130
|
-
payload = params
|
131
|
-
else
|
132
|
-
payload = Util.encode_parameters(params)
|
133
|
-
end
|
202
|
+
body_params = params
|
134
203
|
end
|
135
204
|
|
136
|
-
|
137
|
-
|
205
|
+
query_params, path = merge_query_params(query_params, path)
|
206
|
+
|
207
|
+
headers = request_headers(api_key, method)
|
208
|
+
.update(Util.normalize_headers(headers))
|
209
|
+
url = api_url(path, api_base)
|
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]
|
138
220
|
|
139
221
|
# stores information on the request we're about to make so that we don't
|
140
222
|
# have to pass as many parameters around for logging.
|
141
|
-
context = RequestLogContext.new
|
142
|
-
|
143
|
-
|
144
|
-
|
145
|
-
|
146
|
-
|
147
|
-
|
148
|
-
|
149
|
-
|
150
|
-
|
151
|
-
http_resp = execute_request_with_rescues(api_base, context) do
|
152
|
-
|
153
|
-
|
154
|
-
|
155
|
-
|
223
|
+
context = RequestLogContext.new
|
224
|
+
context.account = headers["Stripe-Account"]
|
225
|
+
context.api_key = api_key
|
226
|
+
context.api_version = headers["Stripe-Version"]
|
227
|
+
context.body = body_log
|
228
|
+
context.idempotency_key = headers["Idempotency-Key"]
|
229
|
+
context.method = method
|
230
|
+
context.path = path
|
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)
|
156
238
|
end
|
157
239
|
|
158
240
|
begin
|
159
|
-
resp = StripeResponse.
|
241
|
+
resp = StripeResponse.from_net_http(http_resp)
|
160
242
|
rescue JSON::ParserError
|
161
|
-
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
|
162
251
|
end
|
163
252
|
|
164
|
-
# Allows StripeClient#request to return a response object to a caller.
|
165
|
-
@last_response = resp
|
166
253
|
[resp, api_key]
|
167
254
|
end
|
168
255
|
|
169
|
-
|
256
|
+
#
|
257
|
+
# private
|
258
|
+
#
|
259
|
+
|
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.
|
318
|
+
#
|
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`.
|
352
|
+
#
|
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
|
170
358
|
|
171
|
-
|
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.
|
362
|
+
#
|
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
|
391
|
+
end
|
392
|
+
|
393
|
+
@thread_contexts_with_connection_managers -= pruned_thread_contexts
|
394
|
+
@last_connection_manager_gc = Util.monotonic_time
|
395
|
+
|
396
|
+
pruned_thread_contexts.count
|
397
|
+
end
|
398
|
+
|
399
|
+
private def api_url(url = "", api_base = nil)
|
172
400
|
(api_base || Stripe.api_base) + url
|
173
401
|
end
|
174
402
|
|
175
|
-
def check_api_key!(api_key)
|
403
|
+
private def check_api_key!(api_key)
|
176
404
|
unless api_key
|
177
|
-
raise AuthenticationError
|
405
|
+
raise AuthenticationError, "No API key provided. " \
|
178
406
|
'Set your API key using "Stripe.api_key = <API-KEY>". ' \
|
179
|
-
|
180
|
-
|
181
|
-
|
407
|
+
"You can generate API keys from the Stripe web interface. " \
|
408
|
+
"See https://stripe.com/api for details, or email " \
|
409
|
+
"support@stripe.com if you have any questions."
|
182
410
|
end
|
183
411
|
|
184
|
-
|
185
|
-
|
186
|
-
|
187
|
-
|
188
|
-
|
412
|
+
return unless api_key =~ /\s/
|
413
|
+
|
414
|
+
raise AuthenticationError, "Your API key is invalid, as it contains " \
|
415
|
+
"whitespace. (HINT: You can double-check your API key from the " \
|
416
|
+
"Stripe web interface. See https://stripe.com/api for details, or " \
|
417
|
+
"email support@stripe.com if you have any questions.)"
|
418
|
+
end
|
419
|
+
|
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)
|
189
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]
|
190
449
|
end
|
191
450
|
|
192
|
-
def execute_request_with_rescues(api_base, context
|
451
|
+
private def execute_request_with_rescues(method, api_base, context)
|
193
452
|
num_retries = 0
|
453
|
+
|
194
454
|
begin
|
195
|
-
request_start =
|
455
|
+
request_start = nil
|
456
|
+
user_data = nil
|
457
|
+
|
196
458
|
log_request(context, num_retries)
|
197
|
-
|
198
|
-
|
199
|
-
|
459
|
+
user_data = notify_request_begin(context)
|
460
|
+
|
461
|
+
request_start = Util.monotonic_time
|
462
|
+
resp = yield
|
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)
|
473
|
+
|
474
|
+
if Stripe.enable_telemetry? && context.request_id
|
475
|
+
request_duration_ms = (request_duration * 1000).to_i
|
476
|
+
@last_request_metrics =
|
477
|
+
StripeRequestMetrics.new(context.request_id, request_duration_ms)
|
478
|
+
end
|
200
479
|
|
201
480
|
# We rescue all exceptions from a request so that we have an easy spot to
|
202
|
-
# implement our retry logic across the board. We'll re-raise if it's a
|
203
|
-
# of exception that we didn't expect to handle.
|
204
|
-
rescue => e
|
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.
|
483
|
+
rescue StandardError => e
|
205
484
|
# If we modify context we copy it into a new variable so as not to
|
206
485
|
# taint the original on a retry.
|
207
486
|
error_context = context
|
487
|
+
http_status = nil
|
488
|
+
request_duration = Util.monotonic_time - request_start if request_start
|
208
489
|
|
209
|
-
if e.
|
210
|
-
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
|
211
493
|
log_response(error_context, request_start,
|
212
|
-
|
494
|
+
e.http_status, e.http_body)
|
213
495
|
else
|
214
496
|
log_response_error(error_context, request_start, e)
|
215
497
|
end
|
498
|
+
notify_request_end(context, request_duration, http_status, num_retries,
|
499
|
+
user_data)
|
216
500
|
|
217
|
-
if self.class.should_retry?(e, num_retries)
|
501
|
+
if self.class.should_retry?(e, method: method, num_retries: num_retries)
|
218
502
|
num_retries += 1
|
219
503
|
sleep self.class.sleep_time(num_retries)
|
220
504
|
retry
|
221
505
|
end
|
222
506
|
|
223
507
|
case e
|
224
|
-
when
|
225
|
-
|
226
|
-
|
227
|
-
|
228
|
-
handle_network_error(e, error_context, num_retries, api_base)
|
229
|
-
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)
|
230
512
|
|
231
513
|
# Only handle errors when we know we can do so, and re-raise otherwise.
|
232
514
|
# This should be pretty infrequent.
|
@@ -238,199 +520,244 @@ module Stripe
|
|
238
520
|
resp
|
239
521
|
end
|
240
522
|
|
241
|
-
def
|
242
|
-
|
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)
|
559
|
+
APIError.new("Invalid response object from API: #{body.inspect} " \
|
243
560
|
"(HTTP response code was #{status})",
|
244
561
|
http_status: status, http_body: body)
|
245
562
|
end
|
246
563
|
|
247
564
|
# Formats a plugin "app info" hash into a string that we can tack onto the
|
248
|
-
# end of a User-Agent string where it'll be fairly
|
565
|
+
# end of a User-Agent string where it'll be fairly prominent in places like
|
249
566
|
# the Dashboard. Note that this formatting has been implemented to match
|
250
567
|
# other libraries, and shouldn't be changed without universal consensus.
|
251
|
-
def format_app_info(info)
|
568
|
+
private def format_app_info(info)
|
252
569
|
str = info[:name]
|
253
570
|
str = "#{str}/#{info[:version]}" unless info[:version].nil?
|
254
571
|
str = "#{str} (#{info[:url]})" unless info[:url].nil?
|
255
572
|
str
|
256
573
|
end
|
257
574
|
|
258
|
-
def handle_error_response(http_resp, context)
|
575
|
+
private def handle_error_response(http_resp, context)
|
259
576
|
begin
|
260
|
-
resp = StripeResponse.
|
577
|
+
resp = StripeResponse.from_net_http(http_resp)
|
261
578
|
error_data = resp.data[:error]
|
262
579
|
|
263
|
-
unless error_data
|
264
|
-
raise StripeError.new("Indeterminate error")
|
265
|
-
end
|
266
|
-
|
580
|
+
raise StripeError, "Indeterminate error" unless error_data
|
267
581
|
rescue JSON::ParserError, StripeError
|
268
|
-
raise general_api_error(http_resp
|
582
|
+
raise general_api_error(http_resp.code.to_i, http_resp.body)
|
269
583
|
end
|
270
584
|
|
271
|
-
if error_data.is_a?(String)
|
272
|
-
|
273
|
-
|
274
|
-
|
275
|
-
|
585
|
+
error = if error_data.is_a?(String)
|
586
|
+
specific_oauth_error(resp, error_data, context)
|
587
|
+
else
|
588
|
+
specific_api_error(resp, error_data, context)
|
589
|
+
end
|
276
590
|
|
277
591
|
error.response = resp
|
278
592
|
raise(error)
|
279
593
|
end
|
280
594
|
|
281
|
-
|
282
|
-
|
283
|
-
|
284
|
-
|
285
|
-
|
286
|
-
|
287
|
-
|
288
|
-
|
289
|
-
|
290
|
-
|
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)
|
618
|
+
Util.log_error("Stripe API error",
|
619
|
+
status: resp.http_status,
|
620
|
+
error_code: error_data[:code],
|
621
|
+
error_message: error_data[:message],
|
622
|
+
error_param: error_data[:param],
|
623
|
+
error_type: error_data[:type],
|
624
|
+
idempotency_key: context.idempotency_key,
|
625
|
+
request_id: context.request_id)
|
626
|
+
|
627
|
+
# The standard set of arguments that can be used to initialize most of
|
628
|
+
# the exceptions.
|
629
|
+
opts = {
|
630
|
+
http_body: resp.http_body,
|
631
|
+
http_headers: resp.http_headers,
|
632
|
+
http_status: resp.http_status,
|
633
|
+
json_body: resp.data,
|
634
|
+
code: error_data[:code],
|
635
|
+
}
|
291
636
|
|
292
637
|
case resp.http_status
|
293
638
|
when 400, 404
|
294
|
-
|
295
|
-
|
296
|
-
|
297
|
-
|
298
|
-
|
639
|
+
case error_data[:type]
|
640
|
+
when "idempotency_error"
|
641
|
+
IdempotencyError.new(error_data[:message], **opts)
|
642
|
+
else
|
643
|
+
InvalidRequestError.new(
|
644
|
+
error_data[:message], error_data[:param],
|
645
|
+
**opts
|
646
|
+
)
|
647
|
+
end
|
299
648
|
when 401
|
300
|
-
|
301
|
-
error_data[:message],
|
302
|
-
http_status: resp.http_status, http_body: resp.http_body,
|
303
|
-
json_body: resp.data, http_headers: resp.http_headers
|
304
|
-
)
|
649
|
+
AuthenticationError.new(error_data[:message], **opts)
|
305
650
|
when 402
|
306
|
-
|
307
|
-
error_data[:message], error_data[:param],
|
308
|
-
|
309
|
-
json_body: resp.data, http_headers: resp.http_headers
|
651
|
+
CardError.new(
|
652
|
+
error_data[:message], error_data[:param],
|
653
|
+
**opts
|
310
654
|
)
|
311
655
|
when 403
|
312
|
-
|
313
|
-
error_data[:message],
|
314
|
-
http_status: resp.http_status, http_body: resp.http_body,
|
315
|
-
json_body: resp.data, http_headers: resp.http_headers
|
316
|
-
)
|
656
|
+
PermissionError.new(error_data[:message], **opts)
|
317
657
|
when 429
|
318
|
-
|
319
|
-
error_data[:message],
|
320
|
-
http_status: resp.http_status, http_body: resp.http_body,
|
321
|
-
json_body: resp.data, http_headers: resp.http_headers
|
322
|
-
)
|
658
|
+
RateLimitError.new(error_data[:message], **opts)
|
323
659
|
else
|
324
|
-
|
325
|
-
error_data[:message],
|
326
|
-
http_status: resp.http_status, http_body: resp.http_body,
|
327
|
-
json_body: resp.data, http_headers: resp.http_headers
|
328
|
-
)
|
660
|
+
APIError.new(error_data[:message], **opts)
|
329
661
|
end
|
330
|
-
|
331
|
-
error
|
332
662
|
end
|
333
663
|
|
334
664
|
# Attempts to look at a response's error code and return an OAuth error if
|
335
665
|
# one matches. Will return `nil` if the code isn't recognized.
|
336
|
-
def specific_oauth_error(resp, error_code, context)
|
666
|
+
private def specific_oauth_error(resp, error_code, context)
|
337
667
|
description = resp.data[:error_description] || error_code
|
338
668
|
|
339
|
-
Util.
|
340
|
-
|
341
|
-
|
342
|
-
|
343
|
-
|
344
|
-
|
345
|
-
)
|
669
|
+
Util.log_error("Stripe OAuth error",
|
670
|
+
status: resp.http_status,
|
671
|
+
error_code: error_code,
|
672
|
+
error_description: description,
|
673
|
+
idempotency_key: context.idempotency_key,
|
674
|
+
request_id: context.request_id)
|
346
675
|
|
347
|
-
args =
|
676
|
+
args = {
|
348
677
|
http_status: resp.http_status, http_body: resp.http_body,
|
349
|
-
json_body: resp.data, http_headers: resp.http_headers
|
350
|
-
}
|
678
|
+
json_body: resp.data, http_headers: resp.http_headers,
|
679
|
+
}
|
351
680
|
|
352
681
|
case error_code
|
353
|
-
when
|
354
|
-
|
355
|
-
when
|
356
|
-
|
357
|
-
when
|
358
|
-
|
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)
|
359
694
|
else
|
360
695
|
# We'd prefer that all errors are typed, but we create a generic
|
361
696
|
# OAuthError in case we run into a code that we don't recognize.
|
362
|
-
OAuth::OAuthError.new(
|
697
|
+
OAuth::OAuthError.new(error_code, description, **args)
|
363
698
|
end
|
364
699
|
end
|
365
700
|
|
366
|
-
def handle_network_error(
|
367
|
-
|
368
|
-
|
369
|
-
|
370
|
-
|
371
|
-
|
372
|
-
|
373
|
-
case e
|
374
|
-
when Faraday::ConnectionFailed
|
375
|
-
message = "Unexpected error communicating when trying to connect to Stripe. " \
|
376
|
-
"You may be seeing this message because your DNS is not working. " \
|
377
|
-
"To check, try running 'host stripe.com' from the command line."
|
378
|
-
|
379
|
-
when Faraday::SSLError
|
380
|
-
message = "Could not establish a secure connection to Stripe, you may " \
|
381
|
-
"need to upgrade your OpenSSL version. To check, try running " \
|
382
|
-
"'openssl s_client -connect api.stripe.com:443' from the " \
|
383
|
-
"command line."
|
384
|
-
|
385
|
-
when Faraday::TimeoutError
|
386
|
-
api_base = Stripe.api_base unless api_base
|
387
|
-
message = "Could not connect to Stripe (#{api_base}). " \
|
388
|
-
"Please check your internet connection and try again. " \
|
389
|
-
"If this problem persists, you should check Stripe's service status at " \
|
390
|
-
"https://twitter.com/stripestatus, or let us know at support@stripe.com."
|
391
|
-
|
392
|
-
else
|
393
|
-
message = "Unexpected error communicating with Stripe. " \
|
394
|
-
"If this problem persists, let us know at support@stripe.com."
|
701
|
+
private def handle_network_error(error, context, num_retries,
|
702
|
+
api_base = nil)
|
703
|
+
Util.log_error("Stripe network error",
|
704
|
+
error_message: error.message,
|
705
|
+
idempotency_key: context.idempotency_key,
|
706
|
+
request_id: context.request_id)
|
395
707
|
|
708
|
+
errors, message = NETWORK_ERROR_MESSAGES_MAP.detect do |(e, _)|
|
709
|
+
error.is_a?(e)
|
396
710
|
end
|
397
711
|
|
398
|
-
if
|
399
|
-
message
|
712
|
+
if errors.nil?
|
713
|
+
message = "Unexpected error #{error.class.name} communicating " \
|
714
|
+
"with Stripe. Please let us know at support@stripe.com."
|
400
715
|
end
|
401
716
|
|
402
|
-
|
717
|
+
api_base ||= Stripe.api_base
|
718
|
+
message = message % api_base
|
719
|
+
|
720
|
+
message += " Request was retried #{num_retries} times." if num_retries > 0
|
721
|
+
|
722
|
+
raise APIConnectionError,
|
723
|
+
message + "\n\n(Network error: #{error.message})"
|
403
724
|
end
|
404
725
|
|
405
|
-
def request_headers(api_key, method)
|
726
|
+
private def request_headers(api_key, method)
|
406
727
|
user_agent = "Stripe/v1 RubyBindings/#{Stripe::VERSION}"
|
407
728
|
unless Stripe.app_info.nil?
|
408
729
|
user_agent += " " + format_app_info(Stripe.app_info)
|
409
730
|
end
|
410
731
|
|
411
732
|
headers = {
|
412
|
-
|
413
|
-
|
414
|
-
|
733
|
+
"User-Agent" => user_agent,
|
734
|
+
"Authorization" => "Bearer #{api_key}",
|
735
|
+
"Content-Type" => "application/x-www-form-urlencoded",
|
415
736
|
}
|
416
737
|
|
738
|
+
if Stripe.enable_telemetry? && !@last_request_metrics.nil?
|
739
|
+
headers["X-Stripe-Client-Telemetry"] = JSON.generate(
|
740
|
+
last_request_metrics: @last_request_metrics.payload
|
741
|
+
)
|
742
|
+
end
|
743
|
+
|
417
744
|
# It is only safe to retry network failures on post and delete
|
418
745
|
# requests if we add an Idempotency-Key header
|
419
|
-
if [
|
420
|
-
headers[
|
746
|
+
if %i[post delete].include?(method) && Stripe.max_network_retries > 0
|
747
|
+
headers["Idempotency-Key"] ||= SecureRandom.uuid
|
421
748
|
end
|
422
749
|
|
423
|
-
headers[
|
424
|
-
headers[
|
750
|
+
headers["Stripe-Version"] = Stripe.api_version if Stripe.api_version
|
751
|
+
headers["Stripe-Account"] = Stripe.stripe_account if Stripe.stripe_account
|
425
752
|
|
426
753
|
user_agent = @system_profiler.user_agent
|
427
754
|
begin
|
428
755
|
headers.update(
|
429
|
-
|
756
|
+
"X-Stripe-Client-User-Agent" => JSON.generate(user_agent)
|
430
757
|
)
|
431
|
-
rescue => e
|
758
|
+
rescue StandardError => e
|
432
759
|
headers.update(
|
433
|
-
|
760
|
+
"X-Stripe-Client-Raw-User-Agent" => user_agent.inspect,
|
434
761
|
:error => "#{e} (#{e.class})"
|
435
762
|
)
|
436
763
|
end
|
@@ -438,102 +765,76 @@ module Stripe
|
|
438
765
|
headers
|
439
766
|
end
|
440
767
|
|
441
|
-
def log_request(context, num_retries)
|
768
|
+
private def log_request(context, num_retries)
|
442
769
|
Util.log_info("Request to Stripe API",
|
443
|
-
|
444
|
-
|
445
|
-
|
446
|
-
|
447
|
-
|
448
|
-
|
449
|
-
)
|
770
|
+
account: context.account,
|
771
|
+
api_version: context.api_version,
|
772
|
+
idempotency_key: context.idempotency_key,
|
773
|
+
method: context.method,
|
774
|
+
num_retries: num_retries,
|
775
|
+
path: context.path)
|
450
776
|
Util.log_debug("Request details",
|
451
|
-
|
452
|
-
|
453
|
-
|
777
|
+
body: context.body,
|
778
|
+
idempotency_key: context.idempotency_key,
|
779
|
+
query: context.query)
|
454
780
|
end
|
455
|
-
private :log_request
|
456
781
|
|
457
|
-
def log_response(context, request_start, status, body)
|
782
|
+
private def log_response(context, request_start, status, body)
|
458
783
|
Util.log_info("Response from Stripe API",
|
459
|
-
|
460
|
-
|
461
|
-
|
462
|
-
|
463
|
-
|
464
|
-
|
465
|
-
|
466
|
-
|
467
|
-
)
|
784
|
+
account: context.account,
|
785
|
+
api_version: context.api_version,
|
786
|
+
elapsed: Util.monotonic_time - request_start,
|
787
|
+
idempotency_key: context.idempotency_key,
|
788
|
+
method: context.method,
|
789
|
+
path: context.path,
|
790
|
+
request_id: context.request_id,
|
791
|
+
status: status)
|
468
792
|
Util.log_debug("Response details",
|
469
|
-
|
470
|
-
|
471
|
-
|
472
|
-
|
473
|
-
|
474
|
-
|
475
|
-
|
476
|
-
|
477
|
-
|
478
|
-
|
479
|
-
|
793
|
+
body: body,
|
794
|
+
idempotency_key: context.idempotency_key,
|
795
|
+
request_id: context.request_id)
|
796
|
+
|
797
|
+
return unless context.request_id
|
798
|
+
|
799
|
+
Util.log_debug("Dashboard link for request",
|
800
|
+
idempotency_key: context.idempotency_key,
|
801
|
+
request_id: context.request_id,
|
802
|
+
url: Util.request_id_dashboard_url(context.request_id,
|
803
|
+
context.api_key))
|
480
804
|
end
|
481
|
-
private :log_response
|
482
805
|
|
483
|
-
def log_response_error(context, request_start,
|
484
|
-
Util.
|
485
|
-
|
486
|
-
|
487
|
-
|
488
|
-
|
489
|
-
|
490
|
-
|
806
|
+
private def log_response_error(context, request_start, error)
|
807
|
+
elapsed = request_start ? Util.monotonic_time - request_start : nil
|
808
|
+
Util.log_error("Request error",
|
809
|
+
elapsed: elapsed,
|
810
|
+
error_message: error.message,
|
811
|
+
idempotency_key: context.idempotency_key,
|
812
|
+
method: context.method,
|
813
|
+
path: context.path)
|
491
814
|
end
|
492
|
-
private :log_response_error
|
493
815
|
|
494
816
|
# RequestLogContext stores information about a request that's begin made so
|
495
817
|
# that we can log certain information. It's useful because it means that we
|
496
818
|
# don't have to pass around as many parameters.
|
497
819
|
class RequestLogContext
|
820
|
+
attr_accessor :body
|
498
821
|
attr_accessor :account
|
499
822
|
attr_accessor :api_key
|
500
823
|
attr_accessor :api_version
|
501
824
|
attr_accessor :idempotency_key
|
502
825
|
attr_accessor :method
|
503
826
|
attr_accessor :path
|
504
|
-
attr_accessor :
|
827
|
+
attr_accessor :query
|
505
828
|
attr_accessor :request_id
|
506
829
|
|
507
|
-
def initialize(account: nil, api_key: nil, api_version: nil,
|
508
|
-
idempotency_key: nil, method: nil, path: nil, payload: nil)
|
509
|
-
self.account = account
|
510
|
-
self.api_key = api_key
|
511
|
-
self.api_version = api_version
|
512
|
-
self.idempotency_key = idempotency_key
|
513
|
-
self.method = method
|
514
|
-
self.path = path
|
515
|
-
self.payload = payload
|
516
|
-
end
|
517
|
-
|
518
830
|
# The idea with this method is that we might want to update some of
|
519
831
|
# context information because a response that we've received from the API
|
520
832
|
# contains information that's more authoritative than what we started
|
521
833
|
# with for a request. For example, we should trust whatever came back in
|
522
834
|
# a `Stripe-Version` header beyond what configuration information that we
|
523
835
|
# might have had available.
|
524
|
-
def
|
525
|
-
|
526
|
-
|
527
|
-
# Faraday's API is a little unusual. Normally it'll produce a response
|
528
|
-
# object with a `headers` method, but on error what it puts into
|
529
|
-
# `e.response` is an untyped `Hash`.
|
530
|
-
headers = if resp.is_a?(Faraday::Response)
|
531
|
-
resp.headers
|
532
|
-
else
|
533
|
-
resp[:headers]
|
534
|
-
end
|
535
|
-
|
536
|
-
context = self.dup
|
836
|
+
def dup_from_response_headers(headers)
|
837
|
+
context = dup
|
537
838
|
context.account = headers["Stripe-Account"]
|
538
839
|
context.api_version = headers["Stripe-Version"]
|
539
840
|
context.idempotency_key = headers["Idempotency-Key"]
|
@@ -546,31 +847,31 @@ module Stripe
|
|
546
847
|
# in so that we can generate a rich user agent header to help debug
|
547
848
|
# integrations.
|
548
849
|
class SystemProfiler
|
549
|
-
def self.
|
550
|
-
if File.exist?(
|
551
|
-
File.read(
|
850
|
+
def self.uname
|
851
|
+
if ::File.exist?("/proc/version")
|
852
|
+
::File.read("/proc/version").strip
|
552
853
|
else
|
553
|
-
case RbConfig::CONFIG[
|
854
|
+
case RbConfig::CONFIG["host_os"]
|
554
855
|
when /linux|darwin|bsd|sunos|solaris|cygwin/i
|
555
|
-
|
856
|
+
uname_from_system
|
556
857
|
when /mswin|mingw/i
|
557
|
-
|
858
|
+
uname_from_system_ver
|
558
859
|
else
|
559
860
|
"unknown platform"
|
560
861
|
end
|
561
862
|
end
|
562
863
|
end
|
563
864
|
|
564
|
-
def self.
|
565
|
-
(`uname -a 2>/dev/null` ||
|
865
|
+
def self.uname_from_system
|
866
|
+
(`uname -a 2>/dev/null` || "").strip
|
566
867
|
rescue Errno::ENOENT
|
567
868
|
"uname executable not found"
|
568
869
|
rescue Errno::ENOMEM # couldn't create subprocess
|
569
870
|
"uname lookup failed"
|
570
871
|
end
|
571
872
|
|
572
|
-
def self.
|
573
|
-
(`ver` ||
|
873
|
+
def self.uname_from_system_ver
|
874
|
+
(`ver` || "").strip
|
574
875
|
rescue Errno::ENOENT
|
575
876
|
"ver executable not found"
|
576
877
|
rescue Errno::ENOMEM # couldn't create subprocess
|
@@ -578,23 +879,43 @@ module Stripe
|
|
578
879
|
end
|
579
880
|
|
580
881
|
def initialize
|
581
|
-
@uname = self.class.
|
882
|
+
@uname = self.class.uname
|
582
883
|
end
|
583
884
|
|
584
885
|
def user_agent
|
585
|
-
lang_version = "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL}
|
886
|
+
lang_version = "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL} " \
|
887
|
+
"(#{RUBY_RELEASE_DATE})"
|
586
888
|
|
587
889
|
{
|
588
|
-
:
|
589
|
-
:
|
590
|
-
:
|
591
|
-
:
|
592
|
-
:
|
593
|
-
:
|
594
|
-
:
|
595
|
-
:
|
596
|
-
:
|
597
|
-
}.delete_if { |
|
890
|
+
application: Stripe.app_info,
|
891
|
+
bindings_version: Stripe::VERSION,
|
892
|
+
lang: "ruby",
|
893
|
+
lang_version: lang_version,
|
894
|
+
platform: RUBY_PLATFORM,
|
895
|
+
engine: defined?(RUBY_ENGINE) ? RUBY_ENGINE : "",
|
896
|
+
publisher: "stripe",
|
897
|
+
uname: @uname,
|
898
|
+
hostname: Socket.gethostname,
|
899
|
+
}.delete_if { |_k, v| v.nil? }
|
900
|
+
end
|
901
|
+
end
|
902
|
+
|
903
|
+
# StripeRequestMetrics tracks metadata to be reported to stripe for metrics
|
904
|
+
# collection
|
905
|
+
class StripeRequestMetrics
|
906
|
+
# The Stripe request ID of the response.
|
907
|
+
attr_accessor :request_id
|
908
|
+
|
909
|
+
# Request duration in milliseconds
|
910
|
+
attr_accessor :request_duration_ms
|
911
|
+
|
912
|
+
def initialize(request_id, request_duration_ms)
|
913
|
+
self.request_id = request_id
|
914
|
+
self.request_duration_ms = request_duration_ms
|
915
|
+
end
|
916
|
+
|
917
|
+
def payload
|
918
|
+
{ request_id: request_id, request_duration_ms: request_duration_ms }
|
598
919
|
end
|
599
920
|
end
|
600
921
|
end
|