stripe 4.9.0 → 5.28.0

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