stripe 5.1.0 → 5.55.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (224) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +241 -17
  3. data/CODE_OF_CONDUCT.md +77 -0
  4. data/Gemfile +9 -5
  5. data/Makefile +7 -0
  6. data/README.md +105 -37
  7. data/VERSION +1 -1
  8. data/lib/stripe/api_operations/create.rb +1 -1
  9. data/lib/stripe/api_operations/delete.rb +7 -3
  10. data/lib/stripe/api_operations/list.rb +1 -6
  11. data/lib/stripe/api_operations/nested_resource.rb +29 -26
  12. data/lib/stripe/api_operations/request.rb +82 -6
  13. data/lib/stripe/api_operations/save.rb +7 -4
  14. data/lib/stripe/api_operations/search.rb +19 -0
  15. data/lib/stripe/api_resource.rb +13 -19
  16. data/lib/stripe/api_resource_test_helpers.rb +47 -0
  17. data/lib/stripe/connection_manager.rb +85 -26
  18. data/lib/stripe/error_object.rb +2 -3
  19. data/lib/stripe/errors.rb +9 -1
  20. data/lib/stripe/instrumentation.rb +84 -0
  21. data/lib/stripe/list_object.rb +32 -4
  22. data/lib/stripe/oauth.rb +8 -6
  23. data/lib/stripe/object_types.rb +26 -1
  24. data/lib/stripe/resources/account.rb +5 -9
  25. data/lib/stripe/resources/account_link.rb +1 -0
  26. data/lib/stripe/resources/apple_pay_domain.rb +1 -0
  27. data/lib/stripe/resources/application_fee.rb +1 -0
  28. data/lib/stripe/resources/application_fee_refund.rb +2 -1
  29. data/lib/stripe/resources/balance.rb +1 -0
  30. data/lib/stripe/resources/balance_transaction.rb +1 -0
  31. data/lib/stripe/resources/bank_account.rb +2 -1
  32. data/lib/stripe/resources/billing_portal/configuration.rb +14 -0
  33. data/lib/stripe/resources/billing_portal/session.rb +12 -0
  34. data/lib/stripe/resources/bitcoin_receiver.rb +1 -0
  35. data/lib/stripe/resources/bitcoin_transaction.rb +3 -2
  36. data/lib/stripe/resources/capability.rb +2 -1
  37. data/lib/stripe/resources/card.rb +1 -0
  38. data/lib/stripe/resources/cash_balance.rb +22 -0
  39. data/lib/stripe/resources/charge.rb +10 -0
  40. data/lib/stripe/resources/checkout/session.rb +16 -0
  41. data/lib/stripe/resources/country_spec.rb +1 -0
  42. data/lib/stripe/resources/coupon.rb +1 -0
  43. data/lib/stripe/resources/credit_note.rb +11 -0
  44. data/lib/stripe/resources/credit_note_line_item.rb +8 -0
  45. data/lib/stripe/resources/customer.rb +41 -2
  46. data/lib/stripe/resources/customer_balance_transaction.rb +3 -2
  47. data/lib/stripe/resources/discount.rb +1 -0
  48. data/lib/stripe/resources/dispute.rb +1 -0
  49. data/lib/stripe/resources/ephemeral_key.rb +1 -0
  50. data/lib/stripe/resources/event.rb +1 -0
  51. data/lib/stripe/resources/exchange_rate.rb +1 -0
  52. data/lib/stripe/resources/file.rb +3 -1
  53. data/lib/stripe/resources/file_link.rb +1 -0
  54. data/lib/stripe/resources/financial_connections/account.rb +31 -0
  55. data/lib/stripe/resources/financial_connections/account_owner.rb +10 -0
  56. data/lib/stripe/resources/financial_connections/account_ownership.rb +10 -0
  57. data/lib/stripe/resources/financial_connections/session.rb +12 -0
  58. data/lib/stripe/resources/funding_instructions.rb +16 -0
  59. data/lib/stripe/resources/identity/verification_report.rb +12 -0
  60. data/lib/stripe/resources/identity/verification_session.rb +35 -0
  61. data/lib/stripe/resources/invoice.rb +12 -2
  62. data/lib/stripe/resources/invoice_item.rb +1 -0
  63. data/lib/stripe/resources/invoice_line_item.rb +1 -0
  64. data/lib/stripe/resources/issuing/authorization.rb +1 -0
  65. data/lib/stripe/resources/issuing/card.rb +1 -0
  66. data/lib/stripe/resources/issuing/card_details.rb +2 -1
  67. data/lib/stripe/resources/issuing/cardholder.rb +1 -0
  68. data/lib/stripe/resources/issuing/dispute.rb +12 -0
  69. data/lib/stripe/resources/issuing/transaction.rb +1 -0
  70. data/lib/stripe/resources/line_item.rb +8 -0
  71. data/lib/stripe/resources/login_link.rb +1 -0
  72. data/lib/stripe/resources/mandate.rb +8 -0
  73. data/lib/stripe/resources/order.rb +1 -0
  74. data/lib/stripe/resources/order_return.rb +1 -0
  75. data/lib/stripe/resources/payment_intent.rb +40 -0
  76. data/lib/stripe/resources/payment_link.rb +23 -0
  77. data/lib/stripe/resources/payment_method.rb +1 -0
  78. data/lib/stripe/resources/payout.rb +11 -0
  79. data/lib/stripe/resources/person.rb +1 -0
  80. data/lib/stripe/resources/plan.rb +1 -0
  81. data/lib/stripe/resources/price.rb +21 -0
  82. data/lib/stripe/resources/product.rb +10 -0
  83. data/lib/stripe/resources/promotion_code.rb +12 -0
  84. data/lib/stripe/resources/quote.rb +105 -0
  85. data/lib/stripe/resources/radar/early_fraud_warning.rb +1 -0
  86. data/lib/stripe/resources/radar/value_list.rb +1 -0
  87. data/lib/stripe/resources/radar/value_list_item.rb +1 -0
  88. data/lib/stripe/resources/recipient.rb +1 -0
  89. data/lib/stripe/resources/refund.rb +31 -0
  90. data/lib/stripe/resources/reporting/report_run.rb +1 -0
  91. data/lib/stripe/resources/reporting/report_type.rb +1 -0
  92. data/lib/stripe/resources/reversal.rb +3 -2
  93. data/lib/stripe/resources/review.rb +1 -0
  94. data/lib/stripe/resources/setup_attempt.rb +10 -0
  95. data/lib/stripe/resources/setup_intent.rb +11 -0
  96. data/lib/stripe/resources/shipping_rate.rb +12 -0
  97. data/lib/stripe/resources/sigma/scheduled_query_run.rb +1 -0
  98. data/lib/stripe/resources/sku.rb +1 -0
  99. data/lib/stripe/resources/source.rb +10 -3
  100. data/lib/stripe/resources/source_transaction.rb +1 -0
  101. data/lib/stripe/resources/subscription.rb +10 -0
  102. data/lib/stripe/resources/subscription_item.rb +7 -1
  103. data/lib/stripe/resources/subscription_schedule.rb +1 -0
  104. data/lib/stripe/resources/tax_code.rb +10 -0
  105. data/lib/stripe/resources/tax_id.rb +1 -0
  106. data/lib/stripe/resources/tax_rate.rb +1 -0
  107. data/lib/stripe/resources/terminal/configuration.rb +15 -0
  108. data/lib/stripe/resources/terminal/connection_token.rb +1 -0
  109. data/lib/stripe/resources/terminal/location.rb +1 -0
  110. data/lib/stripe/resources/terminal/reader.rb +61 -0
  111. data/lib/stripe/resources/test_helpers/test_clock.rb +25 -0
  112. data/lib/stripe/resources/three_d_secure.rb +1 -0
  113. data/lib/stripe/resources/token.rb +1 -0
  114. data/lib/stripe/resources/topup.rb +1 -0
  115. data/lib/stripe/resources/transfer.rb +1 -0
  116. data/lib/stripe/resources/usage_record.rb +1 -0
  117. data/lib/stripe/resources/usage_record_summary.rb +1 -0
  118. data/lib/stripe/resources/webhook_endpoint.rb +1 -0
  119. data/lib/stripe/resources.rb +23 -0
  120. data/lib/stripe/search_result_object.rb +86 -0
  121. data/lib/stripe/stripe_client.rb +412 -146
  122. data/lib/stripe/stripe_configuration.rb +194 -0
  123. data/lib/stripe/stripe_object.rb +26 -2
  124. data/lib/stripe/stripe_response.rb +80 -52
  125. data/lib/stripe/util.rb +74 -7
  126. data/lib/stripe/version.rb +1 -1
  127. data/lib/stripe/webhook.rb +38 -7
  128. data/lib/stripe.rb +39 -168
  129. data/stripe.gemspec +12 -5
  130. metadata +36 -186
  131. data/.editorconfig +0 -10
  132. data/.gitattributes +0 -4
  133. data/.github/ISSUE_TEMPLATE.md +0 -5
  134. data/.gitignore +0 -8
  135. data/.rubocop.yml +0 -56
  136. data/.rubocop_todo.yml +0 -39
  137. data/.travis.yml +0 -39
  138. data/.vscode/extensions.json +0 -7
  139. data/.vscode/settings.json +0 -8
  140. data/test/api_stub_helpers.rb +0 -1
  141. data/test/openapi/README.md +0 -9
  142. data/test/stripe/account_link_test.rb +0 -18
  143. data/test/stripe/account_test.rb +0 -412
  144. data/test/stripe/alipay_account_test.rb +0 -37
  145. data/test/stripe/api_operations_test.rb +0 -80
  146. data/test/stripe/api_resource_test.rb +0 -613
  147. data/test/stripe/apple_pay_domain_test.rb +0 -46
  148. data/test/stripe/application_fee_refund_test.rb +0 -37
  149. data/test/stripe/application_fee_test.rb +0 -58
  150. data/test/stripe/balance_test.rb +0 -13
  151. data/test/stripe/balance_transaction_test.rb +0 -20
  152. data/test/stripe/bank_account_test.rb +0 -36
  153. data/test/stripe/capability_test.rb +0 -45
  154. data/test/stripe/charge_test.rb +0 -64
  155. data/test/stripe/checkout/session_test.rb +0 -41
  156. data/test/stripe/connection_manager_test.rb +0 -138
  157. data/test/stripe/country_spec_test.rb +0 -20
  158. data/test/stripe/coupon_test.rb +0 -61
  159. data/test/stripe/credit_note_test.rb +0 -61
  160. data/test/stripe/customer_balance_transaction_test.rb +0 -37
  161. data/test/stripe/customer_card_test.rb +0 -42
  162. data/test/stripe/customer_test.rb +0 -226
  163. data/test/stripe/dispute_test.rb +0 -51
  164. data/test/stripe/ephemeral_key_test.rb +0 -93
  165. data/test/stripe/errors_test.rb +0 -41
  166. data/test/stripe/exchange_rate_test.rb +0 -20
  167. data/test/stripe/file_link_test.rb +0 -41
  168. data/test/stripe/file_test.rb +0 -87
  169. data/test/stripe/invoice_item_test.rb +0 -66
  170. data/test/stripe/invoice_line_item_test.rb +0 -8
  171. data/test/stripe/invoice_test.rb +0 -229
  172. data/test/stripe/issuing/authorization_test.rb +0 -72
  173. data/test/stripe/issuing/card_test.rb +0 -62
  174. data/test/stripe/issuing/cardholder_test.rb +0 -53
  175. data/test/stripe/issuing/dispute_test.rb +0 -45
  176. data/test/stripe/issuing/transaction_test.rb +0 -48
  177. data/test/stripe/list_object_test.rb +0 -140
  178. data/test/stripe/login_link_test.rb +0 -37
  179. data/test/stripe/multipart_encoder_test.rb +0 -130
  180. data/test/stripe/oauth_test.rb +0 -88
  181. data/test/stripe/order_return_test.rb +0 -21
  182. data/test/stripe/order_test.rb +0 -82
  183. data/test/stripe/payment_intent_test.rb +0 -107
  184. data/test/stripe/payment_method_test.rb +0 -84
  185. data/test/stripe/payout_test.rb +0 -57
  186. data/test/stripe/person_test.rb +0 -46
  187. data/test/stripe/plan_test.rb +0 -98
  188. data/test/stripe/product_test.rb +0 -59
  189. data/test/stripe/radar/early_fraud_warning_test.rb +0 -22
  190. data/test/stripe/radar/value_list_item_test.rb +0 -48
  191. data/test/stripe/radar/value_list_test.rb +0 -61
  192. data/test/stripe/recipient_test.rb +0 -62
  193. data/test/stripe/refund_test.rb +0 -39
  194. data/test/stripe/reporting/report_run_test.rb +0 -33
  195. data/test/stripe/reporting/report_type_test.rb +0 -22
  196. data/test/stripe/reversal_test.rb +0 -43
  197. data/test/stripe/review_test.rb +0 -27
  198. data/test/stripe/setup_intent_test.rb +0 -84
  199. data/test/stripe/sigma/scheduled_query_run_test.rb +0 -22
  200. data/test/stripe/sku_test.rb +0 -60
  201. data/test/stripe/source_test.rb +0 -81
  202. data/test/stripe/source_transaction_test.rb +0 -19
  203. data/test/stripe/stripe_client_test.rb +0 -1039
  204. data/test/stripe/stripe_object_test.rb +0 -497
  205. data/test/stripe/stripe_response_test.rb +0 -95
  206. data/test/stripe/subscription_item_test.rb +0 -75
  207. data/test/stripe/subscription_schedule_test.rb +0 -82
  208. data/test/stripe/subscription_test.rb +0 -80
  209. data/test/stripe/tax_id_test.rb +0 -31
  210. data/test/stripe/tax_rate_test.rb +0 -43
  211. data/test/stripe/terminal/connection_token_test.rb +0 -16
  212. data/test/stripe/terminal/location_test.rb +0 -68
  213. data/test/stripe/terminal/reader_test.rb +0 -62
  214. data/test/stripe/three_d_secure_test.rb +0 -23
  215. data/test/stripe/topup_test.rb +0 -62
  216. data/test/stripe/transfer_test.rb +0 -88
  217. data/test/stripe/usage_record_summary_test.rb +0 -19
  218. data/test/stripe/util_test.rb +0 -402
  219. data/test/stripe/webhook_endpoint_test.rb +0 -59
  220. data/test/stripe/webhook_test.rb +0 -96
  221. data/test/stripe_mock.rb +0 -78
  222. data/test/stripe_test.rb +0 -50
  223. data/test/test_data.rb +0 -61
  224. data/test/test_helper.rb +0 -76
@@ -1,26 +1,44 @@
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
- # A set of all known connection managers across all threads and a mutex to
10
+ # A set of all known thread contexts across all threads and a mutex to
9
11
  # synchronize global access to them.
10
- @all_connection_managers = []
11
- @all_connection_managers_mutex = Mutex.new
12
-
13
- attr_accessor :connection_manager
12
+ @thread_contexts_with_connection_managers = Set.new
13
+ @thread_contexts_with_connection_managers_mutex = Mutex.new
14
+ @last_connection_manager_gc = Util.monotonic_time
14
15
 
15
- # Initializes a new `StripeClient`. Expects a `ConnectionManager` object,
16
- # and uses a default connection manager unless one is passed.
17
- def initialize(connection_manager = nil)
18
- self.connection_manager = connection_manager ||
19
- self.class.default_connection_manager
16
+ # Initializes a new StripeClient
17
+ def initialize(config_arg = {})
20
18
  @system_profiler = SystemProfiler.new
21
19
  @last_request_metrics = nil
20
+
21
+ @config = case config_arg
22
+ when Hash
23
+ Stripe.config.reverse_duplicate_merge(config_arg)
24
+ when Stripe::ConnectionManager
25
+ # Supports accepting a connection manager object for backwards
26
+ # compatibility only, and that use is DEPRECATED.
27
+ Stripe.config.dup
28
+ when Stripe::StripeConfiguration
29
+ config_arg
30
+ when String
31
+ Stripe.config.reverse_duplicate_merge(
32
+ { api_key: config_arg }
33
+ )
34
+ else
35
+ raise ArgumentError, "Can't handle argument: #{config_arg}"
36
+ end
22
37
  end
23
38
 
39
+ attr_reader :config
40
+ attr_reader :options
41
+
24
42
  # Gets a currently active `StripeClient`. Set for the current thread when
25
43
  # `StripeClient#request` is being run so that API operations being executed
26
44
  # inside of that block can find the currently active client. It's reset to
@@ -36,32 +54,55 @@ module Stripe
36
54
  # clears them from internal tracking in all connection managers across all
37
55
  # threads.
38
56
  #
57
+ # If passed a `config` object, only clear connection managers for that
58
+ # particular configuration.
59
+ #
39
60
  # For internal use only. Does not provide a stable API and may be broken
40
61
  # with future non-major changes.
41
- def self.clear_all_connection_managers
62
+ def self.clear_all_connection_managers(config: nil)
42
63
  # Just a quick path for when configuration is being set for the first
43
64
  # time before any connections have been opened. There is technically some
44
65
  # potential for thread raciness here, but not in a practical sense.
45
- return if @all_connection_managers.empty?
66
+ return if @thread_contexts_with_connection_managers.empty?
67
+
68
+ @thread_contexts_with_connection_managers_mutex.synchronize do
69
+ pruned_contexts = Set.new
70
+
71
+ @thread_contexts_with_connection_managers.each do |thread_context|
72
+ # Note that the thread context itself is not destroyed, but we clear
73
+ # its connection manager and remove our reference to it. If it ever
74
+ # makes a new request we'll give it a new connection manager and
75
+ # it'll go back into `@thread_contexts_with_connection_managers`.
76
+ thread_context.default_connection_managers.reject! do |cm_config, cm|
77
+ if config.nil? || config.key == cm_config
78
+ cm.clear
79
+ true
80
+ end
81
+ end
46
82
 
47
- @all_connection_managers_mutex.synchronize do
48
- @all_connection_managers.each(&:clear)
83
+ if thread_context.default_connection_managers.empty?
84
+ pruned_contexts << thread_context
85
+ end
86
+ end
87
+
88
+ @thread_contexts_with_connection_managers.subtract(pruned_contexts)
49
89
  end
50
90
  end
51
91
 
52
92
  # A default client for the current thread.
53
93
  def self.default_client
54
- current_thread_context.default_client ||=
55
- StripeClient.new(default_connection_manager)
94
+ current_thread_context.default_client ||= StripeClient.new(Stripe.config)
56
95
  end
57
96
 
58
- # A default connection manager for the current thread.
59
- def self.default_connection_manager
60
- current_thread_context.default_connection_manager ||= begin
61
- connection_manager = ConnectionManager.new
97
+ # A default connection manager for the current thread scoped to the
98
+ # configuration object that may be provided.
99
+ def self.default_connection_manager(config = Stripe.config)
100
+ current_thread_context.default_connection_managers[config.key] ||= begin
101
+ connection_manager = ConnectionManager.new(config)
62
102
 
63
- @all_connection_managers_mutex.synchronize do
64
- @all_connection_managers << connection_manager
103
+ @thread_contexts_with_connection_managers_mutex.synchronize do
104
+ maybe_gc_connection_managers
105
+ @thread_contexts_with_connection_managers << current_thread_context
65
106
  end
66
107
 
67
108
  connection_manager
@@ -71,20 +112,27 @@ module Stripe
71
112
  # Checks if an error is a problem that we should retry on. This includes
72
113
  # both socket errors that may represent an intermittent problem and some
73
114
  # special HTTP statuses.
74
- def self.should_retry?(error, method:, num_retries:)
75
- return false if num_retries >= Stripe.max_network_retries
76
-
77
- # Retry on timeout-related problems (either on open or read).
78
- return true if error.is_a?(Net::OpenTimeout)
79
- return true if error.is_a?(Net::ReadTimeout)
80
-
81
- # Destination refused the connection, the connection was reset, or a
82
- # variety of other connection failures. This could occur from a single
83
- # saturated server, so retry in case it's intermittent.
84
- return true if error.is_a?(Errno::ECONNREFUSED)
85
- return true if error.is_a?(SocketError)
115
+ def self.should_retry?(error,
116
+ method:, num_retries:, config: Stripe.config)
117
+ return false if num_retries >= config.max_network_retries
118
+
119
+ case error
120
+ when Net::OpenTimeout, Net::ReadTimeout
121
+ # Retry on timeout-related problems (either on open or read).
122
+ true
123
+ when EOFError, Errno::ECONNREFUSED, Errno::ECONNRESET,
124
+ Errno::EHOSTUNREACH, Errno::ETIMEDOUT, SocketError
125
+ # Destination refused the connection, the connection was reset, or a
126
+ # variety of other connection failures. This could occur from a single
127
+ # saturated server, so retry in case it's intermittent.
128
+ true
129
+ when Stripe::StripeError
130
+ # The API may ask us not to retry (e.g. if doing so would be a no-op),
131
+ # or advise us to retry (e.g. in cases of lock timeouts). Defer to
132
+ # those instructions if given.
133
+ return false if error.http_headers["stripe-should-retry"] == "false"
134
+ return true if error.http_headers["stripe-should-retry"] == "true"
86
135
 
87
- if error.is_a?(Stripe::StripeError)
88
136
  # 409 Conflict
89
137
  return true if error.http_status == 409
90
138
 
@@ -106,19 +154,19 @@ module Stripe
106
154
  return true if error.http_status == 500 && method != :post
107
155
 
108
156
  # 503 Service Unavailable
109
- return true if error.http_status == 503
157
+ error.http_status == 503
158
+ else
159
+ false
110
160
  end
111
-
112
- false
113
161
  end
114
162
 
115
- def self.sleep_time(num_retries)
163
+ def self.sleep_time(num_retries, config: Stripe.config)
116
164
  # Apply exponential backoff with initial_network_retry_delay on the
117
165
  # number of num_retries so far as inputs. Do not allow the number to
118
166
  # exceed max_network_retry_delay.
119
167
  sleep_seconds = [
120
- Stripe.initial_network_retry_delay * (2**(num_retries - 1)),
121
- Stripe.max_network_retry_delay,
168
+ config.initial_network_retry_delay * (2**(num_retries - 1)),
169
+ config.max_network_retry_delay,
122
170
  ].min
123
171
 
124
172
  # Apply some jitter by randomizing the value in the range of
@@ -126,10 +174,17 @@ module Stripe
126
174
  sleep_seconds *= (0.5 * (1 + rand))
127
175
 
128
176
  # But never sleep less than the base sleep seconds.
129
- sleep_seconds = [Stripe.initial_network_retry_delay, sleep_seconds].max
177
+ [config.initial_network_retry_delay, sleep_seconds].max
178
+ end
130
179
 
131
- sleep_seconds
180
+ # Gets the connection manager in use for the current `StripeClient`.
181
+ #
182
+ # This method is DEPRECATED and for backwards compatibility only.
183
+ def connection_manager
184
+ self.class.default_connection_manager
132
185
  end
186
+ extend Gem::Deprecate
187
+ deprecate :connection_manager, :none, 2020, 9
133
188
 
134
189
  # Executes the API call within the given block. Usage looks like:
135
190
  #
@@ -158,60 +213,9 @@ module Stripe
158
213
 
159
214
  def execute_request(method, path,
160
215
  api_base: nil, api_key: nil, headers: {}, params: {})
161
- raise ArgumentError, "method should be a symbol" \
162
- unless method.is_a?(Symbol)
163
- raise ArgumentError, "path should be a string" \
164
- unless path.is_a?(String)
165
-
166
- api_base ||= Stripe.api_base
167
- api_key ||= Stripe.api_key
168
- params = Util.objects_to_ids(params)
169
-
170
- check_api_key!(api_key)
171
-
172
- body_params = nil
173
- query_params = nil
174
- case method
175
- when :get, :head, :delete
176
- query_params = params
177
- else
178
- body_params = params
179
- end
180
-
181
- query_params, path = merge_query_params(query_params, path)
182
-
183
- headers = request_headers(api_key, method)
184
- .update(Util.normalize_headers(headers))
185
- url = api_url(path, api_base)
186
-
187
- # Merge given query parameters with any already encoded in the path.
188
- query = query_params ? Util.encode_parameters(query_params) : nil
189
-
190
- # Encoding body parameters is a little more complex because we may have
191
- # to send a multipart-encoded body. `body_log` is produced separately as
192
- # a log-friendly variant of the encoded form. File objects are displayed
193
- # as such instead of as their file contents.
194
- body, body_log =
195
- body_params ? encode_body(body_params, headers) : [nil, nil]
196
-
197
- # stores information on the request we're about to make so that we don't
198
- # have to pass as many parameters around for logging.
199
- context = RequestLogContext.new
200
- context.account = headers["Stripe-Account"]
201
- context.api_key = api_key
202
- context.api_version = headers["Stripe-Version"]
203
- context.body = body_log
204
- context.idempotency_key = headers["Idempotency-Key"]
205
- context.method = method
206
- context.path = path
207
- context.query = query
208
-
209
- http_resp = execute_request_with_rescues(method, api_base, context) do
210
- connection_manager.execute_request(method, url,
211
- body: body,
212
- headers: headers,
213
- query: query)
214
- end
216
+ http_resp, api_key = execute_request_internal(
217
+ method, path, api_base, api_key, headers, params
218
+ )
215
219
 
216
220
  begin
217
221
  resp = StripeResponse.from_net_http(http_resp)
@@ -222,17 +226,65 @@ module Stripe
222
226
  # If being called from `StripeClient#request`, put the last response in
223
227
  # thread-local memory so that it can be returned to the user. Don't store
224
228
  # anything otherwise so that we don't leak memory.
225
- if self.class.current_thread_context.last_responses&.key?(object_id)
226
- self.class.current_thread_context.last_responses[object_id] = resp
229
+ store_last_response(object_id, resp)
230
+
231
+ [resp, api_key]
232
+ end
233
+
234
+ # Executes a request and returns the body as a stream instead of converting
235
+ # it to a StripeObject. This should be used for any request where we expect
236
+ # an arbitrary binary response.
237
+ #
238
+ # A `read_body_chunk` block can be passed, which will be called repeatedly
239
+ # with the body chunks read from the socket.
240
+ #
241
+ # If a block is passed, a StripeHeadersOnlyResponse is returned as the
242
+ # block is expected to do all the necessary body processing. If no block is
243
+ # passed, then a StripeStreamResponse is returned containing an IO stream
244
+ # with the response body.
245
+ def execute_request_stream(method, path,
246
+ api_base: nil, api_key: nil,
247
+ headers: {}, params: {},
248
+ &read_body_chunk_block)
249
+ unless block_given?
250
+ raise ArgumentError,
251
+ "execute_request_stream requires a read_body_chunk_block"
227
252
  end
228
253
 
254
+ http_resp, api_key = execute_request_internal(
255
+ method, path, api_base, api_key, headers, params, &read_body_chunk_block
256
+ )
257
+
258
+ # When the read_body_chunk_block is given, we no longer have access to the
259
+ # response body at this point and so return a response object containing
260
+ # only the headers. This is because the body was consumed by the block.
261
+ resp = StripeHeadersOnlyResponse.from_net_http(http_resp)
262
+
229
263
  [resp, api_key]
230
264
  end
231
265
 
266
+ def store_last_response(object_id, resp)
267
+ return unless last_response_has_key?(object_id)
268
+
269
+ self.class.current_thread_context.last_responses[object_id] = resp
270
+ end
271
+
272
+ def last_response_has_key?(object_id)
273
+ self.class.current_thread_context.last_responses&.key?(object_id)
274
+ end
275
+
232
276
  #
233
277
  # private
234
278
  #
235
279
 
280
+ # Time (in seconds) that a connection manager has not been used before it's
281
+ # eligible for garbage collection.
282
+ CONNECTION_MANAGER_GC_LAST_USED_EXPIRY = 120
283
+
284
+ # How often to check (in seconds) for connection managers that haven't been
285
+ # used in a long time and which should be garbage collected.
286
+ CONNECTION_MANAGER_GC_PERIOD = 60
287
+
236
288
  ERROR_MESSAGE_CONNECTION =
237
289
  "Unexpected error communicating when trying to connect to " \
238
290
  "Stripe (%s). You may be seeing this message because your DNS is not " \
@@ -266,7 +318,11 @@ module Stripe
266
318
  # The original error message is also appended onto the final exception for
267
319
  # full transparency.
268
320
  NETWORK_ERROR_MESSAGES_MAP = {
321
+ EOFError => ERROR_MESSAGE_CONNECTION,
269
322
  Errno::ECONNREFUSED => ERROR_MESSAGE_CONNECTION,
323
+ Errno::ECONNRESET => ERROR_MESSAGE_CONNECTION,
324
+ Errno::EHOSTUNREACH => ERROR_MESSAGE_CONNECTION,
325
+ Errno::ETIMEDOUT => ERROR_MESSAGE_TIMEOUT_CONNECT,
270
326
  SocketError => ERROR_MESSAGE_CONNECTION,
271
327
 
272
328
  Net::OpenTimeout => ERROR_MESSAGE_TIMEOUT_CONNECT,
@@ -292,11 +348,6 @@ module Stripe
292
348
  # the user hasn't specified their own.
293
349
  attr_accessor :default_client
294
350
 
295
- # A default `ConnectionManager` for the thread. Normally shared between
296
- # all `StripeClient` objects on a particular thread, and created so as to
297
- # minimize the number of open connections that an application needs.
298
- attr_accessor :default_connection_manager
299
-
300
351
  # A temporary map of object IDs to responses from last executed API
301
352
  # calls. Used to return a responses from calls to `StripeClient#request`.
302
353
  #
@@ -309,6 +360,17 @@ module Stripe
309
360
  # because that's wrapped in an `ensure` block, they should never leave
310
361
  # garbage in `Thread.current`.
311
362
  attr_accessor :last_responses
363
+
364
+ # A map of connection mangers for the thread. Normally shared between
365
+ # all `StripeClient` objects on a particular thread, and created so as to
366
+ # minimize the number of open connections that an application needs.
367
+ def default_connection_managers
368
+ @default_connection_managers ||= {}
369
+ end
370
+
371
+ def reset_connection_managers
372
+ @default_connection_managers = {}
373
+ end
312
374
  end
313
375
 
314
376
  # Access data stored for `StripeClient` within the thread's current
@@ -320,8 +382,133 @@ module Stripe
320
382
  Thread.current[:stripe_client__internal_use_only] ||= ThreadContext.new
321
383
  end
322
384
 
385
+ # Garbage collects connection managers that haven't been used in some time,
386
+ # with the idea being that we want to remove old connection managers that
387
+ # belong to dead threads and the like.
388
+ #
389
+ # Prefixed with `maybe_` because garbage collection will only run
390
+ # periodically so that we're not constantly engaged in busy work. If
391
+ # connection managers live a little passed their useful age it's not
392
+ # harmful, so it's not necessary to get them right away.
393
+ #
394
+ # For testability, returns `nil` if it didn't run and the number of
395
+ # connection managers that were garbage collected otherwise.
396
+ #
397
+ # IMPORTANT: This method is not thread-safe and expects to be called inside
398
+ # a lock on `@thread_contexts_with_connection_managers_mutex`.
399
+ #
400
+ # For internal use only. Does not provide a stable API and may be broken
401
+ # with future non-major changes.
402
+ def self.maybe_gc_connection_managers
403
+ next_gc_time = @last_connection_manager_gc + CONNECTION_MANAGER_GC_PERIOD
404
+ return nil if next_gc_time > Util.monotonic_time
405
+
406
+ last_used_threshold =
407
+ Util.monotonic_time - CONNECTION_MANAGER_GC_LAST_USED_EXPIRY
408
+
409
+ pruned_contexts = []
410
+ @thread_contexts_with_connection_managers.each do |thread_context|
411
+ thread_context
412
+ .default_connection_managers
413
+ .each do |config_key, connection_manager|
414
+ next if connection_manager.last_used > last_used_threshold
415
+
416
+ connection_manager.clear
417
+ thread_context.default_connection_managers.delete(config_key)
418
+ end
419
+ end
420
+
421
+ @thread_contexts_with_connection_managers.each do |thread_context|
422
+ next unless thread_context.default_connection_managers.empty?
423
+
424
+ pruned_contexts << thread_context
425
+ end
426
+
427
+ @thread_contexts_with_connection_managers -= pruned_contexts
428
+ @last_connection_manager_gc = Util.monotonic_time
429
+
430
+ pruned_contexts.count
431
+ end
432
+
433
+ private def execute_request_internal(method, path,
434
+ api_base, api_key, headers, params,
435
+ &read_body_chunk_block)
436
+ raise ArgumentError, "method should be a symbol" \
437
+ unless method.is_a?(Symbol)
438
+ raise ArgumentError, "path should be a string" \
439
+ unless path.is_a?(String)
440
+
441
+ api_base ||= config.api_base
442
+ api_key ||= config.api_key
443
+ params = Util.objects_to_ids(params)
444
+
445
+ check_api_key!(api_key)
446
+
447
+ body_params = nil
448
+ query_params = nil
449
+ case method
450
+ when :get, :head, :delete
451
+ query_params = params
452
+ else
453
+ body_params = params
454
+ end
455
+
456
+ query_params, path = merge_query_params(query_params, path)
457
+
458
+ headers = request_headers(api_key, method)
459
+ .update(Util.normalize_headers(headers))
460
+ url = api_url(path, api_base)
461
+
462
+ # Merge given query parameters with any already encoded in the path.
463
+ query = query_params ? Util.encode_parameters(query_params) : nil
464
+
465
+ # Encoding body parameters is a little more complex because we may have
466
+ # to send a multipart-encoded body. `body_log` is produced separately as
467
+ # a log-friendly variant of the encoded form. File objects are displayed
468
+ # as such instead of as their file contents.
469
+ body, body_log =
470
+ body_params ? encode_body(body_params, headers) : [nil, nil]
471
+
472
+ # stores information on the request we're about to make so that we don't
473
+ # have to pass as many parameters around for logging.
474
+ context = RequestLogContext.new
475
+ context.account = headers["Stripe-Account"]
476
+ context.api_key = api_key
477
+ context.api_version = headers["Stripe-Version"]
478
+ context.body = body_log
479
+ context.idempotency_key = headers["Idempotency-Key"]
480
+ context.method = method
481
+ context.path = path
482
+ context.query = query
483
+
484
+ # A block can be passed in to read the content directly from the response.
485
+ # We want to execute this block only when the response was actually
486
+ # successful. When it wasn't, we defer to the standard error handling as
487
+ # we have to read the body and parse the error JSON.
488
+ response_block =
489
+ if block_given?
490
+ lambda do |response|
491
+ unless should_handle_as_error(response.code.to_i)
492
+ response.read_body(&read_body_chunk_block)
493
+ end
494
+ end
495
+ end
496
+
497
+ http_resp = execute_request_with_rescues(method, api_base, context) do
498
+ self.class
499
+ .default_connection_manager(config)
500
+ .execute_request(method, url,
501
+ body: body,
502
+ headers: headers,
503
+ query: query,
504
+ &response_block)
505
+ end
506
+
507
+ [http_resp, api_key]
508
+ end
509
+
323
510
  private def api_url(url = "", api_base = nil)
324
- (api_base || Stripe.api_base) + url
511
+ (api_base || config.api_base) + url
325
512
  end
326
513
 
327
514
  private def check_api_key!(api_key)
@@ -359,6 +546,7 @@ module Stripe
359
546
  # that's more condusive to logging.
360
547
  flattened_params =
361
548
  flattened_params.map { |k, v| [k, v.is_a?(String) ? v : v.to_s] }.to_h
549
+
362
550
  else
363
551
  body = Util.encode_parameters(body_params)
364
552
  end
@@ -372,20 +560,37 @@ module Stripe
372
560
  [body, body_log]
373
561
  end
374
562
 
563
+ private def should_handle_as_error(http_status)
564
+ http_status >= 400
565
+ end
566
+
375
567
  private def execute_request_with_rescues(method, api_base, context)
376
568
  num_retries = 0
569
+
377
570
  begin
378
- request_start = Time.now
571
+ request_start = nil
572
+ user_data = nil
573
+
379
574
  log_request(context, num_retries)
575
+ user_data = notify_request_begin(context)
576
+
577
+ request_start = Util.monotonic_time
380
578
  resp = yield
579
+ request_duration = Util.monotonic_time - request_start
580
+
581
+ http_status = resp.code.to_i
381
582
  context = context.dup_from_response_headers(resp)
382
583
 
383
- handle_error_response(resp, context) if resp.code.to_i >= 400
584
+ if should_handle_as_error(http_status)
585
+ handle_error_response(resp, context)
586
+ end
384
587
 
385
- log_response(context, request_start, resp.code.to_i, resp.body)
588
+ log_response(context, request_start, http_status, resp.body, resp)
589
+ notify_request_end(context, request_duration, http_status,
590
+ num_retries, user_data)
386
591
 
387
- if Stripe.enable_telemetry? && context.request_id
388
- request_duration_ms = ((Time.now - request_start) * 1000).to_int
592
+ if config.enable_telemetry? && context.request_id
593
+ request_duration_ms = (request_duration * 1000).to_i
389
594
  @last_request_metrics =
390
595
  StripeRequestMetrics.new(context.request_id, request_duration_ms)
391
596
  end
@@ -397,18 +602,26 @@ module Stripe
397
602
  # If we modify context we copy it into a new variable so as not to
398
603
  # taint the original on a retry.
399
604
  error_context = context
605
+ http_status = nil
606
+ request_duration = Util.monotonic_time - request_start if request_start
400
607
 
401
608
  if e.is_a?(Stripe::StripeError)
402
609
  error_context = context.dup_from_response_headers(e.http_headers)
610
+ http_status = resp.code.to_i
403
611
  log_response(error_context, request_start,
404
- e.http_status, e.http_body)
612
+ e.http_status, e.http_body, resp)
405
613
  else
406
614
  log_response_error(error_context, request_start, e)
407
615
  end
616
+ notify_request_end(context, request_duration, http_status, num_retries,
617
+ user_data)
408
618
 
409
- if self.class.should_retry?(e, method: method, num_retries: num_retries)
619
+ if self.class.should_retry?(e,
620
+ method: method,
621
+ num_retries: num_retries,
622
+ config: config)
410
623
  num_retries += 1
411
- sleep self.class.sleep_time(num_retries)
624
+ sleep self.class.sleep_time(num_retries, config: config)
412
625
  retry
413
626
  end
414
627
 
@@ -428,6 +641,42 @@ module Stripe
428
641
  resp
429
642
  end
430
643
 
644
+ private def notify_request_begin(context)
645
+ return unless Instrumentation.any_subscribers?(:request_begin)
646
+
647
+ event = Instrumentation::RequestBeginEvent.new(
648
+ method: context.method,
649
+ path: context.path,
650
+ user_data: {}
651
+ )
652
+ Stripe::Instrumentation.notify(:request_begin, event)
653
+
654
+ # This field may be set in the `request_begin` callback. If so, we'll
655
+ # forward it onto `request_end`.
656
+ event.user_data
657
+ end
658
+
659
+ private def notify_request_end(context, duration, http_status, num_retries,
660
+ user_data)
661
+ return if !Instrumentation.any_subscribers?(:request_end) &&
662
+ !Instrumentation.any_subscribers?(:request)
663
+
664
+ event = Instrumentation::RequestEndEvent.new(
665
+ duration: duration,
666
+ http_status: http_status,
667
+ method: context.method,
668
+ num_retries: num_retries,
669
+ path: context.path,
670
+ request_id: context.request_id,
671
+ user_data: user_data || {}
672
+ )
673
+ Stripe::Instrumentation.notify(:request_end, event)
674
+
675
+ # The name before `request_begin` was also added. Provided for backwards
676
+ # compatibility.
677
+ Stripe::Instrumentation.notify(:request, event)
678
+ end
679
+
431
680
  private def general_api_error(status, body)
432
681
  APIError.new("Invalid response object from API: #{body.inspect} " \
433
682
  "(HTTP response code was #{status})",
@@ -495,7 +744,8 @@ module Stripe
495
744
  error_param: error_data[:param],
496
745
  error_type: error_data[:type],
497
746
  idempotency_key: context.idempotency_key,
498
- request_id: context.request_id)
747
+ request_id: context.request_id,
748
+ config: config)
499
749
 
500
750
  # The standard set of arguments that can be used to initialize most of
501
751
  # the exceptions.
@@ -511,26 +761,26 @@ module Stripe
511
761
  when 400, 404
512
762
  case error_data[:type]
513
763
  when "idempotency_error"
514
- IdempotencyError.new(error_data[:message], opts)
764
+ IdempotencyError.new(error_data[:message], **opts)
515
765
  else
516
766
  InvalidRequestError.new(
517
767
  error_data[:message], error_data[:param],
518
- opts
768
+ **opts
519
769
  )
520
770
  end
521
771
  when 401
522
- AuthenticationError.new(error_data[:message], opts)
772
+ AuthenticationError.new(error_data[:message], **opts)
523
773
  when 402
524
774
  CardError.new(
525
775
  error_data[:message], error_data[:param],
526
- opts
776
+ **opts
527
777
  )
528
778
  when 403
529
- PermissionError.new(error_data[:message], opts)
779
+ PermissionError.new(error_data[:message], **opts)
530
780
  when 429
531
- RateLimitError.new(error_data[:message], opts)
781
+ RateLimitError.new(error_data[:message], **opts)
532
782
  else
533
- APIError.new(error_data[:message], opts)
783
+ APIError.new(error_data[:message], **opts)
534
784
  end
535
785
  end
536
786
 
@@ -544,30 +794,31 @@ module Stripe
544
794
  error_code: error_code,
545
795
  error_description: description,
546
796
  idempotency_key: context.idempotency_key,
547
- request_id: context.request_id)
797
+ request_id: context.request_id,
798
+ config: config)
548
799
 
549
- args = [error_code, description, {
800
+ args = {
550
801
  http_status: resp.http_status, http_body: resp.http_body,
551
802
  json_body: resp.data, http_headers: resp.http_headers,
552
- },]
803
+ }
553
804
 
554
805
  case error_code
555
806
  when "invalid_client"
556
- OAuth::InvalidClientError.new(*args)
807
+ OAuth::InvalidClientError.new(error_code, description, **args)
557
808
  when "invalid_grant"
558
- OAuth::InvalidGrantError.new(*args)
809
+ OAuth::InvalidGrantError.new(error_code, description, **args)
559
810
  when "invalid_request"
560
- OAuth::InvalidRequestError.new(*args)
811
+ OAuth::InvalidRequestError.new(error_code, description, **args)
561
812
  when "invalid_scope"
562
- OAuth::InvalidScopeError.new(*args)
813
+ OAuth::InvalidScopeError.new(error_code, description, **args)
563
814
  when "unsupported_grant_type"
564
- OAuth::UnsupportedGrantTypeError.new(*args)
815
+ OAuth::UnsupportedGrantTypeError.new(error_code, description, **args)
565
816
  when "unsupported_response_type"
566
- OAuth::UnsupportedResponseTypeError.new(*args)
817
+ OAuth::UnsupportedResponseTypeError.new(error_code, description, **args)
567
818
  else
568
819
  # We'd prefer that all errors are typed, but we create a generic
569
820
  # OAuthError in case we run into a code that we don't recognize.
570
- OAuth::OAuthError.new(*args)
821
+ OAuth::OAuthError.new(error_code, description, **args)
571
822
  end
572
823
  end
573
824
 
@@ -576,7 +827,8 @@ module Stripe
576
827
  Util.log_error("Stripe network error",
577
828
  error_message: error.message,
578
829
  idempotency_key: context.idempotency_key,
579
- request_id: context.request_id)
830
+ request_id: context.request_id,
831
+ config: config)
580
832
 
581
833
  errors, message = NETWORK_ERROR_MESSAGES_MAP.detect do |(e, _)|
582
834
  error.is_a?(e)
@@ -587,7 +839,7 @@ module Stripe
587
839
  "with Stripe. Please let us know at support@stripe.com."
588
840
  end
589
841
 
590
- api_base ||= Stripe.api_base
842
+ api_base ||= config.api_base
591
843
  message = message % api_base
592
844
 
593
845
  message += " Request was retried #{num_retries} times." if num_retries > 0
@@ -608,7 +860,7 @@ module Stripe
608
860
  "Content-Type" => "application/x-www-form-urlencoded",
609
861
  }
610
862
 
611
- if Stripe.enable_telemetry? && !@last_request_metrics.nil?
863
+ if config.enable_telemetry? && !@last_request_metrics.nil?
612
864
  headers["X-Stripe-Client-Telemetry"] = JSON.generate(
613
865
  last_request_metrics: @last_request_metrics.payload
614
866
  )
@@ -616,12 +868,12 @@ module Stripe
616
868
 
617
869
  # It is only safe to retry network failures on post and delete
618
870
  # requests if we add an Idempotency-Key header
619
- if %i[post delete].include?(method) && Stripe.max_network_retries > 0
871
+ if %i[post delete].include?(method) && config.max_network_retries > 0
620
872
  headers["Idempotency-Key"] ||= SecureRandom.uuid
621
873
  end
622
874
 
623
- headers["Stripe-Version"] = Stripe.api_version if Stripe.api_version
624
- headers["Stripe-Account"] = Stripe.stripe_account if Stripe.stripe_account
875
+ headers["Stripe-Version"] = config.api_version if config.api_version
876
+ headers["Stripe-Account"] = config.stripe_account if config.stripe_account
625
877
 
626
878
  user_agent = @system_profiler.user_agent
627
879
  begin
@@ -645,27 +897,38 @@ module Stripe
645
897
  idempotency_key: context.idempotency_key,
646
898
  method: context.method,
647
899
  num_retries: num_retries,
648
- path: context.path)
900
+ path: context.path,
901
+ config: config)
649
902
  Util.log_debug("Request details",
650
903
  body: context.body,
651
904
  idempotency_key: context.idempotency_key,
652
- query: context.query)
905
+ query: context.query,
906
+ config: config,
907
+ process_id: Process.pid,
908
+ thread_object_id: Thread.current.object_id,
909
+ log_timestamp: Util.monotonic_time)
653
910
  end
654
911
 
655
- private def log_response(context, request_start, status, body)
912
+ private def log_response(context, request_start, status, body, resp)
656
913
  Util.log_info("Response from Stripe API",
657
914
  account: context.account,
658
915
  api_version: context.api_version,
659
- elapsed: Time.now - request_start,
916
+ elapsed: Util.monotonic_time - request_start,
660
917
  idempotency_key: context.idempotency_key,
661
918
  method: context.method,
662
919
  path: context.path,
663
920
  request_id: context.request_id,
664
- status: status)
921
+ status: status,
922
+ config: config)
665
923
  Util.log_debug("Response details",
666
924
  body: body,
667
925
  idempotency_key: context.idempotency_key,
668
- request_id: context.request_id)
926
+ request_id: context.request_id,
927
+ config: config,
928
+ process_id: Process.pid,
929
+ thread_object_id: Thread.current.object_id,
930
+ response_object_id: resp.object_id,
931
+ log_timestamp: Util.monotonic_time)
669
932
 
670
933
  return unless context.request_id
671
934
 
@@ -673,16 +936,19 @@ module Stripe
673
936
  idempotency_key: context.idempotency_key,
674
937
  request_id: context.request_id,
675
938
  url: Util.request_id_dashboard_url(context.request_id,
676
- context.api_key))
939
+ context.api_key),
940
+ config: config)
677
941
  end
678
942
 
679
943
  private def log_response_error(context, request_start, error)
944
+ elapsed = request_start ? Util.monotonic_time - request_start : nil
680
945
  Util.log_error("Request error",
681
- elapsed: Time.now - request_start,
946
+ elapsed: elapsed,
682
947
  error_message: error.message,
683
948
  idempotency_key: context.idempotency_key,
684
949
  method: context.method,
685
- path: context.path)
950
+ path: context.path,
951
+ config: config)
686
952
  end
687
953
 
688
954
  # RequestLogContext stores information about a request that's begin made so