stripe 4.24.0 → 5.36.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (216) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +169 -0
  3. data/CODE_OF_CONDUCT.md +77 -0
  4. data/Gemfile +10 -16
  5. data/README.md +111 -44
  6. data/Rakefile +8 -7
  7. data/VERSION +1 -1
  8. data/lib/stripe.rb +39 -130
  9. data/lib/stripe/api_operations/create.rb +1 -1
  10. data/lib/stripe/api_operations/delete.rb +7 -3
  11. data/lib/stripe/api_operations/list.rb +1 -12
  12. data/lib/stripe/api_operations/nested_resource.rb +29 -26
  13. data/lib/stripe/api_operations/request.rb +82 -6
  14. data/lib/stripe/api_operations/save.rb +7 -4
  15. data/lib/stripe/api_resource.rb +12 -3
  16. data/lib/stripe/connection_manager.rb +179 -0
  17. data/lib/stripe/error_object.rb +94 -0
  18. data/lib/stripe/errors.rb +24 -3
  19. data/lib/stripe/instrumentation.rb +82 -0
  20. data/lib/stripe/list_object.rb +34 -5
  21. data/lib/stripe/multipart_encoder.rb +131 -0
  22. data/lib/stripe/oauth.rb +8 -6
  23. data/lib/stripe/object_types.rb +12 -1
  24. data/lib/stripe/resources.rb +12 -1
  25. data/lib/stripe/resources/account.rb +6 -14
  26. data/lib/stripe/resources/account_link.rb +2 -1
  27. data/lib/stripe/resources/alipay_account.rb +1 -1
  28. data/lib/stripe/resources/apple_pay_domain.rb +2 -1
  29. data/lib/stripe/resources/application_fee.rb +2 -12
  30. data/lib/stripe/resources/application_fee_refund.rb +1 -1
  31. data/lib/stripe/resources/balance.rb +2 -1
  32. data/lib/stripe/resources/balance_transaction.rb +2 -1
  33. data/lib/stripe/resources/bank_account.rb +3 -2
  34. data/lib/stripe/resources/billing_portal/configuration.rb +14 -0
  35. data/lib/stripe/resources/billing_portal/session.rb +12 -0
  36. data/lib/stripe/resources/bitcoin_receiver.rb +2 -1
  37. data/lib/stripe/resources/bitcoin_transaction.rb +1 -1
  38. data/lib/stripe/resources/capability.rb +1 -1
  39. data/lib/stripe/resources/card.rb +2 -1
  40. data/lib/stripe/resources/charge.rb +8 -69
  41. data/lib/stripe/resources/checkout/session.rb +6 -1
  42. data/lib/stripe/resources/country_spec.rb +2 -1
  43. data/lib/stripe/resources/coupon.rb +2 -1
  44. data/lib/stripe/resources/credit_note.rb +12 -1
  45. data/lib/stripe/resources/credit_note_line_item.rb +7 -0
  46. data/lib/stripe/resources/customer.rb +9 -63
  47. data/lib/stripe/resources/customer_balance_transaction.rb +1 -1
  48. data/lib/stripe/resources/discount.rb +1 -1
  49. data/lib/stripe/resources/dispute.rb +2 -7
  50. data/lib/stripe/resources/ephemeral_key.rb +2 -1
  51. data/lib/stripe/resources/event.rb +2 -1
  52. data/lib/stripe/resources/exchange_rate.rb +2 -1
  53. data/lib/stripe/resources/file.rb +6 -14
  54. data/lib/stripe/resources/file_link.rb +2 -1
  55. data/lib/stripe/resources/identity/verification_report.rb +12 -0
  56. data/lib/stripe/resources/identity/verification_session.rb +35 -0
  57. data/lib/stripe/resources/invoice.rb +8 -2
  58. data/lib/stripe/resources/invoice_item.rb +2 -1
  59. data/lib/stripe/resources/invoice_line_item.rb +1 -1
  60. data/lib/stripe/resources/issuing/authorization.rb +2 -1
  61. data/lib/stripe/resources/issuing/card.rb +2 -1
  62. data/lib/stripe/resources/issuing/card_details.rb +1 -1
  63. data/lib/stripe/resources/issuing/cardholder.rb +2 -1
  64. data/lib/stripe/resources/issuing/dispute.rb +13 -1
  65. data/lib/stripe/resources/issuing/transaction.rb +2 -1
  66. data/lib/stripe/resources/line_item.rb +7 -0
  67. data/lib/stripe/resources/login_link.rb +1 -1
  68. data/lib/stripe/resources/mandate.rb +8 -0
  69. data/lib/stripe/resources/order.rb +2 -9
  70. data/lib/stripe/resources/order_return.rb +2 -1
  71. data/lib/stripe/resources/payment_intent.rb +2 -1
  72. data/lib/stripe/resources/payment_method.rb +2 -1
  73. data/lib/stripe/resources/payout.rb +10 -5
  74. data/lib/stripe/resources/person.rb +1 -1
  75. data/lib/stripe/resources/plan.rb +2 -1
  76. data/lib/stripe/resources/price.rb +12 -0
  77. data/lib/stripe/resources/product.rb +2 -1
  78. data/lib/stripe/resources/promotion_code.rb +12 -0
  79. data/lib/stripe/resources/quote.rb +95 -0
  80. data/lib/stripe/resources/radar/early_fraud_warning.rb +2 -1
  81. data/lib/stripe/resources/radar/value_list.rb +2 -1
  82. data/lib/stripe/resources/radar/value_list_item.rb +2 -1
  83. data/lib/stripe/resources/recipient.rb +2 -5
  84. data/lib/stripe/resources/recipient_transfer.rb +1 -1
  85. data/lib/stripe/resources/refund.rb +2 -1
  86. data/lib/stripe/resources/reporting/report_run.rb +2 -1
  87. data/lib/stripe/resources/reporting/report_type.rb +2 -1
  88. data/lib/stripe/resources/reversal.rb +1 -1
  89. data/lib/stripe/resources/review.rb +2 -1
  90. data/lib/stripe/resources/setup_attempt.rb +10 -0
  91. data/lib/stripe/resources/setup_intent.rb +2 -1
  92. data/lib/stripe/resources/sigma/scheduled_query_run.rb +2 -1
  93. data/lib/stripe/resources/sku.rb +2 -1
  94. data/lib/stripe/resources/source.rb +11 -10
  95. data/lib/stripe/resources/source_transaction.rb +1 -1
  96. data/lib/stripe/resources/subscription.rb +10 -9
  97. data/lib/stripe/resources/subscription_item.rb +8 -2
  98. data/lib/stripe/resources/subscription_schedule.rb +2 -1
  99. data/lib/stripe/resources/tax_code.rb +10 -0
  100. data/lib/stripe/resources/tax_id.rb +1 -1
  101. data/lib/stripe/resources/tax_rate.rb +2 -1
  102. data/lib/stripe/resources/terminal/connection_token.rb +2 -1
  103. data/lib/stripe/resources/terminal/location.rb +2 -1
  104. data/lib/stripe/resources/terminal/reader.rb +2 -1
  105. data/lib/stripe/resources/three_d_secure.rb +2 -1
  106. data/lib/stripe/resources/token.rb +2 -1
  107. data/lib/stripe/resources/topup.rb +2 -1
  108. data/lib/stripe/resources/transfer.rb +2 -6
  109. data/lib/stripe/resources/usage_record.rb +1 -17
  110. data/lib/stripe/resources/usage_record_summary.rb +1 -1
  111. data/lib/stripe/resources/webhook_endpoint.rb +2 -1
  112. data/lib/stripe/stripe_client.rb +608 -242
  113. data/lib/stripe/stripe_configuration.rb +194 -0
  114. data/lib/stripe/stripe_object.rb +30 -25
  115. data/lib/stripe/stripe_response.rb +87 -27
  116. data/lib/stripe/util.rb +37 -18
  117. data/lib/stripe/version.rb +1 -1
  118. data/lib/stripe/webhook.rb +39 -8
  119. data/stripe.gemspec +15 -11
  120. metadata +24 -216
  121. data/.editorconfig +0 -10
  122. data/.gitattributes +0 -4
  123. data/.github/ISSUE_TEMPLATE.md +0 -5
  124. data/.gitignore +0 -8
  125. data/.rubocop.yml +0 -43
  126. data/.rubocop_todo.yml +0 -38
  127. data/.travis.yml +0 -43
  128. data/.vscode/extensions.json +0 -7
  129. data/.vscode/settings.json +0 -8
  130. data/lib/stripe/resources/issuer_fraud_record.rb +0 -9
  131. data/test/api_stub_helpers.rb +0 -1
  132. data/test/openapi/README.md +0 -9
  133. data/test/stripe/account_link_test.rb +0 -18
  134. data/test/stripe/account_test.rb +0 -428
  135. data/test/stripe/alipay_account_test.rb +0 -37
  136. data/test/stripe/api_operations_test.rb +0 -80
  137. data/test/stripe/api_resource_test.rb +0 -621
  138. data/test/stripe/apple_pay_domain_test.rb +0 -46
  139. data/test/stripe/application_fee_refund_test.rb +0 -37
  140. data/test/stripe/application_fee_test.rb +0 -58
  141. data/test/stripe/balance_test.rb +0 -13
  142. data/test/stripe/balance_transaction_test.rb +0 -20
  143. data/test/stripe/bank_account_test.rb +0 -36
  144. data/test/stripe/capability_test.rb +0 -45
  145. data/test/stripe/charge_test.rb +0 -80
  146. data/test/stripe/checkout/session_test.rb +0 -41
  147. data/test/stripe/country_spec_test.rb +0 -20
  148. data/test/stripe/coupon_test.rb +0 -61
  149. data/test/stripe/credit_note_test.rb +0 -61
  150. data/test/stripe/customer_balance_transaction_test.rb +0 -37
  151. data/test/stripe/customer_card_test.rb +0 -42
  152. data/test/stripe/customer_test.rb +0 -269
  153. data/test/stripe/dispute_test.rb +0 -51
  154. data/test/stripe/ephemeral_key_test.rb +0 -93
  155. data/test/stripe/errors_test.rb +0 -20
  156. data/test/stripe/exchange_rate_test.rb +0 -20
  157. data/test/stripe/file_link_test.rb +0 -41
  158. data/test/stripe/file_test.rb +0 -97
  159. data/test/stripe/file_upload_test.rb +0 -79
  160. data/test/stripe/invoice_item_test.rb +0 -66
  161. data/test/stripe/invoice_line_item_test.rb +0 -8
  162. data/test/stripe/invoice_test.rb +0 -213
  163. data/test/stripe/issuer_fraud_record_test.rb +0 -20
  164. data/test/stripe/issuing/authorization_test.rb +0 -72
  165. data/test/stripe/issuing/card_test.rb +0 -62
  166. data/test/stripe/issuing/cardholder_test.rb +0 -53
  167. data/test/stripe/issuing/dispute_test.rb +0 -45
  168. data/test/stripe/issuing/transaction_test.rb +0 -48
  169. data/test/stripe/list_object_test.rb +0 -156
  170. data/test/stripe/login_link_test.rb +0 -37
  171. data/test/stripe/oauth_test.rb +0 -88
  172. data/test/stripe/order_return_test.rb +0 -21
  173. data/test/stripe/order_test.rb +0 -82
  174. data/test/stripe/payment_intent_test.rb +0 -107
  175. data/test/stripe/payment_method_test.rb +0 -84
  176. data/test/stripe/payout_test.rb +0 -57
  177. data/test/stripe/person_test.rb +0 -46
  178. data/test/stripe/plan_test.rb +0 -98
  179. data/test/stripe/product_test.rb +0 -59
  180. data/test/stripe/radar/early_fraud_warning_test.rb +0 -22
  181. data/test/stripe/radar/value_list_item_test.rb +0 -48
  182. data/test/stripe/radar/value_list_test.rb +0 -61
  183. data/test/stripe/recipient_test.rb +0 -62
  184. data/test/stripe/refund_test.rb +0 -39
  185. data/test/stripe/reporting/report_run_test.rb +0 -33
  186. data/test/stripe/reporting/report_type_test.rb +0 -22
  187. data/test/stripe/reversal_test.rb +0 -43
  188. data/test/stripe/review_test.rb +0 -27
  189. data/test/stripe/setup_intent_test.rb +0 -84
  190. data/test/stripe/sigma/scheduled_query_run_test.rb +0 -22
  191. data/test/stripe/sku_test.rb +0 -60
  192. data/test/stripe/source_test.rb +0 -99
  193. data/test/stripe/source_transaction_test.rb +0 -19
  194. data/test/stripe/stripe_client_test.rb +0 -842
  195. data/test/stripe/stripe_object_test.rb +0 -525
  196. data/test/stripe/stripe_response_test.rb +0 -49
  197. data/test/stripe/subscription_item_test.rb +0 -75
  198. data/test/stripe/subscription_schedule_test.rb +0 -82
  199. data/test/stripe/subscription_test.rb +0 -80
  200. data/test/stripe/tax_id_test.rb +0 -31
  201. data/test/stripe/tax_rate_test.rb +0 -43
  202. data/test/stripe/terminal/connection_token_test.rb +0 -16
  203. data/test/stripe/terminal/location_test.rb +0 -68
  204. data/test/stripe/terminal/reader_test.rb +0 -62
  205. data/test/stripe/three_d_secure_test.rb +0 -23
  206. data/test/stripe/topup_test.rb +0 -62
  207. data/test/stripe/transfer_test.rb +0 -88
  208. data/test/stripe/usage_record_summary_test.rb +0 -19
  209. data/test/stripe/usage_record_test.rb +0 -28
  210. data/test/stripe/util_test.rb +0 -402
  211. data/test/stripe/webhook_endpoint_test.rb +0 -59
  212. data/test/stripe/webhook_test.rb +0 -96
  213. data/test/stripe_mock.rb +0 -77
  214. data/test/stripe_test.rb +0 -63
  215. data/test/test_data.rb +0 -61
  216. data/test/test_helper.rb +0 -71
@@ -1,3 +1,4 @@
1
+ # File generated from our OpenAPI spec
1
2
  # frozen_string_literal: true
2
3
 
3
4
  module Stripe
@@ -7,19 +8,19 @@ module Stripe
7
8
  extend Stripe::APIOperations::List
8
9
  include Stripe::APIOperations::Save
9
10
 
10
- OBJECT_NAME = "subscription".freeze
11
+ OBJECT_NAME = "subscription"
11
12
 
12
13
  custom_method :delete_discount, http_verb: :delete, http_path: "discount"
13
14
 
14
- save_nested_resource :source
15
-
16
- def delete_discount
17
- _, opts = request(:delete, discount_url)
18
- initialize_from({ discount: nil }, opts, true)
15
+ def delete_discount(params = {}, opts = {})
16
+ request_stripe_object(
17
+ method: :delete,
18
+ path: resource_url + "/discount",
19
+ params: params,
20
+ opts: opts
21
+ )
19
22
  end
20
23
 
21
- private def discount_url
22
- resource_url + "/discount"
23
- end
24
+ save_nested_resource :source
24
25
  end
25
26
  end
@@ -1,3 +1,4 @@
1
+ # File generated from our OpenAPI spec
1
2
  # frozen_string_literal: true
2
3
 
3
4
  module Stripe
@@ -8,13 +9,18 @@ module Stripe
8
9
  include Stripe::APIOperations::Save
9
10
  extend Stripe::APIOperations::NestedResource
10
11
 
11
- OBJECT_NAME = "subscription_item".freeze
12
+ OBJECT_NAME = "subscription_item"
12
13
 
13
14
  nested_resource_class_methods :usage_record, operations: %i[create]
15
+ nested_resource_class_methods :usage_record_summary,
16
+ operations: %i[list],
17
+ resource_plural: "usage_record_summaries"
14
18
 
15
19
  def usage_record_summaries(params = {}, opts = {})
16
- resp, opts = request(:get, resource_url + "/usage_record_summaries", params, opts)
20
+ resp, opts = execute_resource_request(:get, resource_url + "/usage_record_summaries", params, opts)
17
21
  Util.convert_to_stripe_object(resp.data, opts)
18
22
  end
23
+ extend Gem::Deprecate
24
+ deprecate :usage_record_summaries, :"SubscriptionItem.list_usage_record_summaries", 2020, 1
19
25
  end
20
26
  end
@@ -1,3 +1,4 @@
1
+ # File generated from our OpenAPI spec
1
2
  # frozen_string_literal: true
2
3
 
3
4
  module Stripe
@@ -6,7 +7,7 @@ module Stripe
6
7
  extend Stripe::APIOperations::List
7
8
  include Stripe::APIOperations::Save
8
9
 
9
- OBJECT_NAME = "subscription_schedule".freeze
10
+ OBJECT_NAME = "subscription_schedule"
10
11
 
11
12
  custom_method :cancel, http_verb: :post
12
13
  custom_method :release, http_verb: :post
@@ -0,0 +1,10 @@
1
+ # File generated from our OpenAPI spec
2
+ # frozen_string_literal: true
3
+
4
+ module Stripe
5
+ class TaxCode < APIResource
6
+ extend Stripe::APIOperations::List
7
+
8
+ OBJECT_NAME = "tax_code"
9
+ end
10
+ end
@@ -5,7 +5,7 @@ module Stripe
5
5
  include Stripe::APIOperations::Delete
6
6
  extend Stripe::APIOperations::List
7
7
 
8
- OBJECT_NAME = "tax_id".freeze
8
+ OBJECT_NAME = "tax_id"
9
9
 
10
10
  def resource_url
11
11
  if !respond_to?(:customer) || customer.nil?
@@ -1,3 +1,4 @@
1
+ # File generated from our OpenAPI spec
1
2
  # frozen_string_literal: true
2
3
 
3
4
  module Stripe
@@ -6,6 +7,6 @@ module Stripe
6
7
  extend Stripe::APIOperations::List
7
8
  include Stripe::APIOperations::Save
8
9
 
9
- OBJECT_NAME = "tax_rate".freeze
10
+ OBJECT_NAME = "tax_rate"
10
11
  end
11
12
  end
@@ -1,3 +1,4 @@
1
+ # File generated from our OpenAPI spec
1
2
  # frozen_string_literal: true
2
3
 
3
4
  module Stripe
@@ -5,7 +6,7 @@ module Stripe
5
6
  class ConnectionToken < APIResource
6
7
  extend Stripe::APIOperations::Create
7
8
 
8
- OBJECT_NAME = "terminal.connection_token".freeze
9
+ OBJECT_NAME = "terminal.connection_token"
9
10
  end
10
11
  end
11
12
  end
@@ -1,3 +1,4 @@
1
+ # File generated from our OpenAPI spec
1
2
  # frozen_string_literal: true
2
3
 
3
4
  module Stripe
@@ -8,7 +9,7 @@ module Stripe
8
9
  extend Stripe::APIOperations::List
9
10
  include Stripe::APIOperations::Save
10
11
 
11
- OBJECT_NAME = "terminal.location".freeze
12
+ OBJECT_NAME = "terminal.location"
12
13
  end
13
14
  end
14
15
  end
@@ -1,3 +1,4 @@
1
+ # File generated from our OpenAPI spec
1
2
  # frozen_string_literal: true
2
3
 
3
4
  module Stripe
@@ -8,7 +9,7 @@ module Stripe
8
9
  extend Stripe::APIOperations::List
9
10
  include Stripe::APIOperations::Save
10
11
 
11
- OBJECT_NAME = "terminal.reader".freeze
12
+ OBJECT_NAME = "terminal.reader"
12
13
  end
13
14
  end
14
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
@@ -1,3 +1,4 @@
1
+ # File generated from our OpenAPI spec
1
2
  # frozen_string_literal: true
2
3
 
3
4
  module Stripe
@@ -6,7 +7,7 @@ module Stripe
6
7
  extend Stripe::APIOperations::List
7
8
  include Stripe::APIOperations::Save
8
9
 
9
- OBJECT_NAME = "topup".freeze
10
+ OBJECT_NAME = "topup"
10
11
 
11
12
  custom_method :cancel, http_verb: :post
12
13
 
@@ -1,3 +1,4 @@
1
+ # File generated from our OpenAPI spec
1
2
  # frozen_string_literal: true
2
3
 
3
4
  module Stripe
@@ -7,7 +8,7 @@ module Stripe
7
8
  include Stripe::APIOperations::Save
8
9
  extend Stripe::APIOperations::NestedResource
9
10
 
10
- OBJECT_NAME = "transfer".freeze
11
+ OBJECT_NAME = "transfer"
11
12
 
12
13
  custom_method :cancel, http_verb: :post
13
14
 
@@ -22,10 +23,5 @@ module Stripe
22
23
  opts: opts
23
24
  )
24
25
  end
25
-
26
- def cancel_url
27
- resource_url + "/cancel"
28
- end
29
- deprecate :cancel_url, :none, 2019, 11
30
26
  end
31
27
  end
@@ -2,22 +2,6 @@
2
2
 
3
3
  module Stripe
4
4
  class UsageRecord < APIResource
5
- OBJECT_NAME = "usage_record".freeze
6
-
7
- def self.create(params = {}, opts = {})
8
- unless params.key?(:subscription_item)
9
- raise ArgumentError, "Params must have a subscription_item key"
10
- end
11
- req_params = params.clone.delete_if do |key, _value|
12
- key == :subscription_item
13
- end
14
- resp, opts = request(
15
- :post,
16
- "/v1/subscription_items/#{params[:subscription_item]}/usage_records",
17
- req_params,
18
- opts
19
- )
20
- Util.convert_to_stripe_object(resp.data, opts)
21
- end
5
+ OBJECT_NAME = "usage_record"
22
6
  end
23
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,3 +1,4 @@
1
+ # File generated from our OpenAPI spec
1
2
  # frozen_string_literal: true
2
3
 
3
4
  module Stripe
@@ -7,6 +8,6 @@ module Stripe
7
8
  extend Stripe::APIOperations::List
8
9
  include Stripe::APIOperations::Save
9
10
 
10
- OBJECT_NAME = "webhook_endpoint".freeze
11
+ OBJECT_NAME = "webhook_endpoint"
11
12
  end
12
13
  end
@@ -1,101 +1,172 @@
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
9
-
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
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 = Set.new
13
+ @thread_contexts_with_connection_managers_mutex = Mutex.new
14
+ @last_connection_manager_gc = Util.monotonic_time
15
+
16
+ # Initializes a new StripeClient
17
+ def initialize(config_arg = {})
14
18
  @system_profiler = SystemProfiler.new
15
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
16
37
  end
17
38
 
39
+ attr_reader :config
40
+ attr_reader :options
41
+
42
+ # Gets a currently active `StripeClient`. Set for the current thread when
43
+ # `StripeClient#request` is being run so that API operations being executed
44
+ # inside of that block can find the currently active client. It's reset to
45
+ # the original value (hopefully `nil`) after the block ends.
46
+ #
47
+ # For internal use only. Does not provide a stable API and may be broken
48
+ # with future non-major changes.
18
49
  def self.active_client
19
- Thread.current[:stripe_client] || default_client
50
+ current_thread_context.active_client || default_client
20
51
  end
21
52
 
22
- def self.default_client
23
- Thread.current[:stripe_client_default_client] ||=
24
- StripeClient.new(default_conn)
25
- end
26
-
27
- # A default Faraday connection to be used when one isn't configured. This
28
- # object should never be mutated, and instead instantiating your own
29
- # connection and wrapping it in a StripeClient object should be preferred.
30
- def self.default_conn
31
- # We're going to keep connections around so that we can take advantage
32
- # of connection re-use, so make sure that we have a separate connection
33
- # object per thread.
34
- Thread.current[:stripe_client_default_conn] ||= begin
35
- conn = Faraday.new do |builder|
36
- builder.use Faraday::Request::Multipart
37
- builder.use Faraday::Request::UrlEncoded
38
- builder.use Faraday::Response::RaiseError
39
-
40
- # Net::HTTP::Persistent doesn't seem to do well on Windows or JRuby,
41
- # so fall back to default there.
42
- if Gem.win_platform? || RUBY_PLATFORM == "java"
43
- builder.adapter :net_http
44
- else
45
- builder.adapter :net_http_persistent
53
+ # Finishes any active connections by closing their TCP connection and
54
+ # clears them from internal tracking in all connection managers across all
55
+ # threads.
56
+ #
57
+ # If passed a `config` object, only clear connection managers for that
58
+ # particular configuration.
59
+ #
60
+ # For internal use only. Does not provide a stable API and may be broken
61
+ # with future non-major changes.
62
+ def self.clear_all_connection_managers(config: nil)
63
+ # Just a quick path for when configuration is being set for the first
64
+ # time before any connections have been opened. There is technically some
65
+ # potential for thread raciness here, but not in a practical sense.
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
82
+
83
+ if thread_context.default_connection_managers.empty?
84
+ pruned_contexts << thread_context
46
85
  end
47
86
  end
48
87
 
49
- conn.proxy = Stripe.proxy if Stripe.proxy
88
+ @thread_contexts_with_connection_managers.subtract(pruned_contexts)
89
+ end
90
+ end
50
91
 
51
- if Stripe.verify_ssl_certs
52
- conn.ssl.verify = true
53
- conn.ssl.cert_store = Stripe.ca_store
54
- else
55
- conn.ssl.verify = false
56
-
57
- unless @verify_ssl_warned
58
- @verify_ssl_warned = true
59
- warn("WARNING: Running without SSL cert verification. " \
60
- "You should never do this in production. " \
61
- "Execute `Stripe.verify_ssl_certs = true` to enable " \
62
- "verification.")
63
- end
92
+ # A default client for the current thread.
93
+ def self.default_client
94
+ current_thread_context.default_client ||= StripeClient.new(Stripe.config)
95
+ end
96
+
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)
102
+
103
+ @thread_contexts_with_connection_managers_mutex.synchronize do
104
+ maybe_gc_connection_managers
105
+ @thread_contexts_with_connection_managers << current_thread_context
64
106
  end
65
107
 
66
- conn
108
+ connection_manager
67
109
  end
68
110
  end
69
111
 
70
112
  # Checks if an error is a problem that we should retry on. This includes
71
113
  # both socket errors that may represent an intermittent problem and some
72
114
  # special HTTP statuses.
73
- def self.should_retry?(error, num_retries)
74
- return false if num_retries >= Stripe.max_network_retries
75
-
76
- # Retry on timeout-related problems (either on open or read).
77
- return true if error.is_a?(Faraday::TimeoutError)
115
+ def self.should_retry?(error,
116
+ method:, num_retries:, config: Stripe.config)
117
+ return false if num_retries >= config.max_network_retries
78
118
 
79
- # Destination refused the connection, the connection was reset, or a
80
- # variety of other connection failures. This could occur from a single
81
- # saturated server, so retry in case it's intermittent.
82
- return true if error.is_a?(Faraday::ConnectionFailed)
83
-
84
- if error.is_a?(Faraday::ClientError) && error.response
85
- # 409 conflict
86
- return true if error.response[:status] == 409
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"
135
+
136
+ # 409 Conflict
137
+ return true if error.http_status == 409
138
+
139
+ # 429 Too Many Requests
140
+ #
141
+ # There are a few different problems that can lead to a 429. The most
142
+ # common is rate limiting, on which we *don't* want to retry because
143
+ # that'd likely contribute to more contention problems. However, some
144
+ # 429s are lock timeouts, which is when a request conflicted with
145
+ # another request or an internal process on some particular object.
146
+ # These 429s are safe to retry.
147
+ return true if error.http_status == 429 && error.code == "lock_timeout"
148
+
149
+ # 500 Internal Server Error
150
+ #
151
+ # We only bother retrying these for non-POST requests. POSTs end up
152
+ # being cached by the idempotency layer so there's no purpose in
153
+ # retrying them.
154
+ return true if error.http_status == 500 && method != :post
155
+
156
+ # 503 Service Unavailable
157
+ error.http_status == 503
158
+ else
159
+ false
87
160
  end
88
-
89
- false
90
161
  end
91
162
 
92
- def self.sleep_time(num_retries)
163
+ def self.sleep_time(num_retries, config: Stripe.config)
93
164
  # Apply exponential backoff with initial_network_retry_delay on the
94
165
  # number of num_retries so far as inputs. Do not allow the number to
95
166
  # exceed max_network_retry_delay.
96
167
  sleep_seconds = [
97
- Stripe.initial_network_retry_delay * (2**(num_retries - 1)),
98
- Stripe.max_network_retry_delay,
168
+ config.initial_network_retry_delay * (2**(num_retries - 1)),
169
+ config.max_network_retry_delay,
99
170
  ].min
100
171
 
101
172
  # Apply some jitter by randomizing the value in the range of
@@ -103,10 +174,17 @@ module Stripe
103
174
  sleep_seconds *= (0.5 * (1 + rand))
104
175
 
105
176
  # But never sleep less than the base sleep seconds.
106
- sleep_seconds = [Stripe.initial_network_retry_delay, sleep_seconds].max
177
+ [config.initial_network_retry_delay, sleep_seconds].max
178
+ end
107
179
 
108
- 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
109
185
  end
186
+ extend Gem::Deprecate
187
+ deprecate :connection_manager, :none, 2020, 9
110
188
 
111
189
  # Executes the API call within the given block. Usage looks like:
112
190
  #
@@ -114,131 +192,323 @@ module Stripe
114
192
  # charge, resp = client.request { Charge.create }
115
193
  #
116
194
  def request
117
- @last_response = nil
118
- old_stripe_client = Thread.current[:stripe_client]
119
- Thread.current[:stripe_client] = self
195
+ old_stripe_client = self.class.current_thread_context.active_client
196
+ self.class.current_thread_context.active_client = self
197
+
198
+ if self.class.current_thread_context.last_responses&.key?(object_id)
199
+ raise "calls to StripeClient#request cannot be nested within a thread"
200
+ end
201
+
202
+ self.class.current_thread_context.last_responses ||= {}
203
+ self.class.current_thread_context.last_responses[object_id] = nil
120
204
 
121
205
  begin
122
206
  res = yield
123
- [res, @last_response]
207
+ [res, self.class.current_thread_context.last_responses[object_id]]
124
208
  ensure
125
- Thread.current[:stripe_client] = old_stripe_client
209
+ self.class.current_thread_context.active_client = old_stripe_client
210
+ self.class.current_thread_context.last_responses.delete(object_id)
126
211
  end
127
212
  end
128
213
 
129
214
  def execute_request(method, path,
130
215
  api_base: nil, api_key: nil, headers: {}, params: {})
131
- api_base ||= Stripe.api_base
132
- api_key ||= Stripe.api_key
216
+ http_resp, api_key = execute_request_internal(
217
+ method, path, api_base, api_key, headers, params
218
+ )
219
+
220
+ begin
221
+ resp = StripeResponse.from_net_http(http_resp)
222
+ rescue JSON::ParserError
223
+ raise general_api_error(http_resp.code.to_i, http_resp.body)
224
+ end
225
+
226
+ # If being called from `StripeClient#request`, put the last response in
227
+ # thread-local memory so that it can be returned to the user. Don't store
228
+ # anything otherwise so that we don't leak memory.
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"
252
+ end
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
+
263
+ [resp, api_key]
264
+ end
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
+
276
+ #
277
+ # private
278
+ #
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
+
288
+ ERROR_MESSAGE_CONNECTION =
289
+ "Unexpected error communicating when trying to connect to " \
290
+ "Stripe (%s). You may be seeing this message because your DNS is not " \
291
+ "working or you don't have an internet connection. To check, try " \
292
+ "running `host stripe.com` from the command line."
293
+ ERROR_MESSAGE_SSL =
294
+ "Could not establish a secure connection to Stripe (%s), you " \
295
+ "may need to upgrade your OpenSSL version. To check, try running " \
296
+ "`openssl s_client -connect api.stripe.com:443` from the command " \
297
+ "line."
298
+
299
+ # Common error suffix sared by both connect and read timeout messages.
300
+ ERROR_MESSAGE_TIMEOUT_SUFFIX =
301
+ "Please check your internet connection and try again. " \
302
+ "If this problem persists, you should check Stripe's service " \
303
+ "status at https://status.stripe.com, or let us know at " \
304
+ "support@stripe.com."
305
+
306
+ ERROR_MESSAGE_TIMEOUT_CONNECT = (
307
+ "Timed out connecting to Stripe (%s). " +
308
+ ERROR_MESSAGE_TIMEOUT_SUFFIX
309
+ ).freeze
310
+
311
+ ERROR_MESSAGE_TIMEOUT_READ = (
312
+ "Timed out communicating with Stripe (%s). " +
313
+ ERROR_MESSAGE_TIMEOUT_SUFFIX
314
+ ).freeze
315
+
316
+ # Maps types of exceptions that we're likely to see during a network
317
+ # request to more user-friendly messages that we put in front of people.
318
+ # The original error message is also appended onto the final exception for
319
+ # full transparency.
320
+ NETWORK_ERROR_MESSAGES_MAP = {
321
+ EOFError => ERROR_MESSAGE_CONNECTION,
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,
326
+ SocketError => ERROR_MESSAGE_CONNECTION,
327
+
328
+ Net::OpenTimeout => ERROR_MESSAGE_TIMEOUT_CONNECT,
329
+ Net::ReadTimeout => ERROR_MESSAGE_TIMEOUT_READ,
330
+
331
+ OpenSSL::SSL::SSLError => ERROR_MESSAGE_SSL,
332
+ }.freeze
333
+ private_constant :NETWORK_ERROR_MESSAGES_MAP
334
+
335
+ # A record representing any data that `StripeClient` puts into
336
+ # `Thread.current`. Making it a class likes this gives us a little extra
337
+ # type safety and lets us document what each field does.
338
+ #
339
+ # For internal use only. Does not provide a stable API and may be broken
340
+ # with future non-major changes.
341
+ class ThreadContext
342
+ # A `StripeClient` that's been flagged as currently active within a
343
+ # thread by `StripeClient#request`. A client stays active until the
344
+ # completion of the request block.
345
+ attr_accessor :active_client
346
+
347
+ # A default `StripeClient` object for the thread. Used in all cases where
348
+ # the user hasn't specified their own.
349
+ attr_accessor :default_client
350
+
351
+ # A temporary map of object IDs to responses from last executed API
352
+ # calls. Used to return a responses from calls to `StripeClient#request`.
353
+ #
354
+ # Stored in the thread data to make the use of a single `StripeClient`
355
+ # object safe across multiple threads. Stored as a map so that multiple
356
+ # `StripeClient` objects can run concurrently on the same thread.
357
+ #
358
+ # Responses are only left in as long as they're needed, which means
359
+ # they're removed as soon as a call leaves `StripeClient#request`, and
360
+ # because that's wrapped in an `ensure` block, they should never leave
361
+ # garbage in `Thread.current`.
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
374
+ end
375
+
376
+ # Access data stored for `StripeClient` within the thread's current
377
+ # context. Returns `ThreadContext`.
378
+ #
379
+ # For internal use only. Does not provide a stable API and may be broken
380
+ # with future non-major changes.
381
+ def self.current_thread_context
382
+ Thread.current[:stripe_client__internal_use_only] ||= ThreadContext.new
383
+ end
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
133
443
  params = Util.objects_to_ids(params)
134
444
 
135
445
  check_api_key!(api_key)
136
446
 
137
- body = nil
447
+ body_params = nil
138
448
  query_params = nil
139
- case method.to_s.downcase.to_sym
449
+ case method
140
450
  when :get, :head, :delete
141
451
  query_params = params
142
452
  else
143
- body = params
453
+ body_params = params
144
454
  end
145
455
 
146
- # This works around an edge case where we end up with both query
147
- # parameters in `query_params` and query parameters that are appended
148
- # onto the end of the given path. In this case, Faraday will silently
149
- # discard the URL's parameters which may break a request.
150
- #
151
- # Here we decode any parameters that were added onto the end of a path
152
- # and add them to `query_params` so that all parameters end up in one
153
- # place and all of them are correctly included in the final request.
154
- u = URI.parse(path)
155
- unless u.query.nil?
156
- query_params ||= {}
157
- query_params = Hash[URI.decode_www_form(u.query)].merge(query_params)
158
-
159
- # Reset the path minus any query parameters that were specified.
160
- path = u.path
161
- end
456
+ query_params, path = merge_query_params(query_params, path)
162
457
 
163
458
  headers = request_headers(api_key, method)
164
459
  .update(Util.normalize_headers(headers))
165
- params_encoder = FaradayStripeEncoder.new
166
460
  url = api_url(path, api_base)
167
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
+
168
472
  # stores information on the request we're about to make so that we don't
169
473
  # have to pass as many parameters around for logging.
170
474
  context = RequestLogContext.new
171
475
  context.account = headers["Stripe-Account"]
172
476
  context.api_key = api_key
173
477
  context.api_version = headers["Stripe-Version"]
174
- context.body = body ? params_encoder.encode(body) : nil
478
+ context.body = body_log
175
479
  context.idempotency_key = headers["Idempotency-Key"]
176
480
  context.method = method
177
481
  context.path = path
178
- context.query_params = if query_params
179
- params_encoder.encode(query_params)
180
- end
181
-
182
- # note that both request body and query params will be passed through
183
- # `FaradayStripeEncoder`
184
- http_resp = execute_request_with_rescues(api_base, context) do
185
- conn.run_request(method, url, body, headers) do |req|
186
- req.options.open_timeout = Stripe.open_timeout
187
- req.options.params_encoder = params_encoder
188
- req.options.timeout = Stripe.read_timeout
189
- req.params = query_params unless query_params.nil?
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
190
495
  end
191
- end
192
-
193
- begin
194
- resp = StripeResponse.from_faraday_response(http_resp)
195
- rescue JSON::ParserError
196
- raise general_api_error(http_resp.status, http_resp.body)
197
- end
198
-
199
- # Allows StripeClient#request to return a response object to a caller.
200
- @last_response = resp
201
- [resp, api_key]
202
- end
203
496
 
204
- # Used to workaround buggy behavior in Faraday: the library will try to
205
- # reshape anything that we pass to `req.params` with one of its default
206
- # encoders. I don't think this process is supposed to be lossy, but it is
207
- # -- in particular when we send our integer-indexed maps (i.e. arrays),
208
- # Faraday ends up stripping out the integer indexes.
209
- #
210
- # We work around the problem by implementing our own simplified encoder and
211
- # telling Faraday to use that.
212
- #
213
- # The class also performs simple caching so that we don't have to encode
214
- # parameters twice for every request (once to build the request and once
215
- # for logging).
216
- #
217
- # When initialized with `multipart: true`, the encoder just inspects the
218
- # hash instead to get a decent representation for logging. In the case of a
219
- # multipart request, Faraday won't use the result of this encoder.
220
- class FaradayStripeEncoder
221
- def initialize
222
- @cache = {}
223
- end
224
-
225
- # This is quite subtle, but for a `multipart/form-data` request Faraday
226
- # will throw away the result of this encoder and build its body.
227
- def encode(hash)
228
- @cache.fetch(hash) do |k|
229
- @cache[k] = Util.encode_parameters(hash)
230
- end
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)
231
505
  end
232
506
 
233
- # We should never need to do this so it's not implemented.
234
- def decode(_str)
235
- raise NotImplementedError,
236
- "#{self.class.name} does not implement #decode"
237
- end
507
+ [http_resp, api_key]
238
508
  end
239
509
 
240
510
  private def api_url(url = "", api_base = nil)
241
- (api_base || Stripe.api_base) + url
511
+ (api_base || config.api_base) + url
242
512
  end
243
513
 
244
514
  private def check_api_key!(api_key)
@@ -258,17 +528,69 @@ module Stripe
258
528
  "email support@stripe.com if you have any questions.)"
259
529
  end
260
530
 
261
- private def execute_request_with_rescues(api_base, context)
531
+ # Encodes a set of body parameters using multipart if `Content-Type` is set
532
+ # for that, or standard form-encoding otherwise. Returns the encoded body
533
+ # and a version of the encoded body that's safe to be logged.
534
+ private def encode_body(body_params, headers)
535
+ body = nil
536
+ flattened_params = Util.flatten_params(body_params)
537
+
538
+ if headers["Content-Type"] == MultipartEncoder::MULTIPART_FORM_DATA
539
+ body, content_type = MultipartEncoder.encode(flattened_params)
540
+
541
+ # Set a new content type that also includes the multipart boundary.
542
+ # See `MultipartEncoder` for details.
543
+ headers["Content-Type"] = content_type
544
+
545
+ # `#to_s` any complex objects like files and the like to build output
546
+ # that's more condusive to logging.
547
+ flattened_params =
548
+ flattened_params.map { |k, v| [k, v.is_a?(String) ? v : v.to_s] }.to_h
549
+
550
+ else
551
+ body = Util.encode_parameters(body_params)
552
+ end
553
+
554
+ # We don't use `Util.encode_parameters` partly as an optimization (to not
555
+ # redo work we've already done), and partly because the encoded forms of
556
+ # certain characters introduce a lot of visual noise and it's nice to
557
+ # have a clearer format for logs.
558
+ body_log = flattened_params.map { |k, v| "#{k}=#{v}" }.join("&")
559
+
560
+ [body, body_log]
561
+ end
562
+
563
+ private def should_handle_as_error(http_status)
564
+ http_status >= 400
565
+ end
566
+
567
+ private def execute_request_with_rescues(method, api_base, context)
262
568
  num_retries = 0
569
+
263
570
  begin
264
- request_start = Time.now
571
+ request_start = nil
572
+ user_data = nil
573
+
265
574
  log_request(context, num_retries)
575
+ user_data = notify_request_begin(context)
576
+
577
+ request_start = Util.monotonic_time
266
578
  resp = yield
267
- context = context.dup_from_response(resp)
268
- log_response(context, request_start, resp.status, resp.body)
579
+ request_duration = Util.monotonic_time - request_start
269
580
 
270
- if Stripe.enable_telemetry? && context.request_id
271
- request_duration_ms = ((Time.now - request_start) * 1000).to_int
581
+ http_status = resp.code.to_i
582
+ context = context.dup_from_response_headers(resp)
583
+
584
+ if should_handle_as_error(http_status)
585
+ handle_error_response(resp, context)
586
+ end
587
+
588
+ log_response(context, request_start, http_status, resp.body)
589
+ notify_request_end(context, request_duration, http_status,
590
+ num_retries, user_data)
591
+
592
+ if config.enable_telemetry? && context.request_id
593
+ request_duration_ms = (request_duration * 1000).to_i
272
594
  @last_request_metrics =
273
595
  StripeRequestMetrics.new(context.request_id, request_duration_ms)
274
596
  end
@@ -280,28 +602,34 @@ module Stripe
280
602
  # If we modify context we copy it into a new variable so as not to
281
603
  # taint the original on a retry.
282
604
  error_context = context
605
+ http_status = nil
606
+ request_duration = Util.monotonic_time - request_start if request_start
283
607
 
284
- if e.respond_to?(:response) && e.response
285
- error_context = context.dup_from_response(e.response)
608
+ if e.is_a?(Stripe::StripeError)
609
+ error_context = context.dup_from_response_headers(e.http_headers)
610
+ http_status = resp.code.to_i
286
611
  log_response(error_context, request_start,
287
- e.response[:status], e.response[:body])
612
+ e.http_status, e.http_body)
288
613
  else
289
614
  log_response_error(error_context, request_start, e)
290
615
  end
616
+ notify_request_end(context, request_duration, http_status, num_retries,
617
+ user_data)
291
618
 
292
- if self.class.should_retry?(e, num_retries)
619
+ if self.class.should_retry?(e,
620
+ method: method,
621
+ num_retries: num_retries,
622
+ config: config)
293
623
  num_retries += 1
294
- sleep self.class.sleep_time(num_retries)
624
+ sleep self.class.sleep_time(num_retries, config: config)
295
625
  retry
296
626
  end
297
627
 
298
628
  case e
299
- when Faraday::ClientError
300
- if e.response
301
- handle_error_response(e.response, error_context)
302
- else
303
- handle_network_error(e, error_context, num_retries, api_base)
304
- end
629
+ when Stripe::StripeError
630
+ raise
631
+ when *NETWORK_ERROR_MESSAGES_MAP.keys
632
+ handle_network_error(e, error_context, num_retries, api_base)
305
633
 
306
634
  # Only handle errors when we know we can do so, and re-raise otherwise.
307
635
  # This should be pretty infrequent.
@@ -313,6 +641,41 @@ module Stripe
313
641
  resp
314
642
  end
315
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
+ user_data: user_data || {}
671
+ )
672
+ Stripe::Instrumentation.notify(:request_end, event)
673
+
674
+ # The name before `request_begin` was also added. Provided for backwards
675
+ # compatibility.
676
+ Stripe::Instrumentation.notify(:request, event)
677
+ end
678
+
316
679
  private def general_api_error(status, body)
317
680
  APIError.new("Invalid response object from API: #{body.inspect} " \
318
681
  "(HTTP response code was #{status})",
@@ -332,12 +695,12 @@ module Stripe
332
695
 
333
696
  private def handle_error_response(http_resp, context)
334
697
  begin
335
- resp = StripeResponse.from_faraday_hash(http_resp)
698
+ resp = StripeResponse.from_net_http(http_resp)
336
699
  error_data = resp.data[:error]
337
700
 
338
701
  raise StripeError, "Indeterminate error" unless error_data
339
702
  rescue JSON::ParserError, StripeError
340
- raise general_api_error(http_resp[:status], http_resp[:body])
703
+ raise general_api_error(http_resp.code.to_i, http_resp.body)
341
704
  end
342
705
 
343
706
  error = if error_data.is_a?(String)
@@ -350,6 +713,28 @@ module Stripe
350
713
  raise(error)
351
714
  end
352
715
 
716
+ # Works around an edge case where we end up with both query parameters from
717
+ # parameteers and query parameters that were appended onto the end of the
718
+ # given path.
719
+ #
720
+ # Decode any parameters that were added onto the end of a path and add them
721
+ # to a unified query parameter hash so that all parameters end up in one
722
+ # place and all of them are correctly included in the final request.
723
+ private def merge_query_params(query_params, path)
724
+ u = URI.parse(path)
725
+
726
+ # Return original results if there was nothing to be found.
727
+ return query_params, path if u.query.nil?
728
+
729
+ query_params ||= {}
730
+ query_params = Hash[URI.decode_www_form(u.query)].merge(query_params)
731
+
732
+ # Reset the path minus any query parameters that were specified.
733
+ path = u.path
734
+
735
+ [query_params, path]
736
+ end
737
+
353
738
  private def specific_api_error(resp, error_data, context)
354
739
  Util.log_error("Stripe API error",
355
740
  status: resp.http_status,
@@ -358,7 +743,8 @@ module Stripe
358
743
  error_param: error_data[:param],
359
744
  error_type: error_data[:type],
360
745
  idempotency_key: context.idempotency_key,
361
- request_id: context.request_id)
746
+ request_id: context.request_id,
747
+ config: config)
362
748
 
363
749
  # The standard set of arguments that can be used to initialize most of
364
750
  # the exceptions.
@@ -374,29 +760,26 @@ module Stripe
374
760
  when 400, 404
375
761
  case error_data[:type]
376
762
  when "idempotency_error"
377
- IdempotencyError.new(error_data[:message], opts)
763
+ IdempotencyError.new(error_data[:message], **opts)
378
764
  else
379
765
  InvalidRequestError.new(
380
766
  error_data[:message], error_data[:param],
381
- opts
767
+ **opts
382
768
  )
383
769
  end
384
770
  when 401
385
- AuthenticationError.new(error_data[:message], opts)
771
+ AuthenticationError.new(error_data[:message], **opts)
386
772
  when 402
387
- # TODO: modify CardError constructor to make code a keyword argument
388
- # so we don't have to delete it from opts
389
- opts.delete(:code)
390
773
  CardError.new(
391
- error_data[:message], error_data[:param], error_data[:code],
392
- opts
774
+ error_data[:message], error_data[:param],
775
+ **opts
393
776
  )
394
777
  when 403
395
- PermissionError.new(error_data[:message], opts)
778
+ PermissionError.new(error_data[:message], **opts)
396
779
  when 429
397
- RateLimitError.new(error_data[:message], opts)
780
+ RateLimitError.new(error_data[:message], **opts)
398
781
  else
399
- APIError.new(error_data[:message], opts)
782
+ APIError.new(error_data[:message], **opts)
400
783
  end
401
784
  end
402
785
 
@@ -410,30 +793,31 @@ module Stripe
410
793
  error_code: error_code,
411
794
  error_description: description,
412
795
  idempotency_key: context.idempotency_key,
413
- request_id: context.request_id)
796
+ request_id: context.request_id,
797
+ config: config)
414
798
 
415
- args = [error_code, description, {
799
+ args = {
416
800
  http_status: resp.http_status, http_body: resp.http_body,
417
801
  json_body: resp.data, http_headers: resp.http_headers,
418
- },]
802
+ }
419
803
 
420
804
  case error_code
421
805
  when "invalid_client"
422
- OAuth::InvalidClientError.new(*args)
806
+ OAuth::InvalidClientError.new(error_code, description, **args)
423
807
  when "invalid_grant"
424
- OAuth::InvalidGrantError.new(*args)
808
+ OAuth::InvalidGrantError.new(error_code, description, **args)
425
809
  when "invalid_request"
426
- OAuth::InvalidRequestError.new(*args)
810
+ OAuth::InvalidRequestError.new(error_code, description, **args)
427
811
  when "invalid_scope"
428
- OAuth::InvalidScopeError.new(*args)
812
+ OAuth::InvalidScopeError.new(error_code, description, **args)
429
813
  when "unsupported_grant_type"
430
- OAuth::UnsupportedGrantTypeError.new(*args)
814
+ OAuth::UnsupportedGrantTypeError.new(error_code, description, **args)
431
815
  when "unsupported_response_type"
432
- OAuth::UnsupportedResponseTypeError.new(*args)
816
+ OAuth::UnsupportedResponseTypeError.new(error_code, description, **args)
433
817
  else
434
818
  # We'd prefer that all errors are typed, but we create a generic
435
819
  # OAuthError in case we run into a code that we don't recognize.
436
- OAuth::OAuthError.new(*args)
820
+ OAuth::OAuthError.new(error_code, description, **args)
437
821
  end
438
822
  end
439
823
 
@@ -442,35 +826,21 @@ module Stripe
442
826
  Util.log_error("Stripe network error",
443
827
  error_message: error.message,
444
828
  idempotency_key: context.idempotency_key,
445
- request_id: context.request_id)
446
-
447
- case error
448
- when Faraday::ConnectionFailed
449
- message = "Unexpected error communicating when trying to connect to " \
450
- "Stripe. You may be seeing this message because your DNS is not " \
451
- "working. To check, try running `host stripe.com` from the " \
452
- "command line."
453
-
454
- when Faraday::SSLError
455
- message = "Could not establish a secure connection to Stripe, you " \
456
- "may need to upgrade your OpenSSL version. To check, try running " \
457
- "`openssl s_client -connect api.stripe.com:443` from the command " \
458
- "line."
459
-
460
- when Faraday::TimeoutError
461
- api_base ||= Stripe.api_base
462
- message = "Could not connect to Stripe (#{api_base}). " \
463
- "Please check your internet connection and try again. " \
464
- "If this problem persists, you should check Stripe's service " \
465
- "status at https://status.stripe.com, or let us know at " \
466
- "support@stripe.com."
829
+ request_id: context.request_id,
830
+ config: config)
467
831
 
468
- else
469
- message = "Unexpected error communicating with Stripe. " \
470
- "If this problem persists, let us know at support@stripe.com."
832
+ errors, message = NETWORK_ERROR_MESSAGES_MAP.detect do |(e, _)|
833
+ error.is_a?(e)
834
+ end
471
835
 
836
+ if errors.nil?
837
+ message = "Unexpected error #{error.class.name} communicating " \
838
+ "with Stripe. Please let us know at support@stripe.com."
472
839
  end
473
840
 
841
+ api_base ||= config.api_base
842
+ message = message % api_base
843
+
474
844
  message += " Request was retried #{num_retries} times." if num_retries > 0
475
845
 
476
846
  raise APIConnectionError,
@@ -489,7 +859,7 @@ module Stripe
489
859
  "Content-Type" => "application/x-www-form-urlencoded",
490
860
  }
491
861
 
492
- if Stripe.enable_telemetry? && !@last_request_metrics.nil?
862
+ if config.enable_telemetry? && !@last_request_metrics.nil?
493
863
  headers["X-Stripe-Client-Telemetry"] = JSON.generate(
494
864
  last_request_metrics: @last_request_metrics.payload
495
865
  )
@@ -497,12 +867,12 @@ module Stripe
497
867
 
498
868
  # It is only safe to retry network failures on post and delete
499
869
  # requests if we add an Idempotency-Key header
500
- if %i[post delete].include?(method) && Stripe.max_network_retries > 0
870
+ if %i[post delete].include?(method) && config.max_network_retries > 0
501
871
  headers["Idempotency-Key"] ||= SecureRandom.uuid
502
872
  end
503
873
 
504
- headers["Stripe-Version"] = Stripe.api_version if Stripe.api_version
505
- headers["Stripe-Account"] = Stripe.stripe_account if Stripe.stripe_account
874
+ headers["Stripe-Version"] = config.api_version if config.api_version
875
+ headers["Stripe-Account"] = config.stripe_account if config.stripe_account
506
876
 
507
877
  user_agent = @system_profiler.user_agent
508
878
  begin
@@ -526,27 +896,31 @@ module Stripe
526
896
  idempotency_key: context.idempotency_key,
527
897
  method: context.method,
528
898
  num_retries: num_retries,
529
- path: context.path)
899
+ path: context.path,
900
+ config: config)
530
901
  Util.log_debug("Request details",
531
902
  body: context.body,
532
903
  idempotency_key: context.idempotency_key,
533
- query_params: context.query_params)
904
+ query: context.query,
905
+ config: config)
534
906
  end
535
907
 
536
908
  private def log_response(context, request_start, status, body)
537
909
  Util.log_info("Response from Stripe API",
538
910
  account: context.account,
539
911
  api_version: context.api_version,
540
- elapsed: Time.now - request_start,
912
+ elapsed: Util.monotonic_time - request_start,
541
913
  idempotency_key: context.idempotency_key,
542
914
  method: context.method,
543
915
  path: context.path,
544
916
  request_id: context.request_id,
545
- status: status)
917
+ status: status,
918
+ config: config)
546
919
  Util.log_debug("Response details",
547
920
  body: body,
548
921
  idempotency_key: context.idempotency_key,
549
- request_id: context.request_id)
922
+ request_id: context.request_id,
923
+ config: config)
550
924
 
551
925
  return unless context.request_id
552
926
 
@@ -554,16 +928,19 @@ module Stripe
554
928
  idempotency_key: context.idempotency_key,
555
929
  request_id: context.request_id,
556
930
  url: Util.request_id_dashboard_url(context.request_id,
557
- context.api_key))
931
+ context.api_key),
932
+ config: config)
558
933
  end
559
934
 
560
935
  private def log_response_error(context, request_start, error)
936
+ elapsed = request_start ? Util.monotonic_time - request_start : nil
561
937
  Util.log_error("Request error",
562
- elapsed: Time.now - request_start,
938
+ elapsed: elapsed,
563
939
  error_message: error.message,
564
940
  idempotency_key: context.idempotency_key,
565
941
  method: context.method,
566
- path: context.path)
942
+ path: context.path,
943
+ config: config)
567
944
  end
568
945
 
569
946
  # RequestLogContext stores information about a request that's begin made so
@@ -577,7 +954,7 @@ module Stripe
577
954
  attr_accessor :idempotency_key
578
955
  attr_accessor :method
579
956
  attr_accessor :path
580
- attr_accessor :query_params
957
+ attr_accessor :query
581
958
  attr_accessor :request_id
582
959
 
583
960
  # The idea with this method is that we might want to update some of
@@ -586,18 +963,7 @@ module Stripe
586
963
  # with for a request. For example, we should trust whatever came back in
587
964
  # a `Stripe-Version` header beyond what configuration information that we
588
965
  # might have had available.
589
- def dup_from_response(resp)
590
- return self if resp.nil?
591
-
592
- # Faraday's API is a little unusual. Normally it'll produce a response
593
- # object with a `headers` method, but on error what it puts into
594
- # `e.response` is an untyped `Hash`.
595
- headers = if resp.is_a?(Faraday::Response)
596
- resp.headers
597
- else
598
- resp[:headers]
599
- end
600
-
966
+ def dup_from_response_headers(headers)
601
967
  context = dup
602
968
  context.account = headers["Stripe-Account"]
603
969
  context.api_version = headers["Stripe-Version"]