stripe 3.2.0 → 5.16.0

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