loading
Generated 2024-11-19T13:01:23+00:00

All Files ( 96.44% covered at 17256.82 hits/line )

101 files in total.
6946 relevant lines, 6699 lines covered and 247 lines missed. ( 96.44% )
File % covered Lines Relevant Lines Lines covered Lines missed Avg. Hits / Line
lib/httpx.rb 100.00 % 67 39 39 0 595.90
lib/httpx/adapters/datadog.rb 87.12 % 352 163 142 21 37.80
lib/httpx/adapters/faraday.rb 98.15 % 296 162 159 3 89.71
lib/httpx/adapters/sentry.rb 100.00 % 121 62 62 0 46.00
lib/httpx/adapters/webmock.rb 100.00 % 158 84 84 0 123.86
lib/httpx/altsvc.rb 96.39 % 163 83 80 3 199.04
lib/httpx/buffer.rb 100.00 % 50 21 21 0 6831.24
lib/httpx/callbacks.rb 100.00 % 40 22 22 0 109683.55
lib/httpx/chainable.rb 95.45 % 104 44 42 2 880.25
lib/httpx/connection.rb 96.38 % 764 387 373 14 35438.52
lib/httpx/connection/http1.rb 90.09 % 401 222 200 22 3247.27
lib/httpx/connection/http2.rb 95.97 % 409 248 238 10 3095.91
lib/httpx/domain_name.rb 95.56 % 145 45 43 2 216.69
lib/httpx/errors.rb 97.56 % 107 41 40 1 76.34
lib/httpx/extensions.rb 67.86 % 59 28 19 9 515.04
lib/httpx/headers.rb 100.00 % 175 71 71 0 15511.76
lib/httpx/io.rb 100.00 % 11 5 5 0 24.00
lib/httpx/io/ssl.rb 96.47 % 162 85 82 3 1774.16
lib/httpx/io/tcp.rb 91.15 % 206 113 103 10 6136.73
lib/httpx/io/udp.rb 100.00 % 62 35 35 0 312.94
lib/httpx/io/unix.rb 94.29 % 70 35 33 2 17.83
lib/httpx/loggable.rb 100.00 % 34 14 14 0 23161.43
lib/httpx/options.rb 98.71 % 350 155 153 2 13809.63
lib/httpx/parser/http1.rb 100.00 % 186 109 109 0 6408.69
lib/httpx/plugins/auth.rb 100.00 % 25 9 9 0 21.00
lib/httpx/plugins/auth/basic.rb 100.00 % 20 10 10 0 73.70
lib/httpx/plugins/auth/digest.rb 100.00 % 102 61 61 0 112.97
lib/httpx/plugins/auth/ntlm.rb 100.00 % 35 19 19 0 4.00
lib/httpx/plugins/auth/socks5.rb 100.00 % 22 11 11 0 21.00
lib/httpx/plugins/aws_sdk_authentication.rb 100.00 % 109 43 43 0 11.56
lib/httpx/plugins/aws_sigv4.rb 100.00 % 221 114 114 0 86.09
lib/httpx/plugins/basic_auth.rb 100.00 % 29 12 12 0 30.92
lib/httpx/plugins/brotli.rb 100.00 % 50 25 25 0 9.00
lib/httpx/plugins/callbacks.rb 100.00 % 91 43 43 0 123.86
lib/httpx/plugins/circuit_breaker.rb 97.06 % 148 68 66 2 60.03
lib/httpx/plugins/circuit_breaker/circuit.rb 100.00 % 100 47 47 0 50.19
lib/httpx/plugins/circuit_breaker/circuit_store.rb 100.00 % 53 23 23 0 86.13
lib/httpx/plugins/cookies.rb 100.00 % 107 51 51 0 103.92
lib/httpx/plugins/cookies/cookie.rb 100.00 % 174 77 77 0 278.23
lib/httpx/plugins/cookies/jar.rb 100.00 % 97 47 47 0 232.49
lib/httpx/plugins/cookies/set_cookie_parser.rb 100.00 % 140 70 70 0 140.99
lib/httpx/plugins/digest_auth.rb 100.00 % 65 29 29 0 86.76
lib/httpx/plugins/expect.rb 100.00 % 117 56 56 0 71.09
lib/httpx/plugins/follow_redirects.rb 100.00 % 230 105 105 0 5238.84
lib/httpx/plugins/grpc.rb 100.00 % 280 133 133 0 98.16
lib/httpx/plugins/grpc/call.rb 90.91 % 63 33 30 3 33.48
lib/httpx/plugins/grpc/grpc_encoding.rb 97.83 % 88 46 45 1 61.85
lib/httpx/plugins/grpc/message.rb 95.83 % 55 24 23 1 32.92
lib/httpx/plugins/h2c.rb 94.44 % 108 54 51 3 12.52
lib/httpx/plugins/ntlm_auth.rb 100.00 % 60 30 30 0 4.83
lib/httpx/plugins/oauth.rb 89.53 % 175 86 77 9 40.29
lib/httpx/plugins/persistent.rb 100.00 % 36 11 11 0 133.64
lib/httpx/plugins/proxy.rb 97.35 % 310 151 147 4 297.44
lib/httpx/plugins/proxy/http.rb 100.00 % 184 102 102 0 169.86
lib/httpx/plugins/proxy/socks4.rb 98.73 % 135 79 78 1 159.05
lib/httpx/plugins/proxy/socks5.rb 100.00 % 194 113 113 0 238.10
lib/httpx/plugins/proxy/ssh.rb 92.31 % 92 52 48 4 6.83
lib/httpx/plugins/push_promise.rb 100.00 % 81 41 41 0 9.17
lib/httpx/plugins/rate_limiter.rb 100.00 % 55 18 18 0 36.56
lib/httpx/plugins/response_cache.rb 100.00 % 181 82 82 0 66.80
lib/httpx/plugins/response_cache/store.rb 100.00 % 93 47 47 0 101.43
lib/httpx/plugins/retries.rb 95.83 % 219 96 92 4 65176.45
lib/httpx/plugins/ssrf_filter.rb 100.00 % 145 61 61 0 116.44
lib/httpx/plugins/stream.rb 100.00 % 157 74 74 0 100.53
lib/httpx/plugins/upgrade.rb 100.00 % 83 37 37 0 39.19
lib/httpx/plugins/upgrade/h2.rb 91.67 % 54 24 22 2 7.25
lib/httpx/plugins/webdav.rb 100.00 % 80 36 36 0 18.97
lib/httpx/pmatch_extensions.rb 100.00 % 33 17 17 0 25.29
lib/httpx/pool.rb 82.46 % 303 171 141 30 86207.53
lib/httpx/punycode.rb 100.00 % 22 9 9 0 16.67
lib/httpx/request.rb 100.00 % 279 114 114 0 4413.28
lib/httpx/request/body.rb 100.00 % 154 69 69 0 2406.46
lib/httpx/resolver.rb 100.00 % 154 79 79 0 1329.92
lib/httpx/resolver/https.rb 88.00 % 253 150 132 18 28.56
lib/httpx/resolver/multi.rb 100.00 % 75 40 40 0 113236.85
lib/httpx/resolver/native.rb 94.44 % 459 270 255 15 53637.04
lib/httpx/resolver/resolver.rb 90.00 % 120 60 54 6 951.32
lib/httpx/resolver/system.rb 92.68 % 214 123 114 9 19.85
lib/httpx/response.rb 100.00 % 287 105 105 0 1523.90
lib/httpx/response/body.rb 100.00 % 253 115 115 0 2196.42
lib/httpx/response/buffer.rb 96.00 % 96 50 48 2 1509.70
lib/httpx/selector.rb 86.76 % 138 68 59 9 231219.54
lib/httpx/session.rb 94.94 % 365 178 169 9 46894.77
lib/httpx/session_extensions.rb 100.00 % 29 14 14 0 6.00
lib/httpx/timers.rb 100.00 % 110 57 57 0 455420.81
lib/httpx/transcoder.rb 100.00 % 92 53 53 0 240.00
lib/httpx/transcoder/body.rb 100.00 % 59 33 33 0 650.85
lib/httpx/transcoder/chunker.rb 100.00 % 115 66 66 0 192.73
lib/httpx/transcoder/deflate.rb 100.00 % 37 20 20 0 22.50
lib/httpx/transcoder/form.rb 100.00 % 80 42 42 0 378.00
lib/httpx/transcoder/gzip.rb 100.00 % 74 43 43 0 75.74
lib/httpx/transcoder/json.rb 100.00 % 59 33 33 0 30.82
lib/httpx/transcoder/multipart.rb 100.00 % 17 10 10 0 800.70
lib/httpx/transcoder/multipart/decoder.rb 93.98 % 139 83 78 5 25.63
lib/httpx/transcoder/multipart/encoder.rb 100.00 % 118 69 69 0 1776.12
lib/httpx/transcoder/multipart/mime_type_detector.rb 92.11 % 78 38 35 3 155.39
lib/httpx/transcoder/multipart/part.rb 100.00 % 35 18 18 0 441.67
lib/httpx/transcoder/utils/body_reader.rb 96.00 % 46 25 24 1 78.32
lib/httpx/transcoder/utils/deflater.rb 100.00 % 72 36 36 0 74.00
lib/httpx/transcoder/xml.rb 92.31 % 52 26 24 2 51.00
lib/httpx/utils.rb 100.00 % 75 39 39 0 114594.90

lib/httpx.rb

100.0% lines covered

39 relevant lines. 39 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "httpx/version"
  3. 24 require "httpx/extensions"
  4. 24 require "httpx/errors"
  5. 24 require "httpx/utils"
  6. 24 require "httpx/punycode"
  7. 24 require "httpx/domain_name"
  8. 24 require "httpx/altsvc"
  9. 24 require "httpx/callbacks"
  10. 24 require "httpx/loggable"
  11. 24 require "httpx/transcoder"
  12. 24 require "httpx/timers"
  13. 24 require "httpx/pool"
  14. 24 require "httpx/headers"
  15. 24 require "httpx/request"
  16. 24 require "httpx/response"
  17. 24 require "httpx/options"
  18. 24 require "httpx/chainable"
  19. # Top-Level Namespace
  20. #
  21. 24 module HTTPX
  22. 24 EMPTY = [].freeze
  23. # All plugins should be stored under this module/namespace. Can register and load
  24. # plugins.
  25. #
  26. 24 module Plugins
  27. 24 @plugins = {}
  28. 24 @plugins_mutex = Thread::Mutex.new
  29. # Loads a plugin based on a name. If the plugin hasn't been loaded, tries to load
  30. # it from the load path under "httpx/plugins/" directory.
  31. #
  32. 24 def self.load_plugin(name)
  33. 4231 h = @plugins
  34. 4231 m = @plugins_mutex
  35. 8462 unless (plugin = m.synchronize { h[name] })
  36. 129 require "httpx/plugins/#{name}"
  37. 258 raise "Plugin #{name} hasn't been registered" unless (plugin = m.synchronize { h[name] })
  38. end
  39. 4231 plugin
  40. end
  41. # Registers a plugin (+mod+) in the central store indexed by +name+.
  42. #
  43. 24 def self.register_plugin(name, mod)
  44. 251 h = @plugins
  45. 251 m = @plugins_mutex
  46. 476 m.synchronize { h[name] = mod }
  47. end
  48. end
  49. 24 extend Chainable
  50. end
  51. 24 require "httpx/session"
  52. 24 require "httpx/session_extensions"
  53. # load integrations when possible
  54. 24 require "httpx/adapters/datadog" if defined?(DDTrace) || defined?(Datadog)
  55. 24 require "httpx/adapters/sentry" if defined?(Sentry)
  56. 24 require "httpx/adapters/webmock" if defined?(WebMock)

lib/httpx/adapters/datadog.rb

87.12% lines covered

163 relevant lines. 142 lines covered and 21 lines missed.
    
  1. # frozen_string_literal: true
  2. 5 require "datadog/tracing/contrib/integration"
  3. 5 require "datadog/tracing/contrib/configuration/settings"
  4. 5 require "datadog/tracing/contrib/patcher"
  5. 5 module Datadog::Tracing
  6. 5 module Contrib
  7. 5 module HTTPX
  8. 5 DATADOG_VERSION = defined?(::DDTrace) ? ::DDTrace::VERSION : ::Datadog::VERSION
  9. 5 METADATA_MODULE = Datadog::Tracing::Metadata
  10. 5 TYPE_OUTBOUND = Datadog::Tracing::Metadata::Ext::HTTP::TYPE_OUTBOUND
  11. 5 TAG_PEER_SERVICE = Datadog::Tracing::Metadata::Ext::TAG_PEER_SERVICE
  12. 5 TAG_URL = Datadog::Tracing::Metadata::Ext::HTTP::TAG_URL
  13. 5 TAG_METHOD = Datadog::Tracing::Metadata::Ext::HTTP::TAG_METHOD
  14. 5 TAG_TARGET_HOST = Datadog::Tracing::Metadata::Ext::NET::TAG_TARGET_HOST
  15. 5 TAG_TARGET_PORT = Datadog::Tracing::Metadata::Ext::NET::TAG_TARGET_PORT
  16. 5 TAG_STATUS_CODE = Datadog::Tracing::Metadata::Ext::HTTP::TAG_STATUS_CODE
  17. # HTTPX Datadog Plugin
  18. #
  19. # Enables tracing for httpx requests.
  20. #
  21. # A span will be created for each request transaction; the span is created lazily only when
  22. # receiving a response, and it is fed the start time stored inside the tracer object.
  23. #
  24. 5 module Plugin
  25. 5 class RequestTracer
  26. 5 include Contrib::HttpAnnotationHelper
  27. 5 SPAN_REQUEST = "httpx.request"
  28. # initializes the tracer object on the +request+.
  29. 5 def initialize(request)
  30. 163 @request = request
  31. 163 @start_time = nil
  32. # request objects are reused, when already buffered requests get rerouted to a different
  33. # connection due to connection issues, or when they already got a response, but need to
  34. # be retried. In such situations, the original span needs to be extended for the former,
  35. # while a new is required for the latter.
  36. 182 request.on(:idle) { reset }
  37. # the span is initialized when the request is buffered in the parser, which is the closest
  38. # one gets to actually sending the request.
  39. 273 request.on(:headers) { call }
  40. end
  41. # sets up the span start time, while preparing the on response callback.
  42. 5 def call(*args)
  43. 119 return if @start_time
  44. 114 start(*args)
  45. 114 @request.once(:response, &method(:finish))
  46. end
  47. 5 private
  48. # just sets the span init time. It can be passed a +start_time+ in cases where
  49. # this is collected outside the request transaction.
  50. 5 def start(start_time = now)
  51. 119 @start_time = start_time
  52. end
  53. # resets the start time for already finished request transactions.
  54. 5 def reset
  55. 19 return unless @start_time
  56. 5 start
  57. end
  58. # creates the span from the collected +@start_time+ to what the +response+ state
  59. # contains. It also resets internal state to allow this object to be reused.
  60. 5 def finish(response)
  61. 114 return unless @start_time
  62. 114 span = initialize_span
  63. 114 return unless span
  64. 114 if response.is_a?(::HTTPX::ErrorResponse)
  65. 9 span.set_error(response.error)
  66. else
  67. 105 span.set_tag(TAG_STATUS_CODE, response.status.to_s)
  68. 105 span.set_error(::HTTPX::HTTPError.new(response)) if response.status >= 400 && response.status <= 599
  69. end
  70. 114 span.finish
  71. ensure
  72. 114 @start_time = nil
  73. end
  74. # return a span initialized with the +@request+ state.
  75. 5 def initialize_span
  76. 114 verb = @request.verb
  77. 114 uri = @request.uri
  78. 114 span = create_span(@request)
  79. 114 span.resource = verb
  80. # Add additional request specific tags to the span.
  81. 114 span.set_tag(TAG_URL, @request.path)
  82. 114 span.set_tag(TAG_METHOD, verb)
  83. 114 span.set_tag(TAG_TARGET_HOST, uri.host)
  84. 114 span.set_tag(TAG_TARGET_PORT, uri.port.to_s)
  85. # Tag as an external peer service
  86. 114 span.set_tag(TAG_PEER_SERVICE, span.service)
  87. 114 if configuration[:distributed_tracing]
  88. 109 propagate_trace_http(
  89. Datadog::Tracing.active_trace.to_digest,
  90. @request.headers
  91. )
  92. end
  93. # Set analytics sample rate
  94. 114 if Contrib::Analytics.enabled?(configuration[:analytics_enabled])
  95. 10 Contrib::Analytics.set_sample_rate(span, configuration[:analytics_sample_rate])
  96. end
  97. 114 span
  98. rescue StandardError => e
  99. Datadog.logger.error("error preparing span for http request: #{e}")
  100. Datadog.logger.error(e.backtrace)
  101. end
  102. 5 def now
  103. 110 ::Datadog::Core::Utils::Time.now.utc
  104. end
  105. 5 def configuration
  106. 352 @configuration ||= Datadog.configuration.tracing[:httpx, @request.uri.host]
  107. end
  108. 5 if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("2.0.0")
  109. 2 def propagate_trace_http(digest, headers)
  110. 41 Datadog::Tracing::Contrib::HTTP.inject(digest, headers)
  111. end
  112. 2 def create_span(request)
  113. 43 Datadog::Tracing.trace(
  114. SPAN_REQUEST,
  115. service: service_name(request.uri.host, configuration, Datadog.configuration_for(self)),
  116. type: TYPE_OUTBOUND,
  117. start_time: @start_time
  118. )
  119. end
  120. else
  121. 3 def propagate_trace_http(digest, headers)
  122. 68 Datadog::Tracing::Propagation::HTTP.inject!(digest, headers)
  123. end
  124. 3 def create_span(request)
  125. 71 Datadog::Tracing.trace(
  126. SPAN_REQUEST,
  127. service: service_name(request.uri.host, configuration, Datadog.configuration_for(self)),
  128. span_type: TYPE_OUTBOUND,
  129. start_time: @start_time
  130. )
  131. end
  132. end
  133. end
  134. 5 module RequestMethods
  135. # intercepts request initialization to inject the tracing logic.
  136. 5 def initialize(*)
  137. 154 super
  138. 154 return unless Datadog::Tracing.enabled?
  139. 154 RequestTracer.new(self)
  140. end
  141. end
  142. 5 module ConnectionMethods
  143. 5 attr_reader :init_time
  144. 5 def initialize(*)
  145. 139 super
  146. 139 @init_time = ::Datadog::Core::Utils::Time.now.utc
  147. end
  148. # handles the case when the +error+ happened during name resolution, which meanns
  149. # that the tracing logic hasn't been injected yet; in such cases, the approximate
  150. # initial resolving time is collected from the connection, and used as span start time,
  151. # and the tracing object in inserted before the on response callback is called.
  152. 5 def handle_error(error, request = nil)
  153. 9 return super unless Datadog::Tracing.enabled?
  154. 9 return super unless error.respond_to?(:connection)
  155. 9 @pending.each do |req|
  156. 9 next if request and request == req
  157. 9 RequestTracer.new(req).call(error.connection.init_time)
  158. end
  159. 9 RequestTracer.new(request).call(error.connection.init_time) if request
  160. 9 super
  161. end
  162. end
  163. end
  164. 5 module Configuration
  165. # Default settings for httpx
  166. #
  167. 5 class Settings < Datadog::Tracing::Contrib::Configuration::Settings
  168. 5 DEFAULT_ERROR_HANDLER = lambda do |response|
  169. Datadog::Ext::HTTP::ERROR_RANGE.cover?(response.status)
  170. end
  171. 5 option :service_name, default: "httpx"
  172. 5 option :distributed_tracing, default: true
  173. 5 option :split_by_domain, default: false
  174. 5 if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
  175. 5 option :enabled do |o|
  176. 5 o.type :bool
  177. 5 o.env "DD_TRACE_HTTPX_ENABLED"
  178. 5 o.default true
  179. end
  180. 5 option :analytics_enabled do |o|
  181. 5 o.type :bool
  182. 5 o.env "DD_TRACE_HTTPX_ANALYTICS_ENABLED"
  183. 5 o.default false
  184. end
  185. 5 option :analytics_sample_rate do |o|
  186. 5 o.type :float
  187. 5 o.env "DD_TRACE_HTTPX_ANALYTICS_SAMPLE_RATE"
  188. 5 o.default 1.0
  189. end
  190. else
  191. option :enabled do |o|
  192. o.default { env_to_bool("DD_TRACE_HTTPX_ENABLED", true) }
  193. o.lazy
  194. end
  195. option :analytics_enabled do |o|
  196. o.default { env_to_bool(%w[DD_TRACE_HTTPX_ANALYTICS_ENABLED DD_HTTPX_ANALYTICS_ENABLED], false) }
  197. o.lazy
  198. end
  199. option :analytics_sample_rate do |o|
  200. o.default { env_to_float(%w[DD_TRACE_HTTPX_ANALYTICS_SAMPLE_RATE DD_HTTPX_ANALYTICS_SAMPLE_RATE], 1.0) }
  201. o.lazy
  202. end
  203. end
  204. 5 if defined?(Datadog::Tracing::Contrib::SpanAttributeSchema)
  205. 5 option :service_name do |o|
  206. 5 o.default do
  207. 59 Datadog::Tracing::Contrib::SpanAttributeSchema.fetch_service_name(
  208. "DD_TRACE_HTTPX_SERVICE_NAME",
  209. "httpx"
  210. )
  211. end
  212. 5 o.lazy unless Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
  213. end
  214. else
  215. option :service_name do |o|
  216. o.default do
  217. ENV.fetch("DD_TRACE_HTTPX_SERVICE_NAME", "httpx")
  218. end
  219. o.lazy unless Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
  220. end
  221. end
  222. 5 option :distributed_tracing, default: true
  223. 5 if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.15.0")
  224. 5 option :error_handler do |o|
  225. 5 o.type :proc
  226. 5 o.default_proc(&DEFAULT_ERROR_HANDLER)
  227. end
  228. elsif Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
  229. option :error_handler do |o|
  230. o.type :proc
  231. o.experimental_default_proc(&DEFAULT_ERROR_HANDLER)
  232. end
  233. else
  234. option :error_handler, default: DEFAULT_ERROR_HANDLER
  235. end
  236. end
  237. end
  238. # Patcher enables patching of 'httpx' with datadog components.
  239. #
  240. 5 module Patcher
  241. 5 include Datadog::Tracing::Contrib::Patcher
  242. 5 module_function
  243. 5 def target_version
  244. 10 Integration.version
  245. end
  246. # loads a session instannce with the datadog plugin, and replaces the
  247. # base HTTPX::Session with the patched session class.
  248. 5 def patch
  249. 5 datadog_session = ::HTTPX.plugin(Plugin)
  250. 5 ::HTTPX.send(:remove_const, :Session)
  251. 5 ::HTTPX.send(:const_set, :Session, datadog_session.class)
  252. end
  253. end
  254. # Datadog Integration for HTTPX.
  255. #
  256. 5 class Integration
  257. 5 include Contrib::Integration
  258. 5 MINIMUM_VERSION = Gem::Version.new("0.10.2")
  259. 5 register_as :httpx
  260. 5 def self.version
  261. 205 Gem.loaded_specs["httpx"] && Gem.loaded_specs["httpx"].version
  262. end
  263. 5 def self.loaded?
  264. 65 defined?(::HTTPX::Request)
  265. end
  266. 5 def self.compatible?
  267. 65 super && version >= MINIMUM_VERSION
  268. end
  269. 5 def new_configuration
  270. 69 Configuration::Settings.new
  271. end
  272. 5 def patcher
  273. 130 Patcher
  274. end
  275. end
  276. end
  277. end
  278. end

lib/httpx/adapters/faraday.rb

98.15% lines covered

162 relevant lines. 159 lines covered and 3 lines missed.
    
  1. # frozen_string_literal: true
  2. 8 require "delegate"
  3. 8 require "httpx"
  4. 8 require "faraday"
  5. 8 module Faraday
  6. 8 class Adapter
  7. 8 class HTTPX < Faraday::Adapter
  8. 8 module RequestMixin
  9. 8 def build_connection(env)
  10. 190 return @connection if defined?(@connection)
  11. 190 @connection = ::HTTPX.plugin(:persistent).plugin(ReasonPlugin)
  12. 190 @connection = @connection.with(@connection_options) unless @connection_options.empty?
  13. 190 connection_opts = options_from_env(env)
  14. 190 if (bind = env.request.bind)
  15. 7 @bind = TCPSocket.new(bind[:host], bind[:port])
  16. 6 connection_opts[:io] = @bind
  17. end
  18. 190 @connection = @connection.with(connection_opts)
  19. 190 if (proxy = env.request.proxy)
  20. 7 proxy_options = { uri: proxy.uri }
  21. 7 proxy_options[:username] = proxy.user if proxy.user
  22. 7 proxy_options[:password] = proxy.password if proxy.password
  23. 7 @connection = @connection.plugin(:proxy).with(proxy: proxy_options)
  24. end
  25. 190 @connection = @connection.plugin(OnDataPlugin) if env.request.stream_response?
  26. 190 @connection = @config_block.call(@connection) || @connection if @config_block
  27. 190 @connection
  28. end
  29. 8 def close
  30. 196 @connection.close if @connection
  31. 196 @bind.close if @bind
  32. end
  33. 8 private
  34. 8 def connect(env, &blk)
  35. 190 connection(env, &blk)
  36. rescue ::HTTPX::TLSError => e
  37. 7 raise Faraday::SSLError, e
  38. rescue Errno::ECONNABORTED,
  39. Errno::ECONNREFUSED,
  40. Errno::ECONNRESET,
  41. Errno::EHOSTUNREACH,
  42. Errno::EINVAL,
  43. Errno::ENETUNREACH,
  44. Errno::EPIPE,
  45. ::HTTPX::ConnectionError => e
  46. 7 raise Faraday::ConnectionFailed, e
  47. end
  48. 8 def build_request(env)
  49. 197 meth = env[:method]
  50. 28 request_options = {
  51. 168 headers: env.request_headers,
  52. body: env.body,
  53. **options_from_env(env),
  54. }
  55. 197 [meth.to_s.upcase, env.url, request_options]
  56. end
  57. 8 def options_from_env(env)
  58. 387 timeout_options = {}
  59. 387 req_opts = env.request
  60. 387 if (sec = request_timeout(:read, req_opts))
  61. 12 timeout_options[:read_timeout] = sec
  62. end
  63. 387 if (sec = request_timeout(:write, req_opts))
  64. 12 timeout_options[:write_timeout] = sec
  65. end
  66. 387 if (sec = request_timeout(:open, req_opts))
  67. 12 timeout_options[:connect_timeout] = sec
  68. end
  69. 55 {
  70. 331 ssl: ssl_options_from_env(env),
  71. timeout: timeout_options,
  72. }
  73. end
  74. 8 if defined?(::OpenSSL)
  75. 8 def ssl_options_from_env(env)
  76. 387 ssl_options = {}
  77. 387 unless env.ssl.verify.nil?
  78. 24 ssl_options[:verify_mode] = env.ssl.verify ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
  79. end
  80. 387 ssl_options[:ca_file] = env.ssl.ca_file if env.ssl.ca_file
  81. 387 ssl_options[:ca_path] = env.ssl.ca_path if env.ssl.ca_path
  82. 387 ssl_options[:cert_store] = env.ssl.cert_store if env.ssl.cert_store
  83. 387 ssl_options[:cert] = env.ssl.client_cert if env.ssl.client_cert
  84. 387 ssl_options[:key] = env.ssl.client_key if env.ssl.client_key
  85. 387 ssl_options[:ssl_version] = env.ssl.version if env.ssl.version
  86. 387 ssl_options[:verify_depth] = env.ssl.verify_depth if env.ssl.verify_depth
  87. 387 ssl_options[:min_version] = env.ssl.min_version if env.ssl.min_version
  88. 387 ssl_options[:max_version] = env.ssl.max_version if env.ssl.max_version
  89. 387 ssl_options
  90. end
  91. else
  92. def ssl_options_from_env(*)
  93. {}
  94. end
  95. end
  96. end
  97. 8 include RequestMixin
  98. 8 module OnDataPlugin
  99. 8 module RequestMethods
  100. 8 attr_writer :response_on_data
  101. 8 def response=(response)
  102. 14 super
  103. 14 return if response.is_a?(::HTTPX::ErrorResponse)
  104. 14 response.body.on_data = @response_on_data
  105. end
  106. end
  107. 8 module ResponseBodyMethods
  108. 8 attr_writer :on_data
  109. 8 def write(chunk)
  110. 30 return super unless @on_data
  111. 30 @on_data.call(chunk, chunk.bytesize)
  112. end
  113. end
  114. end
  115. 8 module ReasonPlugin
  116. 8 def self.load_dependencies(*)
  117. 190 require "net/http/status"
  118. end
  119. 8 module ResponseMethods
  120. 8 def reason
  121. 155 Net::HTTP::STATUS_CODES.fetch(@status)
  122. end
  123. end
  124. end
  125. 8 class ParallelManager
  126. 8 class ResponseHandler < SimpleDelegator
  127. 8 attr_reader :env
  128. 8 def initialize(env)
  129. 28 @env = env
  130. 28 super
  131. end
  132. 8 def on_response(&blk)
  133. 56 if blk
  134. 28 @on_response = ->(response) do
  135. 28 blk.call(response)
  136. end
  137. 28 self
  138. else
  139. 28 @on_response
  140. end
  141. end
  142. 8 def on_complete(&blk)
  143. 84 if blk
  144. 28 @on_complete = blk
  145. 28 self
  146. else
  147. 56 @on_complete
  148. end
  149. end
  150. end
  151. 8 include RequestMixin
  152. 8 def initialize(options)
  153. 28 @handlers = []
  154. 28 @connection_options = options
  155. end
  156. 8 def enqueue(request)
  157. 28 handler = ResponseHandler.new(request)
  158. 28 @handlers << handler
  159. 28 handler
  160. end
  161. 8 def run
  162. 28 return unless @handlers.last
  163. 21 env = @handlers.last.env
  164. 21 connect(env) do |session|
  165. 49 requests = @handlers.map { |handler| session.build_request(*build_request(handler.env)) }
  166. 21 if env.request.stream_response?
  167. 7 requests.each do |request|
  168. 7 request.response_on_data = env.request.on_data
  169. end
  170. end
  171. 21 responses = session.request(*requests)
  172. 21 Array(responses).each_with_index do |response, index|
  173. 28 handler = @handlers[index]
  174. 28 handler.on_response.call(response)
  175. 28 handler.on_complete.call(handler.env) if handler.on_complete
  176. end
  177. end
  178. rescue ::HTTPX::TimeoutError => e
  179. raise Faraday::TimeoutError, e
  180. end
  181. # from Faraday::Adapter#connection
  182. 8 def connection(env)
  183. 21 conn = build_connection(env)
  184. 21 return conn unless block_given?
  185. 21 yield conn
  186. end
  187. 8 private
  188. # from Faraday::Adapter#request_timeout
  189. 8 def request_timeout(type, options)
  190. 147 key = Faraday::Adapter::TIMEOUT_KEYS[type]
  191. 147 options[key] || options[:timeout]
  192. end
  193. end
  194. 8 self.supports_parallel = true
  195. 8 class << self
  196. 8 def setup_parallel_manager(options = {})
  197. 28 ParallelManager.new(options)
  198. end
  199. end
  200. 8 def call(env)
  201. 197 super
  202. 197 if parallel?(env)
  203. 28 handler = env[:parallel_manager].enqueue(env)
  204. 28 handler.on_response do |response|
  205. 28 if response.is_a?(::HTTPX::Response)
  206. 21 save_response(env, response.status, response.body.to_s, response.headers, response.reason) do |response_headers|
  207. 21 response_headers.merge!(response.headers)
  208. end
  209. else
  210. 6 env[:error] = response.error
  211. 7 save_response(env, 0, "", {}, nil)
  212. end
  213. end
  214. 24 return handler
  215. end
  216. 169 response = connect_and_request(env)
  217. 134 save_response(env, response.status, response.body.to_s, response.headers, response.reason) do |response_headers|
  218. 134 response_headers.merge!(response.headers)
  219. end
  220. 134 @app.call(env)
  221. end
  222. 8 private
  223. 8 def connect_and_request(env)
  224. 169 connect(env) do |session|
  225. 169 request = session.build_request(*build_request(env))
  226. 169 request.response_on_data = env.request.on_data if env.request.stream_response?
  227. 169 response = session.request(request)
  228. # do not call #raise_for_status for HTTP 4xx or 5xx, as faraday has a middleware for that.
  229. 169 response.raise_for_status unless response.is_a?(::HTTPX::Response)
  230. 134 response
  231. end
  232. rescue ::HTTPX::TimeoutError => e
  233. 21 raise Faraday::TimeoutError, e
  234. end
  235. 8 def parallel?(env)
  236. 197 env[:parallel_manager]
  237. end
  238. end
  239. 8 register_middleware httpx: HTTPX
  240. end
  241. end

lib/httpx/adapters/sentry.rb

100.0% lines covered

62 relevant lines. 62 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 5 require "sentry-ruby"
  3. 5 module HTTPX::Plugins
  4. 5 module Sentry
  5. 5 module Tracer
  6. 5 module_function
  7. 5 def call(request)
  8. 59 sentry_span = start_sentry_span
  9. 59 return unless sentry_span
  10. 59 set_sentry_trace_header(request, sentry_span)
  11. 59 request.on(:response, &method(:finish_sentry_span).curry(3)[sentry_span, request])
  12. end
  13. 5 def start_sentry_span
  14. 59 return unless ::Sentry.initialized? && (span = ::Sentry.get_current_scope.get_span)
  15. 59 return if span.sampled == false
  16. 59 span.start_child(op: "httpx.client", start_timestamp: ::Sentry.utc_now.to_f)
  17. end
  18. 5 def set_sentry_trace_header(request, sentry_span)
  19. 59 return unless sentry_span
  20. 59 config = ::Sentry.configuration
  21. 59 url = request.uri.to_s
  22. 118 return unless config.propagate_traces && config.trace_propagation_targets.any? { |target| url.match?(target) }
  23. 59 trace = ::Sentry.get_current_client.generate_sentry_trace(sentry_span)
  24. 59 request.headers[::Sentry::SENTRY_TRACE_HEADER_NAME] = trace if trace
  25. end
  26. 5 def finish_sentry_span(span, request, response)
  27. 61 return unless ::Sentry.initialized?
  28. 61 record_sentry_breadcrumb(request, response)
  29. 61 record_sentry_span(request, response, span)
  30. end
  31. 5 def record_sentry_breadcrumb(req, res)
  32. 61 return unless ::Sentry.configuration.breadcrumbs_logger.include?(:http_logger)
  33. 61 request_info = extract_request_info(req)
  34. 61 data = if res.is_a?(HTTPX::ErrorResponse)
  35. 6 { error: res.error.message, **request_info }
  36. else
  37. 55 { status: res.status, **request_info }
  38. end
  39. 61 crumb = ::Sentry::Breadcrumb.new(
  40. level: :info,
  41. category: "httpx",
  42. type: :info,
  43. data: data
  44. )
  45. 61 ::Sentry.add_breadcrumb(crumb)
  46. end
  47. 5 def record_sentry_span(req, res, sentry_span)
  48. 61 return unless sentry_span
  49. 61 request_info = extract_request_info(req)
  50. 61 sentry_span.set_description("#{request_info[:method]} #{request_info[:url]}")
  51. 61 if res.is_a?(HTTPX::ErrorResponse)
  52. 6 sentry_span.set_data(:error, res.error.message)
  53. else
  54. 55 sentry_span.set_data(:status, res.status)
  55. end
  56. 61 sentry_span.set_timestamp(::Sentry.utc_now.to_f)
  57. end
  58. 5 def extract_request_info(req)
  59. 122 uri = req.uri
  60. result = {
  61. 122 method: req.verb,
  62. }
  63. 122 if ::Sentry.configuration.send_default_pii
  64. 20 uri += "?#{req.query}" unless req.query.empty?
  65. 20 result[:body] = req.body.to_s unless req.body.empty? || req.body.unbounded_body?
  66. end
  67. 122 result[:url] = uri.to_s
  68. 122 result
  69. end
  70. end
  71. 5 module RequestMethods
  72. 5 def __sentry_enable_trace!
  73. 61 return if @__sentry_enable_trace
  74. 59 Tracer.call(self)
  75. 59 @__sentry_enable_trace = true
  76. end
  77. end
  78. 5 module ConnectionMethods
  79. 5 def send(request)
  80. 61 request.__sentry_enable_trace!
  81. 61 super
  82. end
  83. end
  84. end
  85. end
  86. 5 Sentry.register_patch(:httpx) do
  87. 25 sentry_session = HTTPX.plugin(HTTPX::Plugins::Sentry)
  88. 25 HTTPX.send(:remove_const, :Session)
  89. 25 HTTPX.send(:const_set, :Session, sentry_session.class)
  90. end

lib/httpx/adapters/webmock.rb

100.0% lines covered

84 relevant lines. 84 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module WebMock
  3. 7 module HttpLibAdapters
  4. 7 require "net/http/status"
  5. 7 HTTP_REASONS = Net::HTTP::STATUS_CODES
  6. #
  7. # HTTPX plugin for webmock.
  8. #
  9. # Requests are "hijacked" at the session, before they're distributed to a connection.
  10. #
  11. 7 module Plugin
  12. 7 class << self
  13. 7 def build_webmock_request_signature(request)
  14. 157 uri = WebMock::Util::URI.heuristic_parse(request.uri)
  15. 157 uri.query = request.query
  16. 157 uri.path = uri.normalized_path.gsub("[^:]//", "/")
  17. 157 WebMock::RequestSignature.new(
  18. request.verb.downcase.to_sym,
  19. uri.to_s,
  20. body: request.body.to_s,
  21. headers: request.headers.to_h
  22. )
  23. end
  24. 7 def build_webmock_response(_request, response)
  25. 5 webmock_response = WebMock::Response.new
  26. 5 webmock_response.status = [response.status, HTTP_REASONS[response.status]]
  27. 5 webmock_response.body = response.body.to_s
  28. 5 webmock_response.headers = response.headers.to_h
  29. 5 webmock_response
  30. end
  31. 7 def build_from_webmock_response(request, webmock_response)
  32. 132 return build_error_response(request, HTTPX::TimeoutError.new(1, "Timed out")) if webmock_response.should_timeout
  33. 117 return build_error_response(request, webmock_response.exception) if webmock_response.exception
  34. 111 request.options.response_class.new(request,
  35. webmock_response.status[0],
  36. "2.0",
  37. webmock_response.headers).tap do |res|
  38. 111 res.mocked = true
  39. end
  40. end
  41. 7 def build_error_response(request, exception)
  42. 21 HTTPX::ErrorResponse.new(request, exception)
  43. end
  44. end
  45. 7 module InstanceMethods
  46. 7 def init_connection(*)
  47. 132 connection = super
  48. 132 connection.once(:unmock_connection) do
  49. 20 unless connection.addresses
  50. 20 connection.__send__(:callbacks)[:connect_error].clear
  51. 20 pool.__send__(:unregister_connection, connection)
  52. end
  53. 20 pool.__send__(:resolve_connection, connection)
  54. end
  55. 132 connection
  56. end
  57. end
  58. 7 module ResponseMethods
  59. 7 attr_accessor :mocked
  60. 7 def initialize(*)
  61. 131 super
  62. 131 @mocked = false
  63. end
  64. end
  65. 7 module ResponseBodyMethods
  66. 7 def decode_chunk(chunk)
  67. 80 return chunk if @response.mocked
  68. 35 super
  69. end
  70. end
  71. 7 module ConnectionMethods
  72. 7 def initialize(*)
  73. 132 super
  74. 132 @mocked = true
  75. end
  76. 7 def open?
  77. 152 return true if @mocked
  78. 20 super
  79. end
  80. 7 def interests
  81. 4034 return if @mocked
  82. 205 super
  83. end
  84. 7 def send(request)
  85. 157 request_signature = Plugin.build_webmock_request_signature(request)
  86. 157 WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
  87. 157 if (mock_response = WebMock::StubRegistry.instance.response_for_request(request_signature))
  88. 132 response = Plugin.build_from_webmock_response(request, mock_response)
  89. 132 WebMock::CallbackRegistry.invoke_callbacks({ lib: :httpx }, request_signature, mock_response)
  90. 132 log { "mocking #{request.uri} with #{mock_response.inspect}" }
  91. 132 request.response = response
  92. 132 request.emit(:response, response)
  93. 132 response << mock_response.body.dup unless response.is_a?(HTTPX::ErrorResponse)
  94. 25 elsif WebMock.net_connect_allowed?(request_signature.uri)
  95. 20 if WebMock::CallbackRegistry.any_callbacks?
  96. 5 request.on(:response) do |resp|
  97. 5 unless resp.is_a?(HTTPX::ErrorResponse)
  98. 5 webmock_response = Plugin.build_webmock_response(request, resp)
  99. 5 WebMock::CallbackRegistry.invoke_callbacks(
  100. { lib: :httpx, real_request: true }, request_signature,
  101. webmock_response
  102. )
  103. end
  104. end
  105. end
  106. 20 @mocked = false
  107. 20 emit(:unmock_connection, self)
  108. 20 super
  109. else
  110. 5 raise WebMock::NetConnectNotAllowedError, request_signature
  111. end
  112. end
  113. end
  114. end
  115. 7 class HttpxAdapter < HttpLibAdapter
  116. 7 adapter_for :httpx
  117. 7 class << self
  118. 7 def enable!
  119. 309 @original_session ||= HTTPX::Session
  120. 309 webmock_session = HTTPX.plugin(Plugin)
  121. 309 HTTPX.send(:remove_const, :Session)
  122. 309 HTTPX.send(:const_set, :Session, webmock_session.class)
  123. end
  124. 7 def disable!
  125. 309 return unless @original_session
  126. 302 HTTPX.send(:remove_const, :Session)
  127. 302 HTTPX.send(:const_set, :Session, @original_session)
  128. end
  129. end
  130. end
  131. end
  132. end

lib/httpx/altsvc.rb

96.39% lines covered

83 relevant lines. 80 lines covered and 3 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "strscan"
  3. 24 module HTTPX
  4. 24 module AltSvc
  5. # makes connections able to accept requests destined to primary service.
  6. 24 module ConnectionMixin
  7. 24 using URIExtensions
  8. 24 def send(request)
  9. 7 request.headers["alt-used"] = @origin.authority if @parser && !@write_buffer.full? && match_altsvcs?(request.uri)
  10. 7 super
  11. end
  12. 24 def match?(uri, options)
  13. 7 return false if !used? && (@state == :closing || @state == :closed)
  14. 7 match_altsvcs?(uri) && match_altsvc_options?(uri, options)
  15. end
  16. 24 private
  17. # checks if this is connection is an alternative service of
  18. # +uri+
  19. 24 def match_altsvcs?(uri)
  20. 21 @origins.any? { |origin| altsvc_match?(uri, origin) } ||
  21. AltSvc.cached_altsvc(@origin).any? do |altsvc|
  22. origin = altsvc["origin"]
  23. altsvc_match?(origin, uri.origin)
  24. end
  25. end
  26. 24 def match_altsvc_options?(uri, options)
  27. 7 return @options == options unless @options.ssl.all? do |k, v|
  28. 7 v == (k == :hostname ? uri.host : options.ssl[k])
  29. end
  30. 7 @options.options_equals?(options, Options::REQUEST_BODY_IVARS + %i[@ssl])
  31. end
  32. 24 def altsvc_match?(uri, other_uri)
  33. 14 other_uri = URI(other_uri)
  34. 14 uri.origin == other_uri.origin || begin
  35. 6 case uri.scheme
  36. when "h2"
  37. (other_uri.scheme == "https" || other_uri.scheme == "h2") &&
  38. uri.host == other_uri.host &&
  39. uri.port == other_uri.port
  40. else
  41. 7 false
  42. end
  43. end
  44. end
  45. end
  46. 24 @altsvc_mutex = Thread::Mutex.new
  47. 42 @altsvcs = Hash.new { |h, k| h[k] = [] }
  48. 24 module_function
  49. 24 def cached_altsvc(origin)
  50. 35 now = Utils.now
  51. 35 @altsvc_mutex.synchronize do
  52. 35 lookup(origin, now)
  53. end
  54. end
  55. 24 def cached_altsvc_set(origin, entry)
  56. 21 now = Utils.now
  57. 21 @altsvc_mutex.synchronize do
  58. 21 return if @altsvcs[origin].any? { |altsvc| altsvc["origin"] == entry["origin"] }
  59. 21 entry["TTL"] = Integer(entry["ma"]) + now if entry.key?("ma")
  60. 21 @altsvcs[origin] << entry
  61. 21 entry
  62. end
  63. end
  64. 24 def lookup(origin, ttl)
  65. 35 return [] unless @altsvcs.key?(origin)
  66. 24 @altsvcs[origin] = @altsvcs[origin].select do |entry|
  67. 21 !entry.key?("TTL") || entry["TTL"] > ttl
  68. end
  69. 42 @altsvcs[origin].reject { |entry| entry["noop"] }
  70. end
  71. 24 def emit(request, response)
  72. 6396 return unless response.respond_to?(:headers)
  73. # Alt-Svc
  74. 6374 return unless response.headers.key?("alt-svc")
  75. 72 origin = request.origin
  76. 72 host = request.uri.host
  77. 72 altsvc = response.headers["alt-svc"]
  78. # https://datatracker.ietf.org/doc/html/rfc7838#section-3
  79. # A field value containing the special value "clear" indicates that the
  80. # origin requests all alternatives for that origin to be invalidated
  81. # (including those specified in the same response, in case of an
  82. # invalid reply containing both "clear" and alternative services).
  83. 72 if altsvc == "clear"
  84. 7 @altsvc_mutex.synchronize do
  85. 7 @altsvcs[origin].clear
  86. end
  87. 6 return
  88. end
  89. 65 parse(altsvc) do |alt_origin, alt_params|
  90. 7 alt_origin.host ||= host
  91. 7 yield(alt_origin, origin, alt_params)
  92. end
  93. end
  94. 24 def parse(altsvc)
  95. 163 return enum_for(__method__, altsvc) unless block_given?
  96. 114 scanner = StringScanner.new(altsvc)
  97. 120 until scanner.eos?
  98. 114 alt_service = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
  99. 114 alt_params = []
  100. 114 loop do
  101. 135 alt_param = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
  102. 135 alt_params << alt_param.strip if alt_param
  103. 135 scanner.skip(/;/)
  104. 135 break if scanner.eos? || scanner.scan(/ *, */)
  105. end
  106. 228 alt_params = Hash[alt_params.map { |field| field.split("=", 2) }]
  107. 114 alt_proto, alt_authority = alt_service.split("=", 2)
  108. 114 alt_origin = parse_altsvc_origin(alt_proto, alt_authority)
  109. 114 return unless alt_origin
  110. 42 yield(alt_origin, alt_params.merge("proto" => alt_proto))
  111. end
  112. end
  113. 24 def parse_altsvc_scheme(alt_proto)
  114. 118 case alt_proto
  115. when "h2c"
  116. 7 "http"
  117. when "h2"
  118. 49 "https"
  119. end
  120. end
  121. 24 def parse_altsvc_origin(alt_proto, alt_origin)
  122. 114 alt_scheme = parse_altsvc_scheme(alt_proto)
  123. 114 return unless alt_scheme
  124. 42 alt_origin = alt_origin[1..-2] if alt_origin.start_with?("\"") && alt_origin.end_with?("\"")
  125. 42 URI.parse("#{alt_scheme}://#{alt_origin}")
  126. end
  127. end
  128. end

lib/httpx/buffer.rb

100.0% lines covered

21 relevant lines. 21 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "forwardable"
  3. 24 module HTTPX
  4. # Internal class to abstract a string buffer, by wrapping a string and providing the
  5. # minimum possible API and functionality required.
  6. #
  7. # buffer = Buffer.new(640)
  8. # buffer.full? #=> false
  9. # buffer << "aa"
  10. # buffer.capacity #=> 638
  11. #
  12. 24 class Buffer
  13. 24 extend Forwardable
  14. 24 def_delegator :@buffer, :<<
  15. 24 def_delegator :@buffer, :to_s
  16. 24 def_delegator :@buffer, :to_str
  17. 24 def_delegator :@buffer, :empty?
  18. 24 def_delegator :@buffer, :bytesize
  19. 24 def_delegator :@buffer, :clear
  20. 24 def_delegator :@buffer, :replace
  21. 24 attr_reader :limit
  22. 24 def initialize(limit)
  23. 12489 @buffer = "".b
  24. 12489 @limit = limit
  25. end
  26. 24 def full?
  27. 100451 @buffer.bytesize >= @limit
  28. end
  29. 24 def capacity
  30. 10 @limit - @buffer.bytesize
  31. end
  32. 24 def shift!(fin)
  33. 17633 @buffer = @buffer.byteslice(fin..-1) || "".b
  34. end
  35. end
  36. end

lib/httpx/callbacks.rb

100.0% lines covered

22 relevant lines. 22 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 module Callbacks
  4. 24 def on(type, &action)
  5. 232586 callbacks(type) << action
  6. 232586 self
  7. end
  8. 24 def once(type, &block)
  9. 87295 on(type) do |*args, &callback|
  10. 86222 block.call(*args, &callback)
  11. 86166 :delete
  12. end
  13. 87295 self
  14. end
  15. 24 def only(type, &block)
  16. 17856 callbacks(type).clear
  17. 17856 on(type, &block)
  18. end
  19. 24 def emit(type, *args)
  20. 264311 callbacks(type).delete_if { |pr| :delete == pr.call(*args) } # rubocop:disable Style/YodaCondition
  21. end
  22. 24 def callbacks_for?(type)
  23. 2615 @callbacks.key?(type) && @callbacks[type].any?
  24. end
  25. 24 protected
  26. 24 def callbacks(type = nil)
  27. 374202 return @callbacks unless type
  28. 549726 @callbacks ||= Hash.new { |h, k| h[k] = [] }
  29. 374106 @callbacks[type]
  30. end
  31. end
  32. end

lib/httpx/chainable.rb

95.45% lines covered

44 relevant lines. 42 lines covered and 2 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. # Session mixin, implements most of the APIs that the users call.
  4. # delegates to a default session when extended.
  5. 24 module Chainable
  6. 24 %w[head get post put delete trace options connect patch].each do |meth|
  7. 207 class_eval(<<-MOD, __FILE__, __LINE__ + 1)
  8. 9 def #{meth}(*uri, **options) # def get(*uri, **options)
  9. 18 request("#{meth.upcase}", uri, **options) # request("GET", uri, **options)
  10. end # end
  11. MOD
  12. end
  13. # delegates to the default session (see HTTPX::Session#request).
  14. 24 def request(*args, **options)
  15. 2147 branch(default_options).request(*args, **options)
  16. end
  17. 24 def accept(type)
  18. 14 with(headers: { "accept" => String(type) })
  19. end
  20. # delegates to the default session (see HTTPX::Session#wrap).
  21. 24 def wrap(&blk)
  22. 85 branch(default_options).wrap(&blk)
  23. end
  24. # returns a new instance loaded with the +pl+ plugin and +options+.
  25. 24 def plugin(pl, options = nil, &blk)
  26. 3976 klass = is_a?(S) ? self.class : Session
  27. 3976 klass = Class.new(klass)
  28. 3976 klass.instance_variable_set(:@default_options, klass.default_options.merge(default_options))
  29. 3976 klass.plugin(pl, options, &blk).new
  30. end
  31. # returns a new instance loaded with +options+.
  32. 24 def with(options, &blk)
  33. 2122 branch(default_options.merge(options), &blk)
  34. end
  35. 24 private
  36. # returns default instance of HTTPX::Options.
  37. 24 def default_options
  38. 8379 @options || Session.default_options
  39. end
  40. # returns a default instance of HTTPX::Session.
  41. 24 def branch(options, &blk)
  42. 4354 return self.class.new(options, &blk) if is_a?(S)
  43. 2543 Session.new(options, &blk)
  44. end
  45. 24 def method_missing(meth, *args, **options, &blk)
  46. 558 case meth
  47. when /\Awith_(.+)/
  48. 636 option = Regexp.last_match(1)
  49. 636 return super unless option
  50. 636 with(option.to_sym => args.first || options)
  51. when /\Aon_(.+)/
  52. 8 callback = Regexp.last_match(1)
  53. 7 return super unless %w[
  54. connection_opened connection_closed
  55. request_error
  56. request_started request_body_chunk request_completed
  57. response_started response_body_chunk response_completed
  58. ].include?(callback)
  59. 8 warn "DEPRECATION WARNING: calling `.#{meth}` on plain HTTPX sessions is deprecated. " \
  60. 1 "Use HTTPX.plugin(:callbacks).#{meth} instead."
  61. 8 plugin(:callbacks).__send__(meth, *args, **options, &blk)
  62. else
  63. super
  64. end
  65. end
  66. 24 def respond_to_missing?(meth, *)
  67. 42 case meth
  68. when /\Awith_(.+)/
  69. 35 option = Regexp.last_match(1)
  70. 35 default_options.respond_to?(option) || super
  71. when /\Aon_(.+)/
  72. 14 callback = Regexp.last_match(1)
  73. 12 %w[
  74. connection_opened connection_closed
  75. request_error
  76. request_started request_body_chunk request_completed
  77. response_started response_body_chunk response_completed
  78. 1 ].include?(callback) || super
  79. else
  80. super
  81. end
  82. end
  83. end
  84. end

lib/httpx/connection.rb

96.38% lines covered

387 relevant lines. 373 lines covered and 14 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "resolv"
  3. 24 require "forwardable"
  4. 24 require "httpx/io"
  5. 24 require "httpx/buffer"
  6. 24 module HTTPX
  7. # The Connection can be watched for IO events.
  8. #
  9. # It contains the +io+ object to read/write from, and knows what to do when it can.
  10. #
  11. # It defers connecting until absolutely necessary. Connection should be triggered from
  12. # the IO selector (until then, any request will be queued).
  13. #
  14. # A connection boots up its parser after connection is established. All pending requests
  15. # will be redirected there after connection.
  16. #
  17. # A connection can be prevented from closing by the parser, that is, if there are pending
  18. # requests. This will signal that the connection was prematurely closed, due to a possible
  19. # number of conditions:
  20. #
  21. # * Remote peer closed the connection ("Connection: close");
  22. # * Remote peer doesn't support pipelining;
  23. #
  24. # A connection may also route requests for a different host for which the +io+ was connected
  25. # to, provided that the IP is the same and the port and scheme as well. This will allow to
  26. # share the same socket to send HTTP/2 requests to different hosts.
  27. #
  28. 24 class Connection
  29. 24 extend Forwardable
  30. 24 include Loggable
  31. 24 include Callbacks
  32. 24 using URIExtensions
  33. 24 require "httpx/connection/http2"
  34. 24 require "httpx/connection/http1"
  35. 24 def_delegator :@io, :closed?
  36. 24 def_delegator :@write_buffer, :empty?
  37. 24 attr_reader :type, :io, :origin, :origins, :state, :pending, :options, :ssl_session
  38. 24 attr_writer :timers
  39. 24 attr_accessor :family
  40. 24 def initialize(uri, options)
  41. 5936 @origins = [uri.origin]
  42. 5936 @origin = Utils.to_uri(uri.origin)
  43. 5936 @options = Options.new(options)
  44. 5936 @type = initialize_type(uri, @options)
  45. 5936 @origins = [uri.origin]
  46. 5936 @origin = Utils.to_uri(uri.origin)
  47. 5936 @window_size = @options.window_size
  48. 5936 @read_buffer = Buffer.new(@options.buffer_size)
  49. 5936 @write_buffer = Buffer.new(@options.buffer_size)
  50. 5936 @pending = []
  51. 5936 on(:error, &method(:on_error))
  52. 5936 if @options.io
  53. # if there's an already open IO, get its
  54. # peer address, and force-initiate the parser
  55. 57 transition(:already_open)
  56. 57 @io = build_socket
  57. 57 parser
  58. else
  59. 5879 transition(:idle)
  60. end
  61. 5936 @inflight = 0
  62. 5936 @keep_alive_timeout = @options.timeout[:keep_alive_timeout]
  63. 5936 @intervals = []
  64. 5936 self.addresses = @options.addresses if @options.addresses
  65. end
  66. # this is a semi-private method, to be used by the resolver
  67. # to initiate the io object.
  68. 24 def addresses=(addrs)
  69. 5738 if @io
  70. 179 @io.add_addresses(addrs)
  71. else
  72. 5559 @io = build_socket(addrs)
  73. end
  74. end
  75. 24 def addresses
  76. 25410 @io && @io.addresses
  77. end
  78. 24 def match?(uri, options)
  79. 12706 return false if !used? && (@state == :closing || @state == :closed)
  80. 476 (
  81. 12503 @origins.include?(uri.origin) &&
  82. # if there is more than one origin to match, it means that this connection
  83. # was the result of coalescing. To prevent blind trust in the case where the
  84. # origin came from an ORIGIN frame, we're going to verify the hostname with the
  85. # SSL certificate
  86. 2710 (@origins.size == 1 || @origin == uri.origin || (@io.is_a?(SSL) && @io.verify_hostname(uri.host)))
  87. ) && @options == options
  88. end
  89. 24 def expired?
  90. return false unless @io
  91. @io.expired?
  92. end
  93. 24 def mergeable?(connection)
  94. 9953 return false if @state == :closing || @state == :closed || !@io
  95. 6836 return false unless connection.addresses
  96. 90 (
  97. 6836 (open? && @origin == connection.origin) ||
  98. 6761 !(@io.addresses & (connection.addresses || [])).empty?
  99. ) && @options == connection.options
  100. end
  101. # coalescable connections need to be mergeable!
  102. # but internally, #mergeable? is called before #coalescable?
  103. 24 def coalescable?(connection)
  104. 13 if @io.protocol == "h2" &&
  105. @origin.scheme == "https" &&
  106. connection.origin.scheme == "https" &&
  107. @io.can_verify_peer?
  108. 6 @io.verify_hostname(connection.origin.host)
  109. else
  110. 7 @origin == connection.origin
  111. end
  112. end
  113. 24 def create_idle(options = {})
  114. 7 self.class.new(@origin, @options.merge(options))
  115. end
  116. 24 def merge(connection)
  117. 23 @origins |= connection.instance_variable_get(:@origins)
  118. 25 if connection.ssl_session
  119. 6 @ssl_session = connection.ssl_session
  120. @io.session_new_cb do |sess|
  121. @ssl_session = sess
  122. 6 end if @io
  123. end
  124. 25 connection.purge_pending do |req|
  125. 6 send(req)
  126. end
  127. end
  128. 24 def purge_pending(&block)
  129. 25 pendings = []
  130. 25 if @parser
  131. 12 @inflight -= @parser.pending.size
  132. 14 pendings << @parser.pending
  133. end
  134. 25 pendings << @pending
  135. 25 pendings.each do |pending|
  136. 39 pending.reject!(&block)
  137. end
  138. end
  139. 24 def connecting?
  140. 126717 @state == :idle
  141. end
  142. 24 def inflight?
  143. 5649 @parser && !@parser.empty? && !@write_buffer.empty?
  144. end
  145. 24 def interests
  146. # connecting
  147. 117620 if connecting?
  148. 8823 connect
  149. 8823 return @io.interests if connecting?
  150. end
  151. # if the write buffer is full, we drain it
  152. 109393 return :w unless @write_buffer.empty?
  153. 75883 return @parser.interests if @parser
  154. 9 nil
  155. end
  156. 24 def to_io
  157. 19088 @io.to_io
  158. end
  159. 24 def call
  160. 15240 case @state
  161. when :idle
  162. 8096 connect
  163. 8082 consume
  164. when :closed
  165. return
  166. when :closing
  167. consume
  168. transition(:closed)
  169. when :open
  170. 8720 consume
  171. end
  172. 3588 nil
  173. end
  174. 24 def close
  175. 5676 transition(:active) if @state == :inactive
  176. 5676 @parser.close if @parser
  177. end
  178. 24 def terminate
  179. 5676 @connected_at = nil if @state == :closed
  180. 5676 close
  181. end
  182. # bypasses the state machine to force closing of connections still connecting.
  183. # **only** used for Happy Eyeballs v2.
  184. 24 def force_reset
  185. 135 @state = :closing
  186. 135 transition(:closed)
  187. end
  188. 24 def reset
  189. 9124 return if @state == :closing || @state == :closed
  190. 6191 transition(:closing)
  191. 6191 transition(:closed)
  192. end
  193. 24 def send(request)
  194. 7233 if @parser && !@write_buffer.full?
  195. 356 if @response_received_at && @keep_alive_timeout &&
  196. Utils.elapsed_time(@response_received_at) > @keep_alive_timeout
  197. # when pushing a request into an existing connection, we have to check whether there
  198. # is the possibility that the connection might have extended the keep alive timeout.
  199. # for such cases, we want to ping for availability before deciding to shovel requests.
  200. 7 log(level: 3) { "keep alive timeout expired, pinging connection..." }
  201. 7 @pending << request
  202. 7 transition(:active) if @state == :inactive
  203. 7 parser.ping
  204. 6 return
  205. end
  206. 349 send_request_to_parser(request)
  207. else
  208. 6877 @pending << request
  209. end
  210. end
  211. 24 def timeout
  212. 3652852 return @timeout if @timeout
  213. 3578022 return @options.timeout[:connect_timeout] if @state == :idle
  214. 3578022 @options.timeout[:operation_timeout]
  215. end
  216. 24 def idling
  217. 565 purge_after_closed
  218. 565 @write_buffer.clear
  219. 565 transition(:idle)
  220. 565 @parser = nil if @parser
  221. end
  222. 24 def used?
  223. 19519 @connected_at
  224. end
  225. 24 def deactivate
  226. 1013 transition(:inactive)
  227. end
  228. 24 def open?
  229. 12595 @state == :open || @state == :inactive
  230. end
  231. 24 def handle_socket_timeout(interval)
  232. 390 @intervals.delete_if(&:elapsed?)
  233. 390 unless @intervals.empty?
  234. # remove the intervals which will elapse
  235. 310 return
  236. end
  237. 28 error = HTTPX::TimeoutError.new(interval, "timed out while waiting on select")
  238. 28 error.set_backtrace(caller)
  239. 28 on_error(error)
  240. end
  241. 24 private
  242. 24 def connect
  243. 16037 transition(:open)
  244. end
  245. 24 def consume
  246. 19344 return unless @io
  247. 19344 catch(:called) do
  248. 19344 epiped = false
  249. 19344 loop do
  250. # connection may have
  251. 35682 return if @state == :idle
  252. 33273 parser.consume
  253. # we exit if there's no more requests to process
  254. #
  255. # this condition takes into account:
  256. #
  257. # * the number of inflight requests
  258. # * the number of pending requests
  259. # * whether the write buffer has bytes (i.e. for close handshake)
  260. 33259 if @pending.empty? && @inflight.zero? && @write_buffer.empty?
  261. 2332 log(level: 3) { "NO MORE REQUESTS..." }
  262. 2318 return
  263. end
  264. 30941 @timeout = @current_timeout
  265. 30941 read_drained = false
  266. 30941 write_drained = nil
  267. #
  268. # tight read loop.
  269. #
  270. # read as much of the socket as possible.
  271. #
  272. # this tight loop reads all the data it can from the socket and pipes it to
  273. # its parser.
  274. #
  275. 2253 loop do
  276. 40408 siz = @io.read(@window_size, @read_buffer)
  277. 40510 log(level: 3, color: :cyan) { "IO READ: #{siz} bytes... (wsize: #{@window_size}, rbuffer: #{@read_buffer.bytesize})" }
  278. 40408 unless siz
  279. 13 ex = EOFError.new("descriptor closed")
  280. 13 ex.set_backtrace(caller)
  281. 13 on_error(ex)
  282. 13 return
  283. end
  284. # socket has been drained. mark and exit the read loop.
  285. 40395 if siz.zero?
  286. 7990 read_drained = @read_buffer.empty?
  287. 7990 epiped = false
  288. 7990 break
  289. end
  290. 32405 parser << @read_buffer.to_s
  291. # continue reading if possible.
  292. 28953 break if interests == :w && !epiped
  293. # exit the read loop if connection is preparing to be closed
  294. 22921 break if @state == :closing || @state == :closed
  295. # exit #consume altogether if all outstanding requests have been dealt with
  296. 22915 return if @pending.empty? && @inflight.zero?
  297. 30941 end unless ((ints = interests).nil? || ints == :w || @state == :closing) && !epiped
  298. #
  299. # tight write loop.
  300. #
  301. # flush as many bytes as the sockets allow.
  302. #
  303. 2135 loop do
  304. # buffer has been drainned, mark and exit the write loop.
  305. 19505 if @write_buffer.empty?
  306. # we only mark as drained on the first loop
  307. 2433 write_drained = write_drained.nil? && @inflight.positive?
  308. 2433 break
  309. end
  310. 1905 begin
  311. 17072 siz = @io.write(@write_buffer)
  312. rescue Errno::EPIPE
  313. # this can happen if we still have bytes in the buffer to send to the server, but
  314. # the server wants to respond immediately with some message, or an error. An example is
  315. # when one's uploading a big file to an unintended endpoint, and the server stops the
  316. # consumption, and responds immediately with an authorization of even method not allowed error.
  317. # at this point, we have to let the connection switch to read-mode.
  318. 18 log(level: 2) { "pipe broken, could not flush buffer..." }
  319. 18 epiped = true
  320. 18 read_drained = false
  321. 18 break
  322. end
  323. 17122 log(level: 3, color: :cyan) { "IO WRITE: #{siz} bytes..." }
  324. 17046 unless siz
  325. ex = EOFError.new("descriptor closed")
  326. ex.set_backtrace(caller)
  327. on_error(ex)
  328. return
  329. end
  330. # socket closed for writing. mark and exit the write loop.
  331. 17046 if siz.zero?
  332. 21 write_drained = !@write_buffer.empty?
  333. 21 break
  334. end
  335. # exit write loop if marked to consume from peer, or is closing.
  336. 17025 break if interests == :r || @state == :closing || @state == :closed
  337. 2477 write_drained = false
  338. 25001 end unless (ints = interests) == :r
  339. 24993 send_pending if @state == :open
  340. # return if socket is drained
  341. 24993 next unless (ints != :r || read_drained) && (ints != :w || write_drained)
  342. # gotta go back to the event loop. It happens when:
  343. #
  344. # * the socket is drained of bytes or it's not the interest of the conn to read;
  345. # * theres nothing more to write, or it's not in the interest of the conn to write;
  346. 8682 log(level: 3) { "(#{ints}): WAITING FOR EVENTS..." }
  347. 8655 return
  348. end
  349. end
  350. end
  351. 24 def send_pending
  352. 65955 while !@write_buffer.full? && (request = @pending.shift)
  353. 17070 send_request_to_parser(request)
  354. end
  355. end
  356. 24 def parser
  357. 90002 @parser ||= build_parser
  358. end
  359. 24 def send_request_to_parser(request)
  360. 16582 @inflight += 1
  361. 17419 request.peer_address = @io.ip
  362. 17419 parser.send(request)
  363. 17419 set_request_timeouts(request)
  364. 17419 return unless @state == :inactive
  365. 80 transition(:active)
  366. end
  367. 24 def build_parser(protocol = @io.protocol)
  368. 5890 parser = self.class.parser_type(protocol).new(@write_buffer, @options)
  369. 5890 set_parser_callbacks(parser)
  370. 5890 parser
  371. end
  372. 24 def set_parser_callbacks(parser)
  373. 5987 parser.on(:response) do |request, response|
  374. 6389 AltSvc.emit(request, response) do |alt_origin, origin, alt_params|
  375. 7 emit(:altsvc, alt_origin, origin, alt_params)
  376. end
  377. 6389 @response_received_at = Utils.now
  378. 5626 @inflight -= 1
  379. 6389 request.emit(:response, response)
  380. end
  381. 5987 parser.on(:altsvc) do |alt_origin, origin, alt_params|
  382. emit(:altsvc, alt_origin, origin, alt_params)
  383. end
  384. 5987 parser.on(:pong, &method(:send_pending))
  385. 5987 parser.on(:promise) do |request, stream|
  386. 21 request.emit(:promise, parser, stream)
  387. end
  388. 5987 parser.on(:exhausted) do
  389. 7 @pending.concat(parser.pending)
  390. 7 emit(:exhausted)
  391. end
  392. 5987 parser.on(:origin) do |origin|
  393. @origins |= [origin]
  394. end
  395. 5987 parser.on(:close) do |force|
  396. 5287 if force
  397. 5287 reset
  398. 5280 emit(:terminate)
  399. end
  400. end
  401. 5987 parser.on(:close_handshake) do
  402. 7 consume
  403. end
  404. 5987 parser.on(:reset) do
  405. 3124 @pending.concat(parser.pending) unless parser.empty?
  406. 3124 reset
  407. 3117 idling unless @pending.empty?
  408. end
  409. 5987 parser.on(:current_timeout) do
  410. 2537 @current_timeout = @timeout = parser.timeout
  411. end
  412. 5987 parser.on(:timeout) do |tout|
  413. 2380 @timeout = tout
  414. end
  415. 5987 parser.on(:error) do |request, ex|
  416. 42 case ex
  417. when MisdirectedRequestError
  418. 7 emit(:misdirected, request)
  419. else
  420. 41 response = ErrorResponse.new(request, ex)
  421. 41 request.response = response
  422. 41 request.emit(:response, response)
  423. end
  424. end
  425. end
  426. 24 def transition(nextstate)
  427. 37851 handle_transition(nextstate)
  428. rescue Errno::ECONNABORTED,
  429. Errno::ECONNREFUSED,
  430. Errno::ECONNRESET,
  431. Errno::EADDRNOTAVAIL,
  432. Errno::EHOSTUNREACH,
  433. Errno::EINVAL,
  434. Errno::ENETUNREACH,
  435. Errno::EPIPE,
  436. Errno::ENOENT,
  437. SocketError,
  438. IOError => e
  439. # connect errors, exit gracefully
  440. 64 error = ConnectionError.new(e.message)
  441. 64 error.set_backtrace(e.backtrace)
  442. 64 connecting? && callbacks_for?(:connect_error) ? emit(:connect_error, error) : handle_error(error)
  443. 64 @state = :closed
  444. 64 emit(:close)
  445. rescue TLSError, ::HTTP2::Error::ProtocolError, ::HTTP2::Error::HandshakeError => e
  446. # connect errors, exit gracefully
  447. 22 handle_error(e)
  448. 22 connecting? && callbacks_for?(:connect_error) ? emit(:connect_error, e) : handle_error(e)
  449. 22 @state = :closed
  450. 22 emit(:close)
  451. end
  452. 24 def handle_transition(nextstate)
  453. 32797 case nextstate
  454. when :idle
  455. 6458 @timeout = @current_timeout = @options.timeout[:connect_timeout]
  456. 6458 @connected_at = nil
  457. when :open
  458. 16296 return if @state == :closed
  459. 16296 @io.connect
  460. 16211 emit(:tcp_open, self) if @io.state == :connected
  461. 16211 return unless @io.connected?
  462. 5895 @connected_at = Utils.now
  463. 5895 send_pending
  464. 5895 @timeout = @current_timeout = parser.timeout
  465. 5895 emit(:open)
  466. when :inactive
  467. 1013 return unless @state == :open
  468. # do not deactivate connection in use
  469. 583 return if @inflight.positive?
  470. when :closing
  471. 6248 return unless @state == :idle || @state == :open
  472. 6224 unless @write_buffer.empty?
  473. # preset state before handshake, as error callbacks
  474. # may take it back here.
  475. 2258 @state = nextstate
  476. # handshakes, try sending
  477. 2258 consume
  478. 2257 @write_buffer.clear
  479. 2257 return
  480. end
  481. when :closed
  482. 6333 return unless @state == :closing
  483. 6315 return unless @write_buffer.empty?
  484. 6293 purge_after_closed
  485. 6293 emit(:close) if @pending.empty?
  486. when :already_open
  487. 57 nextstate = :open
  488. # the first check for given io readiness must still use a timeout.
  489. # connect is the reasonable choice in such a case.
  490. 57 @timeout = @options.timeout[:connect_timeout]
  491. 57 send_pending
  492. when :active
  493. 493 return unless @state == :inactive
  494. 493 nextstate = :open
  495. 493 emit(:activate)
  496. end
  497. 24201 @state = nextstate
  498. end
  499. 24 def purge_after_closed
  500. 6865 @io.close if @io
  501. 6865 @read_buffer.clear
  502. 6865 @timeout = nil
  503. end
  504. 24 def initialize_type(uri, options)
  505. 5616 options.transport || begin
  506. 4883 case uri.scheme
  507. when "http"
  508. 3075 "tcp"
  509. when "https"
  510. 2517 "ssl"
  511. else
  512. raise UnsupportedSchemeError, "#{uri}: #{uri.scheme}: unsupported URI scheme"
  513. end
  514. end
  515. end
  516. 24 def build_socket(addrs = nil)
  517. 4877 case @type
  518. when "tcp"
  519. 3161 TCP.new(@origin, addrs, @options)
  520. when "ssl"
  521. 2431 SSL.new(@origin, addrs, @options) do |sock|
  522. 2412 sock.ssl_session = @ssl_session
  523. 2412 sock.session_new_cb do |sess|
  524. 4047 @ssl_session = sess
  525. 4047 sock.ssl_session = sess
  526. end
  527. end
  528. when "unix"
  529. 24 path = Array(addrs).first
  530. 24 path = String(path) if path
  531. 24 UNIX.new(@origin, path, @options)
  532. else
  533. raise Error, "unsupported transport (#{@type})"
  534. end
  535. end
  536. 24 def on_error(error, request = nil)
  537. 699 if error.instance_of?(TimeoutError)
  538. # inactive connections do not contribute to the select loop, therefore
  539. # they should not fail due to such errors.
  540. 28 return if @state == :inactive
  541. 28 if @timeout
  542. 24 @timeout -= error.timeout
  543. 28 return unless @timeout <= 0
  544. end
  545. 28 error = error.to_connection_error if connecting?
  546. end
  547. 699 handle_error(error, request)
  548. 699 reset
  549. end
  550. 24 def handle_error(error, request = nil)
  551. 807 parser.handle_error(error, request) if @parser && parser.respond_to?(:handle_error)
  552. 1760 while (req = @pending.shift)
  553. 368 next if request && req == request
  554. 368 response = ErrorResponse.new(req, error)
  555. 368 req.response = response
  556. 368 req.emit(:response, response)
  557. end
  558. 807 return unless request
  559. 358 response = ErrorResponse.new(request, error)
  560. 358 request.response = response
  561. 358 request.emit(:response, response)
  562. end
  563. 24 def set_request_timeouts(request)
  564. 17419 set_request_write_timeout(request)
  565. 17419 set_request_read_timeout(request)
  566. 17419 set_request_request_timeout(request)
  567. end
  568. 24 def set_request_read_timeout(request)
  569. 17419 read_timeout = request.read_timeout
  570. 17419 return if read_timeout.nil? || read_timeout.infinite?
  571. 17174 set_request_timeout(request, read_timeout, :done, :response) do
  572. 21 read_timeout_callback(request, read_timeout)
  573. end
  574. end
  575. 24 def set_request_write_timeout(request)
  576. 17419 write_timeout = request.write_timeout
  577. 17419 return if write_timeout.nil? || write_timeout.infinite?
  578. 17419 set_request_timeout(request, write_timeout, :headers, %i[done response]) do
  579. 21 write_timeout_callback(request, write_timeout)
  580. end
  581. end
  582. 24 def set_request_request_timeout(request)
  583. 17170 request_timeout = request.request_timeout
  584. 17170 return if request_timeout.nil? || request_timeout.infinite?
  585. 448 set_request_timeout(request, request_timeout, :headers, :complete) do
  586. 316 read_timeout_callback(request, request_timeout, RequestTimeoutError)
  587. end
  588. end
  589. 24 def write_timeout_callback(request, write_timeout)
  590. 21 return if request.state == :done
  591. 21 @write_buffer.clear
  592. 21 error = WriteTimeoutError.new(request, nil, write_timeout)
  593. 21 on_error(error, request)
  594. end
  595. 24 def read_timeout_callback(request, read_timeout, error_type = ReadTimeoutError)
  596. 337 response = request.response
  597. 337 return if response && response.finished?
  598. 337 @write_buffer.clear
  599. 337 error = error_type.new(request, request.response, read_timeout)
  600. 337 on_error(error, request)
  601. end
  602. 24 def set_request_timeout(request, timeout, start_event, finish_events, &callback)
  603. 35111 request.once(start_event) do
  604. 34478 interval = @timers.after(timeout, callback)
  605. 34478 Array(finish_events).each do |event|
  606. # clean up request timeouts if the connection errors out
  607. 51668 request.once(event) do
  608. 51535 if @intervals.include?(interval)
  609. 51064 interval.delete(callback)
  610. 51064 @intervals.delete(interval) if interval.no_callbacks?
  611. end
  612. end
  613. end
  614. 34478 @intervals << interval
  615. end
  616. end
  617. 24 class << self
  618. 24 def parser_type(protocol)
  619. 5232 case protocol
  620. 2544 when "h2" then HTTP2
  621. 3472 when "http/1.1" then HTTP1
  622. else
  623. raise Error, "unsupported protocol (##{protocol})"
  624. end
  625. end
  626. end
  627. end
  628. end

lib/httpx/connection/http1.rb

90.09% lines covered

222 relevant lines. 200 lines covered and 22 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "httpx/parser/http1"
  3. 24 module HTTPX
  4. 24 class Connection::HTTP1
  5. 24 include Callbacks
  6. 24 include Loggable
  7. 24 MAX_REQUESTS = 200
  8. 24 CRLF = "\r\n"
  9. 24 attr_reader :pending, :requests
  10. 24 attr_accessor :max_concurrent_requests
  11. 24 def initialize(buffer, options)
  12. 3472 @options = options
  13. 3472 @max_concurrent_requests = @options.max_concurrent_requests || MAX_REQUESTS
  14. 3472 @max_requests = @options.max_requests
  15. 3472 @parser = Parser::HTTP1.new(self)
  16. 3472 @buffer = buffer
  17. 3472 @version = [1, 1]
  18. 3472 @pending = []
  19. 3472 @requests = []
  20. 3472 @handshake_completed = false
  21. end
  22. 24 def timeout
  23. 3370 @options.timeout[:operation_timeout]
  24. end
  25. 24 def interests
  26. # this means we're processing incoming response already
  27. 24920 return :r if @request
  28. 20653 return if @requests.empty?
  29. 20598 request = @requests.first
  30. 20598 return unless request
  31. 20598 return :w if request.interests == :w || !@buffer.empty?
  32. 17873 :r
  33. end
  34. 24 def reset
  35. 6092 @max_requests = @options.max_requests || MAX_REQUESTS
  36. 6092 @parser.reset!
  37. 6092 @handshake_completed = false
  38. 6092 @pending.concat(@requests) unless @requests.empty?
  39. end
  40. 24 def close
  41. 2926 reset
  42. 2926 emit(:close, true)
  43. end
  44. 24 def exhausted?
  45. 545 !@max_requests.positive?
  46. end
  47. 24 def empty?
  48. # this means that for every request there's an available
  49. # partial response, so there are no in-flight requests waiting.
  50. 6021 @requests.empty? || (
  51. # checking all responses can be time-consuming. Alas, as in HTTP/1, responses
  52. # do not come out of order, we can get away with checking first and last.
  53. 279 !@requests.first.response.nil? &&
  54. 116 (@requests.size == 1 || !@requests.last.response.nil?)
  55. )
  56. end
  57. 24 def <<(data)
  58. 5746 @parser << data
  59. end
  60. 24 def send(request)
  61. 14542 unless @max_requests.positive?
  62. @pending << request
  63. return
  64. end
  65. 14542 return if @requests.include?(request)
  66. 14542 @requests << request
  67. 14542 @pipelining = true if @requests.size > 1
  68. end
  69. 24 def consume
  70. 13028 requests_limit = [@max_requests, @requests.size].min
  71. 13028 concurrent_requests_limit = [@max_concurrent_requests, requests_limit].min
  72. 13028 @requests.each_with_index do |request, idx|
  73. 15527 break if idx >= concurrent_requests_limit
  74. 12974 next if request.state == :done
  75. 5006 handle(request)
  76. end
  77. end
  78. # HTTP Parser callbacks
  79. #
  80. # must be public methods, or else they won't be reachable
  81. 24 def on_start
  82. 3859 log(level: 2) { "parsing begins" }
  83. end
  84. 24 def on_headers(h)
  85. 3838 @request = @requests.first
  86. 3838 return if @request.response
  87. 3859 log(level: 2) { "headers received" }
  88. 3838 headers = @request.options.headers_class.new(h)
  89. 3838 response = @request.options.response_class.new(@request,
  90. @parser.status_code,
  91. @parser.http_version.join("."),
  92. headers)
  93. 3859 log(color: :yellow) { "-> HEADLINE: #{response.status} HTTP/#{@parser.http_version.join(".")}" }
  94. 4027 log(color: :yellow) { response.headers.each.map { |f, v| "-> HEADER: #{f}: #{v}" }.join("\n") }
  95. 3838 @request.response = response
  96. 3831 on_complete if response.finished?
  97. end
  98. 24 def on_trailers(h)
  99. 7 return unless @request
  100. 7 response = @request.response
  101. 7 log(level: 2) { "trailer headers received" }
  102. 7 log(color: :yellow) { h.each.map { |f, v| "-> HEADER: #{f}: #{v.join(", ")}" }.join("\n") }
  103. 7 response.merge_headers(h)
  104. end
  105. 24 def on_data(chunk)
  106. 4379 request = @request
  107. 4379 return unless request
  108. 4400 log(color: :green) { "-> DATA: #{chunk.bytesize} bytes..." }
  109. 4400 log(level: 2, color: :green) { "-> #{chunk.inspect}" }
  110. 4379 response = request.response
  111. 4379 response << chunk
  112. rescue StandardError => e
  113. 12 error_response = ErrorResponse.new(request, e)
  114. 12 request.response = error_response
  115. 12 dispatch
  116. end
  117. 24 def on_complete
  118. 3812 request = @request
  119. 3812 return unless request
  120. 3833 log(level: 2) { "parsing complete" }
  121. 3812 dispatch
  122. end
  123. 24 def dispatch
  124. 3824 request = @request
  125. 3824 if request.expects?
  126. 63 @parser.reset!
  127. 54 return handle(request)
  128. end
  129. 3761 @request = nil
  130. 3761 @requests.shift
  131. 3761 response = request.response
  132. 3761 response.finish! unless response.is_a?(ErrorResponse)
  133. 3761 emit(:response, request, response)
  134. 3711 if @parser.upgrade?
  135. 28 response << @parser.upgrade_data
  136. 28 throw(:called)
  137. end
  138. 3683 @parser.reset!
  139. 3265 @max_requests -= 1
  140. 3683 if response.is_a?(ErrorResponse)
  141. 12 disable
  142. else
  143. 3671 manage_connection(request, response)
  144. end
  145. 545 if exhausted?
  146. @pending.concat(@requests)
  147. @requests.clear
  148. emit(:exhausted)
  149. else
  150. 545 send(@pending.shift) unless @pending.empty?
  151. end
  152. end
  153. 24 def handle_error(ex, request = nil)
  154. 189 if (ex.is_a?(EOFError) || ex.is_a?(TimeoutError)) && @request && @request.response &&
  155. !@request.response.headers.key?("content-length") &&
  156. !@request.response.headers.key?("transfer-encoding")
  157. # if the response does not contain a content-length header, the server closing the
  158. # connnection is the indicator of response consumed.
  159. # https://greenbytes.de/tech/webdav/rfc2616.html#rfc.section.4.4
  160. 14 catch(:called) { on_complete }
  161. 6 return
  162. end
  163. 182 if @pipelining
  164. catch(:called) { disable }
  165. else
  166. 182 @requests.each do |req|
  167. 172 next if request && request == req
  168. emit(:error, req, ex)
  169. end
  170. 182 @pending.each do |req|
  171. next if request && request == req
  172. emit(:error, req, ex)
  173. end
  174. end
  175. end
  176. 24 def ping
  177. reset
  178. emit(:reset)
  179. emit(:exhausted)
  180. end
  181. 24 private
  182. 24 def manage_connection(request, response)
  183. 3671 connection = response.headers["connection"]
  184. 3254 case connection
  185. when /keep-alive/i
  186. 545 if @handshake_completed
  187. if @max_requests.zero?
  188. @pending.concat(@requests)
  189. @requests.clear
  190. emit(:exhausted)
  191. end
  192. return
  193. end
  194. 545 keep_alive = response.headers["keep-alive"]
  195. 545 return unless keep_alive
  196. 114 parameters = Hash[keep_alive.split(/ *, */).map do |pair|
  197. 114 pair.split(/ *= */, 2)
  198. end]
  199. 114 @max_requests = parameters["max"].to_i - 1 if parameters.key?("max")
  200. 114 if parameters.key?("timeout")
  201. keep_alive_timeout = parameters["timeout"].to_i
  202. emit(:timeout, keep_alive_timeout)
  203. end
  204. 114 @handshake_completed = true
  205. when /close/i
  206. 3126 disable
  207. when nil
  208. # In HTTP/1.1, it's keep alive by default
  209. return if response.version == "1.1" && request.headers["connection"] != "close"
  210. disable
  211. end
  212. end
  213. 24 def disable
  214. 3138 disable_pipelining
  215. 3138 reset
  216. 3138 emit(:reset)
  217. 3131 throw(:called)
  218. end
  219. 24 def disable_pipelining
  220. 3138 return if @requests.empty?
  221. # do not disable pipelining if already set to 1 request at a time
  222. 169 return if @max_concurrent_requests == 1
  223. 18 @requests.each do |r|
  224. 18 r.transition(:idle)
  225. # when we disable pipelining, we still want to try keep-alive.
  226. # only when keep-alive with one request fails, do we fallback to
  227. # connection: close.
  228. 18 r.headers["connection"] = "close" if @max_concurrent_requests == 1
  229. end
  230. # server doesn't handle pipelining, and probably
  231. # doesn't support keep-alive. Fallback to send only
  232. # 1 keep alive request.
  233. 18 @max_concurrent_requests = 1
  234. 18 @pipelining = false
  235. end
  236. 24 def set_protocol_headers(request)
  237. 3972 if !request.headers.key?("content-length") &&
  238. request.body.bytesize == Float::INFINITY
  239. 28 request.body.chunk!
  240. end
  241. 3972 extra_headers = {}
  242. 3972 unless request.headers.key?("connection")
  243. 3951 connection_value = if request.persistent?
  244. # when in a persistent connection, the request can't be at
  245. # the edge of a renegotiation
  246. 834 if @requests.index(request) + 1 < @max_requests
  247. 723 "keep-alive"
  248. else
  249. 111 "close"
  250. end
  251. else
  252. # when it's not a persistent connection, it sets "Connection: close" always
  253. # on the last request of the possible batch (either allowed max requests,
  254. # or if smaller, the size of the batch itself)
  255. 3117 requests_limit = [@max_requests, @requests.size].min
  256. 3117 if request == @requests[requests_limit - 1]
  257. 3077 "close"
  258. else
  259. 40 "keep-alive"
  260. end
  261. end
  262. 3497 extra_headers["connection"] = connection_value
  263. end
  264. 3972 extra_headers["host"] = request.authority unless request.headers.key?("host")
  265. 3972 extra_headers
  266. end
  267. 24 def handle(request)
  268. 5069 catch(:buffer_full) do
  269. 5069 request.transition(:headers)
  270. 5062 join_headers(request) if request.state == :headers
  271. 5062 request.transition(:body)
  272. 5062 join_body(request) if request.state == :body
  273. 4128 request.transition(:trailers)
  274. # HTTP/1.1 trailers should only work for chunked encoding
  275. 4128 join_trailers(request) if request.body.chunked? && request.state == :trailers
  276. 4128 request.transition(:done)
  277. end
  278. end
  279. 24 def join_headline(request)
  280. 3455 "#{request.verb} #{request.path} HTTP/#{@version.join(".")}"
  281. end
  282. 24 def join_headers(request)
  283. 3972 headline = join_headline(request)
  284. 3972 @buffer << headline << CRLF
  285. 3993 log(color: :yellow) { "<- HEADLINE: #{headline.chomp.inspect}" }
  286. 3972 extra_headers = set_protocol_headers(request)
  287. 3972 join_headers2(request.headers.each(extra_headers))
  288. 3993 log { "<- " }
  289. 3972 @buffer << CRLF
  290. end
  291. 24 def join_body(request)
  292. 4885 return if request.body.empty?
  293. 5429 while (chunk = request.drain_body)
  294. 2958 log(color: :green) { "<- DATA: #{chunk.bytesize} bytes..." }
  295. 2958 log(level: 2, color: :green) { "<- #{chunk.inspect}" }
  296. 2958 @buffer << chunk
  297. 2958 throw(:buffer_full, request) if @buffer.full?
  298. end
  299. 1299 return unless (error = request.drain_error)
  300. raise error
  301. end
  302. 24 def join_trailers(request)
  303. 84 return unless request.trailers? && request.callbacks_for?(:trailers)
  304. 28 join_headers2(request.trailers)
  305. 28 log { "<- " }
  306. 28 @buffer << CRLF
  307. end
  308. 24 def join_headers2(headers)
  309. 4000 headers.each do |field, value|
  310. 24040 buffer = "#{capitalized(field)}: #{value}#{CRLF}"
  311. 24145 log(color: :yellow) { "<- HEADER: #{buffer.chomp}" }
  312. 24040 @buffer << buffer
  313. end
  314. end
  315. 24 UPCASED = {
  316. "www-authenticate" => "WWW-Authenticate",
  317. "http2-settings" => "HTTP2-Settings",
  318. "content-md5" => "Content-MD5",
  319. }.freeze
  320. 24 def capitalized(field)
  321. 24040 UPCASED[field] || field.split("-").map(&:capitalize).join("-")
  322. end
  323. end
  324. end

lib/httpx/connection/http2.rb

95.97% lines covered

248 relevant lines. 238 lines covered and 10 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "securerandom"
  3. 24 require "http/2"
  4. 24 module HTTPX
  5. 24 class Connection::HTTP2
  6. 24 include Callbacks
  7. 24 include Loggable
  8. 24 MAX_CONCURRENT_REQUESTS = ::HTTP2::DEFAULT_MAX_CONCURRENT_STREAMS
  9. 24 class Error < Error
  10. 24 def initialize(id, code)
  11. 29 super("stream #{id} closed with error: #{code}")
  12. end
  13. end
  14. 24 class GoawayError < Error
  15. 24 def initialize
  16. 13 super(0, :no_error)
  17. end
  18. end
  19. 24 attr_reader :streams, :pending
  20. 24 def initialize(buffer, options)
  21. 2565 @options = options
  22. 2565 @settings = @options.http2_settings
  23. 2565 @pending = []
  24. 2565 @streams = {}
  25. 2565 @drains = {}
  26. 2565 @pings = []
  27. 2565 @buffer = buffer
  28. 2565 @handshake_completed = false
  29. 2565 @wait_for_handshake = @settings.key?(:wait_for_handshake) ? @settings.delete(:wait_for_handshake) : true
  30. 2565 @max_concurrent_requests = @options.max_concurrent_requests || MAX_CONCURRENT_REQUESTS
  31. 2565 @max_requests = @options.max_requests
  32. 2565 init_connection
  33. end
  34. 24 def timeout
  35. 5062 return @options.timeout[:operation_timeout] if @handshake_completed
  36. 2525 @options.timeout[:settings_timeout]
  37. end
  38. 24 def interests
  39. # waiting for WINDOW_UPDATE frames
  40. 50899 return :r if @buffer.full?
  41. 50899 if @connection.state == :closed
  42. 2384 return unless @handshake_completed
  43. 2043 return :w
  44. end
  45. 48515 unless @connection.state == :connected && @handshake_completed
  46. 9396 return @buffer.empty? ? :r : :rw
  47. end
  48. 37775 return :w if !@pending.empty? && can_buffer_more_requests?
  49. 37775 return :w unless @drains.empty?
  50. 37024 if @buffer.empty?
  51. 37024 return if @streams.empty? && @pings.empty?
  52. 29800 return :r
  53. end
  54. :rw
  55. end
  56. 24 def close
  57. 2392 unless @connection.state == :closed
  58. 2380 @connection.goaway
  59. 2380 emit(:timeout, @options.timeout[:close_handshake_timeout])
  60. end
  61. 2392 emit(:close, true)
  62. end
  63. 24 def empty?
  64. 2358 @connection.state == :closed || @streams.empty?
  65. end
  66. 24 def exhausted?
  67. 2566 !@max_requests.positive?
  68. end
  69. 24 def <<(data)
  70. 26393 @connection << data
  71. end
  72. 24 def can_buffer_more_requests?
  73. 6035 (@handshake_completed || !@wait_for_handshake) &&
  74. @streams.size < @max_concurrent_requests &&
  75. @streams.size < @max_requests
  76. end
  77. 24 def send(request)
  78. 5631 unless can_buffer_more_requests?
  79. 2732 @pending << request
  80. 2732 return
  81. end
  82. 2899 unless (stream = @streams[request])
  83. 2899 stream = @connection.new_stream
  84. 2899 handle_stream(stream, request)
  85. 2527 @streams[request] = stream
  86. 2527 @max_requests -= 1
  87. end
  88. 2899 handle(request, stream)
  89. 2885 true
  90. rescue ::HTTP2::Error::StreamLimitExceeded
  91. @pending.unshift(request)
  92. end
  93. 24 def consume
  94. 19580 @streams.each do |request, stream|
  95. 7453 next if request.state == :done
  96. 858 handle(request, stream)
  97. end
  98. end
  99. 24 def handle_error(ex, request = nil)
  100. 233 if ex.instance_of?(TimeoutError) && !@handshake_completed && @connection.state != :closed
  101. 7 @connection.goaway(:settings_timeout, "closing due to settings timeout")
  102. 7 emit(:close_handshake)
  103. 7 settings_ex = SettingsTimeoutError.new(ex.timeout, ex.message)
  104. 7 settings_ex.set_backtrace(ex.backtrace)
  105. 7 ex = settings_ex
  106. end
  107. 233 @streams.each_key do |req|
  108. 187 next if request && request == req
  109. 12 emit(:error, req, ex)
  110. end
  111. 233 @pending.each do |req|
  112. 29 next if request && request == req
  113. 29 emit(:error, req, ex)
  114. end
  115. end
  116. 24 def ping
  117. 7 ping = SecureRandom.gen_random(8)
  118. 7 @connection.ping(ping)
  119. ensure
  120. 7 @pings << ping
  121. end
  122. 24 private
  123. 24 def send_pending
  124. 6649 while (request = @pending.shift)
  125. # TODO: this request should go back to top of stack
  126. 2628 break unless send(request)
  127. end
  128. end
  129. 24 def handle(request, stream)
  130. 3813 catch(:buffer_full) do
  131. 3813 request.transition(:headers)
  132. 3806 join_headers(stream, request) if request.state == :headers
  133. 3806 request.transition(:body)
  134. 3806 join_body(stream, request) if request.state == :body
  135. 3048 request.transition(:trailers)
  136. 3048 join_trailers(stream, request) if request.state == :trailers && !request.body.empty?
  137. 3048 request.transition(:done)
  138. end
  139. end
  140. 24 def init_connection
  141. 2565 @connection = ::HTTP2::Client.new(@settings)
  142. 2565 @connection.on(:frame, &method(:on_frame))
  143. 2565 @connection.on(:frame_sent, &method(:on_frame_sent))
  144. 2565 @connection.on(:frame_received, &method(:on_frame_received))
  145. 2565 @connection.on(:origin, &method(:on_origin))
  146. 2565 @connection.on(:promise, &method(:on_promise))
  147. 2565 @connection.on(:altsvc) { |frame| on_altsvc(frame[:origin], frame) }
  148. 2565 @connection.on(:settings_ack, &method(:on_settings))
  149. 2565 @connection.on(:ack, &method(:on_pong))
  150. 2565 @connection.on(:goaway, &method(:on_close))
  151. #
  152. # Some servers initiate HTTP/2 negotiation right away, some don't.
  153. # As such, we have to check the socket buffer. If there is something
  154. # to read, the server initiated the negotiation. If not, we have to
  155. # initiate it.
  156. #
  157. 2565 @connection.send_connection_preface
  158. end
  159. 24 alias_method :reset, :init_connection
  160. 24 public :reset
  161. 24 def handle_stream(stream, request)
  162. 2913 request.on(:refuse, &method(:on_stream_refuse).curry(3)[stream, request])
  163. 2913 stream.on(:close, &method(:on_stream_close).curry(3)[stream, request])
  164. 2913 stream.on(:half_close) do
  165. 2894 log(level: 2) { "#{stream.id}: waiting for response..." }
  166. end
  167. 2913 stream.on(:altsvc, &method(:on_altsvc).curry(2)[request.origin])
  168. 2913 stream.on(:headers, &method(:on_stream_headers).curry(3)[stream, request])
  169. 2913 stream.on(:data, &method(:on_stream_data).curry(3)[stream, request])
  170. end
  171. 24 def set_protocol_headers(request)
  172. 371 {
  173. 2520 ":scheme" => request.scheme,
  174. ":method" => request.verb,
  175. ":path" => request.path,
  176. ":authority" => request.authority,
  177. }
  178. end
  179. 24 def join_headers(stream, request)
  180. 2892 extra_headers = set_protocol_headers(request)
  181. 2892 if request.headers.key?("host")
  182. 7 log { "forbidden \"host\" header found (#{request.headers["host"]}), will use it as authority..." }
  183. 6 extra_headers[":authority"] = request.headers["host"]
  184. end
  185. 2892 log(level: 1, color: :yellow) do
  186. 110 request.headers.merge(extra_headers).each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{v}" }.join("\n")
  187. end
  188. 2892 stream.headers(request.headers.each(extra_headers), end_stream: request.body.empty?)
  189. end
  190. 24 def join_trailers(stream, request)
  191. 1187 unless request.trailers?
  192. 1180 stream.data("", end_stream: true) if request.callbacks_for?(:trailers)
  193. 1036 return
  194. end
  195. 7 log(level: 1, color: :yellow) do
  196. 13 request.trailers.each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{v}" }.join("\n")
  197. end
  198. 7 stream.headers(request.trailers.each, end_stream: true)
  199. end
  200. 24 def join_body(stream, request)
  201. 3650 return if request.body.empty?
  202. 1945 chunk = @drains.delete(request) || request.drain_body
  203. 2120 while chunk
  204. 2283 next_chunk = request.drain_body
  205. 2301 log(level: 1, color: :green) { "#{stream.id}: -> DATA: #{chunk.bytesize} bytes..." }
  206. 2301 log(level: 2, color: :green) { "#{stream.id}: -> #{chunk.inspect}" }
  207. 2283 stream.data(chunk, end_stream: !(next_chunk || request.trailers? || request.callbacks_for?(:trailers)))
  208. 2283 if next_chunk && (@buffer.full? || request.body.unbounded_body?)
  209. 654 @drains[request] = next_chunk
  210. 758 throw(:buffer_full)
  211. end
  212. 1525 chunk = next_chunk
  213. end
  214. 1187 return unless (error = request.drain_error)
  215. 10 on_stream_refuse(stream, request, error)
  216. end
  217. ######
  218. # HTTP/2 Callbacks
  219. ######
  220. 24 def on_stream_headers(stream, request, h)
  221. 2871 response = request.response
  222. 2871 if response.is_a?(Response) && response.version == "2.0"
  223. 95 on_stream_trailers(stream, response, h)
  224. 95 return
  225. end
  226. 2776 log(color: :yellow) do
  227. 110 h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{v}" }.join("\n")
  228. end
  229. 2776 _, status = h.shift
  230. 2776 headers = request.options.headers_class.new(h)
  231. 2776 response = request.options.response_class.new(request, status, "2.0", headers)
  232. 2776 request.response = response
  233. 2414 @streams[request] = stream
  234. 2769 handle(request, stream) if request.expects?
  235. end
  236. 24 def on_stream_trailers(stream, response, h)
  237. 95 log(color: :yellow) do
  238. h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{v}" }.join("\n")
  239. end
  240. 95 response.merge_headers(h)
  241. end
  242. 24 def on_stream_data(stream, request, data)
  243. 5206 log(level: 1, color: :green) { "#{stream.id}: <- DATA: #{data.bytesize} bytes..." }
  244. 5206 log(level: 2, color: :green) { "#{stream.id}: <- #{data.inspect}" }
  245. 5186 request.response << data
  246. end
  247. 24 def on_stream_refuse(stream, request, error)
  248. 10 on_stream_close(stream, request, error)
  249. 10 stream.close
  250. end
  251. 24 def on_stream_close(stream, request, error)
  252. 2702 return if error == :stream_closed && !@streams.key?(request)
  253. 2704 log(level: 2) { "#{stream.id}: closing stream" }
  254. 2692 @drains.delete(request)
  255. 2692 @streams.delete(request)
  256. 2692 if error
  257. 10 ex = Error.new(stream.id, error)
  258. 10 ex.set_backtrace(caller)
  259. 10 response = ErrorResponse.new(request, ex)
  260. 10 request.response = response
  261. 10 emit(:response, request, response)
  262. else
  263. 2682 response = request.response
  264. 2682 if response && response.is_a?(Response) && response.status == 421
  265. 7 ex = MisdirectedRequestError.new(response)
  266. 7 ex.set_backtrace(caller)
  267. 7 emit(:error, request, ex)
  268. else
  269. 2675 emit(:response, request, response)
  270. end
  271. end
  272. 2685 send(@pending.shift) unless @pending.empty?
  273. 2685 return unless @streams.empty? && exhausted?
  274. 7 close
  275. 7 emit(:exhausted) unless @pending.empty?
  276. end
  277. 24 def on_frame(bytes)
  278. 16221 @buffer << bytes
  279. end
  280. 24 def on_settings(*)
  281. 2537 @handshake_completed = true
  282. 2537 emit(:current_timeout)
  283. 2537 @max_concurrent_requests = [@max_concurrent_requests, @connection.remote_settings[:settings_max_concurrent_streams]].min
  284. 2537 send_pending
  285. end
  286. 24 def on_close(_last_frame, error, _payload)
  287. 19 is_connection_closed = @connection.state == :closed
  288. 19 if error
  289. 19 @buffer.clear if is_connection_closed
  290. 19 if error == :no_error
  291. 13 ex = GoawayError.new
  292. 13 @pending.unshift(*@streams.keys)
  293. 13 @drains.clear
  294. 13 @streams.clear
  295. else
  296. 6 ex = Error.new(0, error)
  297. end
  298. 19 ex.set_backtrace(caller)
  299. 19 handle_error(ex)
  300. end
  301. 19 return unless is_connection_closed && @streams.empty?
  302. 19 emit(:close, is_connection_closed)
  303. end
  304. 24 def on_frame_sent(frame)
  305. 13719 log(level: 2) { "#{frame[:stream]}: frame was sent!" }
  306. 13647 log(level: 2, color: :blue) do
  307. 84 payload = frame
  308. 84 payload = payload.merge(payload: frame[:payload].bytesize) if frame[:type] == :data
  309. 72 "#{frame[:stream]}: #{payload}"
  310. end
  311. end
  312. 24 def on_frame_received(frame)
  313. 14317 log(level: 2) { "#{frame[:stream]}: frame was received!" }
  314. 14261 log(level: 2, color: :magenta) do
  315. 65 payload = frame
  316. 65 payload = payload.merge(payload: frame[:payload].bytesize) if frame[:type] == :data
  317. 56 "#{frame[:stream]}: #{payload}"
  318. end
  319. end
  320. 24 def on_altsvc(origin, frame)
  321. log(level: 2) { "#{frame[:stream]}: altsvc frame was received" }
  322. log(level: 2) { "#{frame[:stream]}: #{frame.inspect}" }
  323. alt_origin = URI.parse("#{frame[:proto]}://#{frame[:host]}:#{frame[:port]}")
  324. params = { "ma" => frame[:max_age] }
  325. emit(:altsvc, origin, alt_origin, origin, params)
  326. end
  327. 24 def on_promise(stream)
  328. 21 emit(:promise, @streams.key(stream.parent), stream)
  329. end
  330. 24 def on_origin(origin)
  331. emit(:origin, origin)
  332. end
  333. 24 def on_pong(ping)
  334. 7 if @pings.delete(ping.to_s)
  335. 7 emit(:pong)
  336. else
  337. close(:protocol_error, "ping payload did not match")
  338. end
  339. end
  340. end
  341. end

lib/httpx/domain_name.rb

95.56% lines covered

45 relevant lines. 43 lines covered and 2 lines missed.
    
  1. # frozen_string_literal: true
  2. #
  3. # domain_name.rb - Domain Name manipulation library for Ruby
  4. #
  5. # Copyright (C) 2011-2017 Akinori MUSHA, All rights reserved.
  6. #
  7. # Redistribution and use in source and binary forms, with or without
  8. # modification, are permitted provided that the following conditions
  9. # are met:
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # 2. Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in the
  14. # documentation and/or other materials provided with the distribution.
  15. #
  16. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  17. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  19. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  20. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  22. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  23. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  24. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  25. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  26. # SUCH DAMAGE.
  27. 24 require "ipaddr"
  28. 24 module HTTPX
  29. # Represents a domain name ready for extracting its registered domain
  30. # and TLD.
  31. 24 class DomainName
  32. 24 include Comparable
  33. # The full host name normalized, ASCII-ized and downcased using the
  34. # Unicode NFC rules and the Punycode algorithm. If initialized with
  35. # an IP address, the string representation of the IP address
  36. # suitable for opening a connection to.
  37. 24 attr_reader :hostname
  38. # The Unicode representation of the #hostname property.
  39. #
  40. # :attr_reader: hostname_idn
  41. # The least "universally original" domain part of this domain name.
  42. # For example, "example.co.uk" for "www.sub.example.co.uk". This
  43. # may be nil if the hostname does not have one, like when it is an
  44. # IP address, an effective TLD or higher itself, or of a
  45. # non-canonical domain.
  46. 24 attr_reader :domain
  47. 24 class << self
  48. 24 def new(domain)
  49. 749 return domain if domain.is_a?(self)
  50. 693 super(domain)
  51. end
  52. # Normalizes a _domain_ using the Punycode algorithm as necessary.
  53. # The result will be a downcased, ASCII-only string.
  54. 24 def normalize(domain)
  55. 665 unless domain.ascii_only?
  56. domain = domain.chomp(".").unicode_normalize(:nfc)
  57. domain = Punycode.encode_hostname(domain)
  58. end
  59. 665 domain.downcase
  60. end
  61. end
  62. # Parses _hostname_ into a DomainName object. An IP address is also
  63. # accepted. An IPv6 address may be enclosed in square brackets.
  64. 24 def initialize(hostname)
  65. 693 hostname = String(hostname)
  66. 693 raise ArgumentError, "domain name must not start with a dot: #{hostname}" if hostname.start_with?(".")
  67. 98 begin
  68. 693 @ipaddr = IPAddr.new(hostname)
  69. 28 @hostname = @ipaddr.to_s
  70. 28 return
  71. rescue IPAddr::Error
  72. 665 nil
  73. end
  74. 665 @hostname = DomainName.normalize(hostname)
  75. 665 tld = if (last_dot = @hostname.rindex("."))
  76. 161 @hostname[(last_dot + 1)..-1]
  77. else
  78. 504 @hostname
  79. end
  80. # unknown/local TLD
  81. 665 @domain = if last_dot
  82. # fallback - accept cookies down to second level
  83. # cf. http://www.dkim-reputation.org/regdom-libs/
  84. 161 if (penultimate_dot = @hostname.rindex(".", last_dot - 1))
  85. 42 @hostname[(penultimate_dot + 1)..-1]
  86. else
  87. 119 @hostname
  88. end
  89. else
  90. # no domain part - must be a local hostname
  91. 504 tld
  92. end
  93. end
  94. # Checks if the server represented by this domain is qualified to
  95. # send and receive cookies with a domain attribute value of
  96. # _domain_. A true value given as the second argument represents
  97. # cookies without a domain attribute value, in which case only
  98. # hostname equality is checked.
  99. 24 def cookie_domain?(domain, host_only = false)
  100. # RFC 6265 #5.3
  101. # When the user agent "receives a cookie":
  102. 28 return self == @domain if host_only
  103. 28 domain = DomainName.new(domain)
  104. # RFC 6265 #5.1.3
  105. # Do not perform subdomain matching against IP addresses.
  106. 28 @hostname == domain.hostname if @ipaddr
  107. # RFC 6265 #4.1.1
  108. # Domain-value must be a subdomain.
  109. 28 @domain && self <= domain && domain <= @domain
  110. end
  111. 24 def <=>(other)
  112. 42 other = DomainName.new(other)
  113. 42 othername = other.hostname
  114. 42 if othername == @hostname
  115. 14 0
  116. 27 elsif @hostname.end_with?(othername) && @hostname[-othername.size - 1, 1] == "."
  117. # The other is higher
  118. 14 -1
  119. else
  120. # The other is lower
  121. 14 1
  122. end
  123. end
  124. end
  125. end

lib/httpx/errors.rb

97.56% lines covered

41 relevant lines. 40 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. # the default exception class for exceptions raised by HTTPX.
  4. 24 class Error < StandardError; end
  5. 24 class UnsupportedSchemeError < Error; end
  6. 24 class ConnectionError < Error; end
  7. # Error raised when there was a timeout. Its subclasses allow for finer-grained
  8. # control of which timeout happened.
  9. 24 class TimeoutError < Error
  10. # The timeout value which caused this error to be raised.
  11. 24 attr_reader :timeout
  12. # initializes the timeout exception with the +timeout+ causing the error, and the
  13. # error +message+ for it.
  14. 24 def initialize(timeout, message)
  15. 440 @timeout = timeout
  16. 440 super(message)
  17. end
  18. # clones this error into a HTTPX::ConnectionTimeoutError.
  19. 24 def to_connection_error
  20. 21 ex = ConnectTimeoutError.new(@timeout, message)
  21. 21 ex.set_backtrace(backtrace)
  22. 21 ex
  23. end
  24. end
  25. # Error raised when there was a timeout establishing the connection to a server.
  26. # This may be raised due to timeouts during TCP and TLS (when applicable) connection
  27. # establishment.
  28. 24 class ConnectTimeoutError < TimeoutError; end
  29. # Error raised when there was a timeout while sending a request, or receiving a response
  30. # from the server.
  31. 24 class RequestTimeoutError < TimeoutError
  32. # The HTTPX::Request request object this exception refers to.
  33. 24 attr_reader :request
  34. # initializes the exception with the +request+ and +response+ it refers to, and the
  35. # +timeout+ causing the error, and the
  36. 24 def initialize(request, response, timeout)
  37. 358 @request = request
  38. 358 @response = response
  39. 358 super(timeout, "Timed out after #{timeout} seconds")
  40. end
  41. 24 def marshal_dump
  42. [message]
  43. end
  44. end
  45. # Error raised when there was a timeout while receiving a response from the server.
  46. 24 class ReadTimeoutError < RequestTimeoutError; end
  47. # Error raised when there was a timeout while sending a request from the server.
  48. 24 class WriteTimeoutError < RequestTimeoutError; end
  49. # Error raised when there was a timeout while waiting for the HTTP/2 settings frame from the server.
  50. 24 class SettingsTimeoutError < TimeoutError; end
  51. # Error raised when there was a timeout while resolving a domain to an IP.
  52. 24 class ResolveTimeoutError < TimeoutError; end
  53. # Error raised when there was an error while resolving a domain to an IP.
  54. 24 class ResolveError < Error; end
  55. # Error raised when there was an error while resolving a domain to an IP
  56. # using a HTTPX::Resolver::Native resolver.
  57. 24 class NativeResolveError < ResolveError
  58. 24 attr_reader :connection, :host
  59. # initializes the exception with the +connection+ it refers to, the +host+ domain
  60. # which failed to resolve, and the error +message+.
  61. 24 def initialize(connection, host, message = "Can't resolve #{host}")
  62. 103 @connection = connection
  63. 103 @host = host
  64. 103 super(message)
  65. end
  66. end
  67. # The exception class for HTTP responses with 4xx or 5xx status.
  68. 24 class HTTPError < Error
  69. # The HTTPX::Response response object this exception refers to.
  70. 24 attr_reader :response
  71. # Creates the instance and assigns the HTTPX::Response +response+.
  72. 24 def initialize(response)
  73. 83 @response = response
  74. 83 super("HTTP Error: #{@response.status} #{@response.headers}\n#{@response.body}")
  75. end
  76. # The HTTP response status.
  77. #
  78. # error.status #=> 404
  79. 24 def status
  80. 14 @response.status
  81. end
  82. end
  83. # error raised when a request was sent a server which can't reproduce a response, and
  84. # has therefore returned an HTTP response using the 421 status code.
  85. 24 class MisdirectedRequestError < HTTPError; end
  86. end

lib/httpx/extensions.rb

67.86% lines covered

28 relevant lines. 19 lines covered and 9 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "uri"
  3. 24 module HTTPX
  4. 24 module ArrayExtensions
  5. 24 module FilterMap
  6. refine Array do
  7. # Ruby 2.7 backport
  8. def filter_map
  9. return to_enum(:filter_map) unless block_given?
  10. each_with_object([]) do |item, res|
  11. processed = yield(item)
  12. res << processed if processed
  13. end
  14. end
  15. 23 end unless Array.method_defined?(:filter_map)
  16. end
  17. 24 module Intersect
  18. refine Array do
  19. # Ruby 3.1 backport
  20. 4 def intersect?(arr)
  21. if size < arr.size
  22. smaller = self
  23. else
  24. smaller, arr = arr, self
  25. end
  26. (arr & smaller).size > 0
  27. end
  28. 23 end unless Array.method_defined?(:intersect?)
  29. end
  30. end
  31. 24 module URIExtensions
  32. # uri 0.11 backport, ships with ruby 3.1
  33. 24 refine URI::Generic do
  34. 24 def non_ascii_hostname
  35. 365 @non_ascii_hostname
  36. end
  37. 24 def non_ascii_hostname=(hostname)
  38. 28 @non_ascii_hostname = hostname
  39. end
  40. def authority
  41. 7071 return host if port == default_port
  42. 533 "#{host}:#{port}"
  43. 23 end unless URI::HTTP.method_defined?(:authority)
  44. def origin
  45. 6112 "#{scheme}://#{authority}"
  46. 23 end unless URI::HTTP.method_defined?(:origin)
  47. end
  48. end
  49. end

lib/httpx/headers.rb

100.0% lines covered

71 relevant lines. 71 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 class Headers
  4. 24 class << self
  5. 24 def new(headers = nil)
  6. 20632 return headers if headers.is_a?(self)
  7. 9624 super
  8. end
  9. end
  10. 24 def initialize(headers = nil)
  11. 9624 @headers = {}
  12. 9624 return unless headers
  13. 9467 headers.each do |field, value|
  14. 49066 array_value(value).each do |v|
  15. 49115 add(downcased(field), v)
  16. end
  17. end
  18. end
  19. # cloned initialization
  20. 24 def initialize_clone(orig)
  21. 7 super
  22. 7 @headers = orig.instance_variable_get(:@headers).clone
  23. end
  24. # dupped initialization
  25. 24 def initialize_dup(orig)
  26. 11946 super
  27. 11946 @headers = orig.instance_variable_get(:@headers).dup
  28. end
  29. # freezes the headers hash
  30. 24 def freeze
  31. 12960 @headers.freeze
  32. 12960 super
  33. end
  34. 24 def same_headers?(headers)
  35. 28 @headers.empty? || begin
  36. 28 headers.each do |k, v|
  37. 63 next unless key?(k)
  38. 63 return false unless v == self[k]
  39. end
  40. 14 true
  41. end
  42. end
  43. # merges headers with another header-quack.
  44. # the merge rule is, if the header already exists,
  45. # ignore what the +other+ headers has. Otherwise, set
  46. #
  47. 24 def merge(other)
  48. 3700 headers = dup
  49. 3700 other.each do |field, value|
  50. 2856 headers[downcased(field)] = value
  51. end
  52. 3700 headers
  53. end
  54. # returns the comma-separated values of the header field
  55. # identified by +field+, or nil otherwise.
  56. #
  57. 24 def [](field)
  58. 72740 a = @headers[downcased(field)] || return
  59. 21863 a.join(", ")
  60. end
  61. # sets +value+ (if not nil) as single value for the +field+ header.
  62. #
  63. 24 def []=(field, value)
  64. 32170 return unless value
  65. 28394 @headers[downcased(field)] = array_value(value)
  66. end
  67. # deletes all values associated with +field+ header.
  68. #
  69. 24 def delete(field)
  70. 225 canonical = downcased(field)
  71. 225 @headers.delete(canonical) if @headers.key?(canonical)
  72. end
  73. # adds additional +value+ to the existing, for header +field+.
  74. #
  75. 24 def add(field, value)
  76. 49493 (@headers[downcased(field)] ||= []) << String(value)
  77. end
  78. # helper to be used when adding an header field as a value to another field
  79. #
  80. # h2_headers.add_header("vary", "accept-encoding")
  81. # h2_headers["vary"] #=> "accept-encoding"
  82. # h1_headers.add_header("vary", "accept-encoding")
  83. # h1_headers["vary"] #=> "Accept-Encoding"
  84. #
  85. 24 alias_method :add_header, :add
  86. # returns the enumerable headers store in pairs of header field + the values in
  87. # the comma-separated string format
  88. #
  89. 24 def each(extra_headers = nil)
  90. 51851 return enum_for(__method__, extra_headers) { @headers.size } unless block_given?
  91. 27675 @headers.each do |field, value|
  92. 35572 yield(field, value.join(", ")) unless value.empty?
  93. end
  94. 6046 extra_headers.each do |field, value|
  95. 19567 yield(field, value) unless value.empty?
  96. 27660 end if extra_headers
  97. end
  98. 24 def ==(other)
  99. 16080 other == to_hash
  100. end
  101. # the headers store in Hash format
  102. 24 def to_hash
  103. 17124 Hash[to_a]
  104. end
  105. 24 alias_method :to_h, :to_hash
  106. # the headers store in array of pairs format
  107. 24 def to_a
  108. 17144 Array(each)
  109. end
  110. # headers as string
  111. 24 def to_s
  112. 1608 @headers.to_s
  113. end
  114. skipped # :nocov:
  115. skipped def inspect
  116. skipped to_hash.inspect
  117. skipped end
  118. skipped # :nocov:
  119. # this is internal API and doesn't abide to other public API
  120. # guarantees, like downcasing strings.
  121. # Please do not use this outside of core!
  122. #
  123. 24 def key?(downcased_key)
  124. 50875 @headers.key?(downcased_key)
  125. end
  126. # returns the values for the +field+ header in array format.
  127. # This method is more internal, and for this reason doesn't try
  128. # to "correct" the user input, i.e. it doesn't downcase the key.
  129. #
  130. 24 def get(field)
  131. 221 @headers[field] || EMPTY
  132. end
  133. 24 private
  134. 24 def array_value(value)
  135. 71343 case value
  136. when Array
  137. 77827 value.map { |val| String(val).strip }
  138. else
  139. 46323 [String(value).strip]
  140. end
  141. end
  142. 24 def downcased(field)
  143. 206942 String(field).downcase
  144. end
  145. end
  146. end

lib/httpx/io.rb

100.0% lines covered

5 relevant lines. 5 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "socket"
  3. 24 require "httpx/io/udp"
  4. 24 require "httpx/io/tcp"
  5. 24 require "httpx/io/unix"
  6. begin
  7. 24 require "httpx/io/ssl"
  8. rescue LoadError
  9. end

lib/httpx/io/ssl.rb

96.47% lines covered

85 relevant lines. 82 lines covered and 3 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "openssl"
  3. 24 module HTTPX
  4. 24 TLSError = OpenSSL::SSL::SSLError
  5. 24 class SSL < TCP
  6. # rubocop:disable Style/MutableConstant
  7. 24 TLS_OPTIONS = { alpn_protocols: %w[h2 http/1.1].freeze }
  8. # https://github.com/jruby/jruby-openssl/issues/284
  9. 24 TLS_OPTIONS[:verify_hostname] = true if RUBY_ENGINE == "jruby"
  10. # rubocop:enable Style/MutableConstant
  11. 24 TLS_OPTIONS.freeze
  12. 24 attr_writer :ssl_session
  13. 24 def initialize(_, _, options)
  14. 2509 super
  15. 2509 ctx_options = TLS_OPTIONS.merge(options.ssl)
  16. 2509 @sni_hostname = ctx_options.delete(:hostname) || @hostname
  17. 2509 if @keep_open && @io.is_a?(OpenSSL::SSL::SSLSocket)
  18. # externally initiated ssl socket
  19. 19 @ctx = @io.context
  20. 19 @state = :negotiated
  21. else
  22. 2490 @ctx = OpenSSL::SSL::SSLContext.new
  23. 2490 @ctx.set_params(ctx_options) unless ctx_options.empty?
  24. 2490 unless @ctx.session_cache_mode.nil? # a dummy method on JRuby
  25. 2170 @ctx.session_cache_mode =
  26. OpenSSL::SSL::SSLContext::SESSION_CACHE_CLIENT | OpenSSL::SSL::SSLContext::SESSION_CACHE_NO_INTERNAL_STORE
  27. end
  28. 2490 yield(self) if block_given?
  29. end
  30. 2509 @verify_hostname = @ctx.verify_hostname
  31. end
  32. 24 if OpenSSL::SSL::SSLContext.method_defined?(:session_new_cb=)
  33. 23 def session_new_cb(&pr)
  34. 6149 @ctx.session_new_cb = proc { |_, sess| pr.call(sess) }
  35. end
  36. else
  37. # session_new_cb not implemented under JRuby
  38. 1 def session_new_cb; end
  39. end
  40. 24 def protocol
  41. 2255 @io.alpn_protocol || super
  42. rescue StandardError
  43. 6 super
  44. end
  45. 24 if RUBY_ENGINE == "jruby"
  46. # in jruby, alpn_protocol may return ""
  47. # https://github.com/jruby/jruby-openssl/issues/287
  48. 1 def protocol
  49. 332 proto = @io.alpn_protocol
  50. 331 return super if proto.nil? || proto.empty?
  51. 330 proto
  52. rescue StandardError
  53. 1 super
  54. end
  55. end
  56. 24 def can_verify_peer?
  57. 11 @ctx.verify_mode == OpenSSL::SSL::VERIFY_PEER
  58. end
  59. 24 def verify_hostname(host)
  60. 13 return false if @ctx.verify_mode == OpenSSL::SSL::VERIFY_NONE
  61. 13 return false if !@io.respond_to?(:peer_cert) || @io.peer_cert.nil?
  62. 13 OpenSSL::SSL.verify_certificate_identity(@io.peer_cert, host)
  63. end
  64. 24 def connected?
  65. 9502 @state == :negotiated
  66. end
  67. 24 def expired?
  68. super || ssl_session_expired?
  69. end
  70. 24 def ssl_session_expired?
  71. 2552 @ssl_session.nil? || Process.clock_gettime(Process::CLOCK_REALTIME) >= (@ssl_session.time.to_f + @ssl_session.timeout)
  72. end
  73. 24 def connect
  74. 9545 super
  75. 9523 return if @state == :negotiated ||
  76. @state != :connected
  77. 6670 unless @io.is_a?(OpenSSL::SSL::SSLSocket)
  78. 2552 if (hostname_is_ip = (@ip == @sni_hostname))
  79. # IPv6 address would be "[::1]", must turn to "0000:0000:0000:0000:0000:0000:0000:0001" for cert SAN check
  80. 28 @sni_hostname = @ip.to_string
  81. # IP addresses in SNI is not valid per RFC 6066, section 3.
  82. 28 @ctx.verify_hostname = false
  83. end
  84. 2552 @io = OpenSSL::SSL::SSLSocket.new(@io, @ctx)
  85. 2552 @io.hostname = @sni_hostname unless hostname_is_ip
  86. 2552 @io.session = @ssl_session unless ssl_session_expired?
  87. 2552 @io.sync_close = true
  88. end
  89. 6670 try_ssl_connect
  90. end
  91. 24 def try_ssl_connect
  92. 6670 ret = @io.connect_nonblock(exception: false)
  93. 6681 log(level: 3, color: :cyan) { "TLS CONNECT: #{ret}..." }
  94. 5957 case ret
  95. when :wait_readable
  96. 4139 @interests = :r
  97. 4139 return
  98. when :wait_writable
  99. @interests = :w
  100. return
  101. end
  102. 2511 @io.post_connection_check(@sni_hostname) if @ctx.verify_mode != OpenSSL::SSL::VERIFY_NONE && @verify_hostname
  103. 2510 transition(:negotiated)
  104. 2510 @interests = :w
  105. end
  106. 24 private
  107. 24 def transition(nextstate)
  108. 8644 case nextstate
  109. when :negotiated
  110. 2510 return unless @state == :connected
  111. when :closed
  112. 2478 return unless @state == :negotiated ||
  113. @state == :connected
  114. end
  115. 9958 do_transition(nextstate)
  116. end
  117. 24 def log_transition_state(nextstate)
  118. 61 return super unless nextstate == :negotiated
  119. 14 server_cert = @io.peer_cert
  120. 12 "#{super}\n\n" \
  121. 2 "SSL connection using #{@io.ssl_version} / #{Array(@io.cipher).first}\n" \
  122. 2 "ALPN, server accepted to use #{protocol}\n" \
  123. "Server certificate:\n " \
  124. 2 "subject: #{server_cert.subject}\n " \
  125. 2 "start date: #{server_cert.not_before}\n " \
  126. 2 "expire date: #{server_cert.not_after}\n " \
  127. 2 "issuer: #{server_cert.issuer}\n " \
  128. "SSL certificate verify ok."
  129. end
  130. end
  131. end

lib/httpx/io/tcp.rb

91.15% lines covered

113 relevant lines. 103 lines covered and 10 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "resolv"
  3. 24 require "ipaddr"
  4. 24 module HTTPX
  5. 24 class TCP
  6. 24 include Loggable
  7. 24 using URIExtensions
  8. 24 attr_reader :ip, :port, :addresses, :state, :interests
  9. 24 alias_method :host, :ip
  10. 24 def initialize(origin, addresses, options)
  11. 5685 @state = :idle
  12. 5685 @addresses = []
  13. 5685 @hostname = origin.host
  14. 5685 @options = options
  15. 5685 @fallback_protocol = @options.fallback_protocol
  16. 5685 @port = origin.port
  17. 5685 @interests = :w
  18. 5685 if @options.io
  19. 45 @io = case @options.io
  20. when Hash
  21. 14 @options.io[origin.authority]
  22. else
  23. 31 @options.io
  24. end
  25. 45 raise Error, "Given IO objects do not match the request authority" unless @io
  26. 45 _, _, _, @ip = @io.addr
  27. 45 @addresses << @ip
  28. 45 @keep_open = true
  29. 45 @state = :connected
  30. else
  31. 5640 add_addresses(addresses)
  32. end
  33. 5685 @ip_index = @addresses.size - 1
  34. end
  35. 24 def socket
  36. 171 @io
  37. end
  38. 24 def add_addresses(addrs)
  39. 5819 return if addrs.empty?
  40. 18725 addrs = addrs.map { |addr| addr.is_a?(IPAddr) ? addr : IPAddr.new(addr) }
  41. 5819 ip_index = @ip_index || (@addresses.size - 1)
  42. 5819 if addrs.first.ipv6?
  43. # should be the next in line
  44. 189 @addresses = [*@addresses[0, ip_index], *addrs, *@addresses[ip_index..-1]]
  45. else
  46. 5630 @addresses.unshift(*addrs)
  47. 5630 @ip_index += addrs.size if @ip_index
  48. end
  49. end
  50. 24 def to_io
  51. 19201 @io.to_io
  52. end
  53. 24 def protocol
  54. 3492 @fallback_protocol
  55. end
  56. 24 def connect
  57. 19814 return unless closed?
  58. 15507 if !@io || @io.closed?
  59. 6124 transition(:idle)
  60. 6124 @io = build_socket
  61. end
  62. 15507 try_connect
  63. rescue Errno::ECONNREFUSED,
  64. Errno::EADDRNOTAVAIL,
  65. Errno::EHOSTUNREACH,
  66. SocketError,
  67. IOError => e
  68. 430 raise e if @ip_index <= 0
  69. 382 log { "failed connecting to #{@ip} (#{e.message}), trying next..." }
  70. 364 @ip_index -= 1
  71. 372 @io = build_socket
  72. 372 retry
  73. rescue Errno::ETIMEDOUT => e
  74. raise ConnectTimeoutError.new(@options.timeout[:connect_timeout], e.message) if @ip_index <= 0
  75. log { "failed connecting to #{@ip} (#{e.message}), trying next..." }
  76. @ip_index -= 1
  77. @io = build_socket
  78. retry
  79. end
  80. 24 def try_connect
  81. 15507 ret = @io.connect_nonblock(Socket.sockaddr_in(@port, @ip.to_s), exception: false)
  82. 12642 log(level: 3, color: :cyan) { "TCP CONNECT: #{ret}..." }
  83. 10958 case ret
  84. when :wait_readable
  85. @interests = :r
  86. return
  87. when :wait_writable
  88. 6486 @interests = :w
  89. 6486 return
  90. end
  91. 6066 transition(:connected)
  92. 6066 @interests = :w
  93. rescue Errno::EALREADY
  94. 2525 @interests = :w
  95. end
  96. 24 private :try_connect
  97. 24 def read(size, buffer)
  98. 40433 ret = @io.read_nonblock(size, buffer, exception: false)
  99. 40433 if ret == :wait_readable
  100. 7990 buffer.clear
  101. 7261 return 0
  102. end
  103. 32443 return if ret.nil?
  104. 32505 log { "READ: #{buffer.bytesize} bytes..." }
  105. 32430 buffer.bytesize
  106. end
  107. 24 def write(buffer)
  108. 17085 siz = @io.write_nonblock(buffer, exception: false)
  109. 17061 return 0 if siz == :wait_writable
  110. 17040 return if siz.nil?
  111. 17116 log { "WRITE: #{siz} bytes..." }
  112. 17040 buffer.shift!(siz)
  113. 17040 siz
  114. end
  115. 24 def close
  116. 6691 return if @keep_open || closed?
  117. 777 begin
  118. 5958 @io.close
  119. ensure
  120. 5958 transition(:closed)
  121. end
  122. end
  123. 24 def connected?
  124. 9873 @state == :connected
  125. end
  126. 24 def closed?
  127. 26466 @state == :idle || @state == :closed
  128. end
  129. 24 def expired?
  130. # do not mess with external sockets
  131. return false if @options.io
  132. return true unless @addresses
  133. resolver_addresses = Resolver.nolookup_resolve(@hostname)
  134. (Array(resolver_addresses) & @addresses).empty?
  135. end
  136. skipped # :nocov:
  137. skipped def inspect
  138. skipped "#<#{self.class}: #{@ip}:#{@port} (state: #{@state})>"
  139. skipped end
  140. skipped # :nocov:
  141. 24 private
  142. 24 def build_socket
  143. 6496 @ip = @addresses[@ip_index]
  144. 6496 Socket.new(@ip.family, :STREAM, 0)
  145. end
  146. 24 def transition(nextstate)
  147. 9327 case nextstate
  148. # when :idle
  149. when :connected
  150. 3604 return unless @state == :idle
  151. when :closed
  152. 3480 return unless @state == :connected
  153. end
  154. 10718 do_transition(nextstate)
  155. end
  156. 24 def do_transition(nextstate)
  157. 20805 log(level: 1) { log_transition_state(nextstate) }
  158. 20676 @state = nextstate
  159. end
  160. 24 def log_transition_state(nextstate)
  161. 112 case nextstate
  162. when :connected
  163. 35 "Connected to #{host} (##{@io.fileno})"
  164. else
  165. 82 "#{host} #{@state} -> #{nextstate}"
  166. end
  167. end
  168. end
  169. end

lib/httpx/io/udp.rb

100.0% lines covered

35 relevant lines. 35 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "ipaddr"
  3. 24 module HTTPX
  4. 24 class UDP
  5. 24 include Loggable
  6. 24 def initialize(ip, port, options)
  7. 460 @host = ip
  8. 460 @port = port
  9. 460 @io = UDPSocket.new(IPAddr.new(ip).family)
  10. 460 @options = options
  11. end
  12. 24 def to_io
  13. 1025 @io.to_io
  14. end
  15. 24 def connect; end
  16. 24 def connected?
  17. 460 true
  18. end
  19. 24 def close
  20. 624 @io.close
  21. end
  22. 24 if RUBY_ENGINE == "jruby"
  23. # In JRuby, sendmsg_nonblock is not implemented
  24. 1 def write(buffer)
  25. 52 siz = @io.send(buffer.to_s, 0, @host, @port)
  26. 52 log { "WRITE: #{siz} bytes..." }
  27. 52 buffer.shift!(siz)
  28. 52 siz
  29. end
  30. else
  31. 23 def write(buffer)
  32. 541 siz = @io.sendmsg_nonblock(buffer.to_s, 0, Socket.sockaddr_in(@port, @host.to_s), exception: false)
  33. 541 return 0 if siz == :wait_writable
  34. 541 return if siz.nil?
  35. 541 log { "WRITE: #{siz} bytes..." }
  36. 541 buffer.shift!(siz)
  37. 541 siz
  38. end
  39. end
  40. 24 def read(size, buffer)
  41. 809 ret = @io.recvfrom_nonblock(size, 0, buffer, exception: false)
  42. 809 return 0 if ret == :wait_readable
  43. 548 return if ret.nil?
  44. 548 log { "READ: #{buffer.bytesize} bytes..." }
  45. 548 buffer.bytesize
  46. rescue IOError
  47. end
  48. end
  49. end

lib/httpx/io/unix.rb

94.29% lines covered

35 relevant lines. 33 lines covered and 2 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 class UNIX < TCP
  4. 24 using URIExtensions
  5. 24 attr_reader :path
  6. 24 alias_method :host, :path
  7. 24 def initialize(origin, path, options)
  8. 24 @addresses = []
  9. 24 @hostname = origin.host
  10. 24 @state = :idle
  11. 24 @options = options
  12. 24 @fallback_protocol = @options.fallback_protocol
  13. 24 if @options.io
  14. 12 @io = case @options.io
  15. when Hash
  16. 6 @options.io[origin.authority]
  17. else
  18. 6 @options.io
  19. end
  20. 12 raise Error, "Given IO objects do not match the request authority" unless @io
  21. 12 @path = @io.path
  22. 12 @keep_open = true
  23. 12 @state = :connected
  24. 12 elsif path
  25. 12 @path = path
  26. else
  27. raise Error, "No path given where to store the socket"
  28. end
  29. 24 @io ||= build_socket
  30. end
  31. 24 def connect
  32. 18 return unless closed?
  33. begin
  34. 18 if @io.closed?
  35. 6 transition(:idle)
  36. 6 @io = build_socket
  37. end
  38. 18 @io.connect_nonblock(Socket.sockaddr_un(@path))
  39. rescue Errno::EISCONN
  40. end
  41. 12 transition(:connected)
  42. rescue Errno::EINPROGRESS,
  43. Errno::EALREADY,
  44. ::IO::WaitReadable
  45. end
  46. 24 def expired?
  47. false
  48. end
  49. skipped # :nocov:
  50. skipped def inspect
  51. skipped "#<#{self.class}(path: #{@path}): (state: #{@state})>"
  52. skipped end
  53. skipped # :nocov:
  54. 24 private
  55. 24 def build_socket
  56. 18 Socket.new(Socket::PF_UNIX, :STREAM, 0)
  57. end
  58. end
  59. end

lib/httpx/loggable.rb

100.0% lines covered

14 relevant lines. 14 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 module Loggable
  4. 24 COLORS = {
  5. black: 30,
  6. red: 31,
  7. green: 32,
  8. yellow: 33,
  9. blue: 34,
  10. magenta: 35,
  11. cyan: 36,
  12. white: 37,
  13. }.freeze
  14. 24 def log(level: @options.debug_level, color: nil, &msg)
  15. 316054 return unless @options.debug
  16. 1424 return unless @options.debug_level >= level
  17. 1424 debug_stream = @options.debug
  18. 1424 message = (+"" << msg.call << "\n")
  19. 1424 message = "\e[#{COLORS[color]}m#{message}\e[0m" if color && debug_stream.respond_to?(:isatty) && debug_stream.isatty
  20. 1424 debug_stream << message
  21. end
  22. 24 def log_exception(ex, level: @options.debug_level, color: nil)
  23. 936 return unless @options.debug
  24. 10 return unless @options.debug_level >= level
  25. 20 log(level: level, color: color) { ex.full_message }
  26. end
  27. end
  28. end

lib/httpx/options.rb

98.71% lines covered

155 relevant lines. 153 lines covered and 2 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "socket"
  3. 24 module HTTPX
  4. # Contains a set of options which are passed and shared across from session to its requests or
  5. # responses.
  6. 24 class Options
  7. 24 BUFFER_SIZE = 1 << 14
  8. 24 WINDOW_SIZE = 1 << 14 # 16K
  9. 24 MAX_BODY_THRESHOLD_SIZE = (1 << 10) * 112 # 112K
  10. 24 KEEP_ALIVE_TIMEOUT = 20
  11. 24 SETTINGS_TIMEOUT = 10
  12. 24 CLOSE_HANDSHAKE_TIMEOUT = 10
  13. 24 CONNECT_TIMEOUT = READ_TIMEOUT = WRITE_TIMEOUT = 60
  14. 24 REQUEST_TIMEOUT = OPERATION_TIMEOUT = nil
  15. # https://github.com/ruby/resolv/blob/095f1c003f6073730500f02acbdbc55f83d70987/lib/resolv.rb#L408
  16. 2 ip_address_families = begin
  17. 24 list = Socket.ip_address_list
  18. 98 if list.any? { |a| a.ipv6? && !a.ipv6_loopback? && !a.ipv6_linklocal? && !a.ipv6_unique_local? }
  19. [Socket::AF_INET6, Socket::AF_INET]
  20. else
  21. 24 [Socket::AF_INET]
  22. end
  23. rescue NotImplementedError
  24. [Socket::AF_INET]
  25. end
  26. 2 DEFAULT_OPTIONS = {
  27. 22 :max_requests => Float::INFINITY,
  28. 23 :debug => ENV.key?("HTTPX_DEBUG") ? $stderr : nil,
  29. 24 :debug_level => (ENV["HTTPX_DEBUG"] || 1).to_i,
  30. :ssl => {},
  31. :http2_settings => { settings_enable_push: 0 },
  32. :fallback_protocol => "http/1.1",
  33. :supported_compression_formats => %w[gzip deflate],
  34. :decompress_response_body => true,
  35. :compress_request_body => true,
  36. :timeout => {
  37. connect_timeout: CONNECT_TIMEOUT,
  38. settings_timeout: SETTINGS_TIMEOUT,
  39. close_handshake_timeout: CLOSE_HANDSHAKE_TIMEOUT,
  40. operation_timeout: OPERATION_TIMEOUT,
  41. keep_alive_timeout: KEEP_ALIVE_TIMEOUT,
  42. read_timeout: READ_TIMEOUT,
  43. write_timeout: WRITE_TIMEOUT,
  44. request_timeout: REQUEST_TIMEOUT,
  45. },
  46. :headers_class => Class.new(Headers),
  47. :headers => {},
  48. :window_size => WINDOW_SIZE,
  49. :buffer_size => BUFFER_SIZE,
  50. :body_threshold_size => MAX_BODY_THRESHOLD_SIZE,
  51. :request_class => Class.new(Request),
  52. :response_class => Class.new(Response),
  53. :request_body_class => Class.new(Request::Body),
  54. :response_body_class => Class.new(Response::Body),
  55. :connection_class => Class.new(Connection),
  56. :options_class => Class.new(self),
  57. :transport => nil,
  58. :addresses => nil,
  59. :persistent => false,
  60. 24 :resolver_class => (ENV["HTTPX_RESOLVER"] || :native).to_sym,
  61. :resolver_options => { cache: true },
  62. :ip_families => ip_address_families,
  63. }.freeze
  64. 24 class << self
  65. 24 def new(options = {})
  66. # let enhanced options go through
  67. 9556 return options if self == Options && options.class < self
  68. 7368 return options if options.is_a?(self)
  69. 3599 super
  70. end
  71. 24 def method_added(meth)
  72. 15422 super
  73. 15422 return unless meth =~ /^option_(.+)$/
  74. 7165 optname = Regexp.last_match(1).to_sym
  75. 7165 attr_reader(optname)
  76. end
  77. end
  78. # creates a new options instance from a given hash, which optionally define the following:
  79. #
  80. # :debug :: an object which log messages are written to (must respond to <tt><<</tt>)
  81. # :debug_level :: the log level of messages (can be 1, 2, or 3).
  82. # :ssl :: a hash of options which can be set as params of OpenSSL::SSL::SSLContext (see HTTPX::IO::SSL)
  83. # :http2_settings :: a hash of options to be passed to a HTTP2::Connection (ex: <tt>{ max_concurrent_streams: 2 }</tt>)
  84. # :fallback_protocol :: version of HTTP protocol to use by default in the absence of protocol negotiation
  85. # like ALPN (defaults to <tt>"http/1.1"</tt>)
  86. # :supported_compression_formats :: list of compressions supported by the transcoder layer (defaults to <tt>%w[gzip deflate]</tt>).
  87. # :decompress_response_body :: whether to auto-decompress response body (defaults to <tt>true</tt>).
  88. # :compress_request_body :: whether to auto-decompress response body (defaults to <tt>true</tt>)
  89. # :timeout :: hash of timeout configurations (supports <tt>:connect_timeout</tt>, <tt>:settings_timeout</tt>,
  90. # <tt>:operation_timeout</tt>, <tt>:keep_alive_timeout</tt>, <tt>:read_timeout</tt>, <tt>:write_timeout</tt>
  91. # and <tt>:request_timeout</tt>
  92. # :headers :: hash of HTTP headers (ex: <tt>{ "x-custom-foo" => "bar" }</tt>)
  93. # :window_size :: number of bytes to read from a socket
  94. # :buffer_size :: internal read and write buffer size in bytes
  95. # :body_threshold_size :: maximum size in bytes of response payload that is buffered in memory.
  96. # :request_class :: class used to instantiate a request
  97. # :response_class :: class used to instantiate a response
  98. # :headers_class :: class used to instantiate headers
  99. # :request_body_class :: class used to instantiate a request body
  100. # :response_body_class :: class used to instantiate a response body
  101. # :connection_class :: class used to instantiate connections
  102. # :options_class :: class used to instantiate options
  103. # :transport :: type of transport to use (set to "unix" for UNIX sockets)
  104. # :addresses :: bucket of peer addresses (can be a list of IP addresses, a hash of domain to list of adddresses;
  105. # paths should be used for UNIX sockets instead)
  106. # :io :: open socket, or domain/ip-to-socket hash, which requests should be sent to
  107. # :persistent :: whether to persist connections in between requests (defaults to <tt>true</tt>)
  108. # :resolver_class :: which resolver to use (defaults to <tt>:native</tt>, can also be <tt>:system<tt> for
  109. # using getaddrinfo or <tt>:https</tt> for DoH resolver, or a custom class)
  110. # :resolver_options :: hash of options passed to the resolver
  111. # :ip_families :: which socket families are supported (system-dependent)
  112. # :origin :: HTTP origin to set on requests with relative path (ex: "https://api.serv.com")
  113. # :base_path :: path to prefix given relative paths with (ex: "/v2")
  114. # :max_concurrent_requests :: max number of requests which can be set concurrently
  115. # :max_requests :: max number of requests which can be made on socket before it reconnects.
  116. #
  117. # This list of options are enhanced with each loaded plugin, see the plugin docs for details.
  118. 24 def initialize(options = {})
  119. 3599 do_initialize(options)
  120. 3585 freeze
  121. end
  122. 24 def freeze
  123. 9211 super
  124. 9211 @origin.freeze
  125. 9211 @base_path.freeze
  126. 9211 @timeout.freeze
  127. 9211 @headers.freeze
  128. 9211 @addresses.freeze
  129. 9211 @supported_compression_formats.freeze
  130. end
  131. 24 def option_origin(value)
  132. 520 URI(value)
  133. end
  134. 24 def option_base_path(value)
  135. 28 String(value)
  136. end
  137. 24 def option_headers(value)
  138. 6424 headers_class.new(value)
  139. end
  140. 24 def option_timeout(value)
  141. 6807 Hash[value]
  142. end
  143. 24 def option_supported_compression_formats(value)
  144. 5906 Array(value).map(&:to_s)
  145. end
  146. 24 def option_max_concurrent_requests(value)
  147. 844 raise TypeError, ":max_concurrent_requests must be positive" unless value.positive?
  148. 844 value
  149. end
  150. 24 def option_max_requests(value)
  151. 5895 raise TypeError, ":max_requests must be positive" unless value.positive?
  152. 5895 value
  153. end
  154. 24 def option_window_size(value)
  155. 5900 value = Integer(value)
  156. 5900 raise TypeError, ":window_size must be positive" unless value.positive?
  157. 5900 value
  158. end
  159. 24 def option_buffer_size(value)
  160. 5900 value = Integer(value)
  161. 5900 raise TypeError, ":buffer_size must be positive" unless value.positive?
  162. 5900 value
  163. end
  164. 24 def option_body_threshold_size(value)
  165. 5886 bytes = Integer(value)
  166. 5886 raise TypeError, ":body_threshold_size must be positive" unless bytes.positive?
  167. 5886 bytes
  168. end
  169. 24 def option_transport(value)
  170. 42 transport = value.to_s
  171. 42 raise TypeError, "#{transport} is an unsupported transport type" unless %w[unix].include?(transport)
  172. 42 transport
  173. end
  174. 24 def option_addresses(value)
  175. 37 Array(value)
  176. end
  177. 24 def option_ip_families(value)
  178. 5886 Array(value)
  179. end
  180. 24 %i[
  181. ssl http2_settings
  182. request_class response_class headers_class request_body_class
  183. response_body_class connection_class options_class
  184. io fallback_protocol debug debug_level resolver_class resolver_options
  185. compress_request_body decompress_response_body
  186. persistent
  187. ].each do |method_name|
  188. 432 class_eval(<<-OUT, __FILE__, __LINE__ + 1)
  189. 18 # sets +v+ as the value of #{method_name}
  190. 18 def option_#{method_name}(v); v; end # def option_smth(v); v; end
  191. OUT
  192. end
  193. 24 REQUEST_BODY_IVARS = %i[@headers].freeze
  194. 24 def ==(other)
  195. 3658 super || options_equals?(other)
  196. end
  197. 24 def options_equals?(other, ignore_ivars = REQUEST_BODY_IVARS)
  198. # headers and other request options do not play a role, as they are
  199. # relevant only for the request.
  200. 2398 ivars = instance_variables - ignore_ivars
  201. 2398 other_ivars = other.instance_variables - ignore_ivars
  202. 2398 return false if ivars.size != other_ivars.size
  203. 1680 return false if ivars.sort != other_ivars.sort
  204. 1668 ivars.all? do |ivar|
  205. 23247 instance_variable_get(ivar) == other.instance_variable_get(ivar)
  206. end
  207. end
  208. 24 OTHER_LOOKUP = ->(obj, k, ivar_map) {
  209. 234035 case obj
  210. when Hash
  211. 22067 obj[ivar_map[k]]
  212. else
  213. 243033 obj.instance_variable_get(k)
  214. end
  215. }
  216. 24 def merge(other)
  217. 27563 ivar_map = nil
  218. 27563 other_ivars = case other
  219. when Hash
  220. 32484 ivar_map = other.keys.to_h { |k| [:"@#{k}", k] }
  221. 19071 ivar_map.keys
  222. else
  223. 8492 other.instance_variables
  224. end
  225. 27563 return self if other_ivars.empty?
  226. 211934 return self if other_ivars.all? { |ivar| instance_variable_get(ivar) == OTHER_LOOKUP[other, ivar, ivar_map] }
  227. 10397 opts = dup
  228. 10397 other_ivars.each do |ivar|
  229. 69914 v = OTHER_LOOKUP[other, ivar, ivar_map]
  230. 69914 unless v
  231. 2631 opts.instance_variable_set(ivar, v)
  232. 2631 next
  233. end
  234. 67283 v = opts.__send__(:"option_#{ivar[1..-1]}", v)
  235. 67283 orig_v = instance_variable_get(ivar)
  236. 67283 v = orig_v.merge(v) if orig_v.respond_to?(:merge) && v.respond_to?(:merge)
  237. 67283 opts.instance_variable_set(ivar, v)
  238. end
  239. 10397 opts
  240. end
  241. 24 def to_hash
  242. 2610 instance_variables.each_with_object({}) do |ivar, hs|
  243. 55389 hs[ivar[1..-1].to_sym] = instance_variable_get(ivar)
  244. end
  245. end
  246. 24 def extend_with_plugin_classes(pl)
  247. 5588 if defined?(pl::RequestMethods) || defined?(pl::RequestClassMethods)
  248. 1654 @request_class = @request_class.dup
  249. 1654 @request_class.__send__(:include, pl::RequestMethods) if defined?(pl::RequestMethods)
  250. 1654 @request_class.extend(pl::RequestClassMethods) if defined?(pl::RequestClassMethods)
  251. end
  252. 5588 if defined?(pl::ResponseMethods) || defined?(pl::ResponseClassMethods)
  253. 1725 @response_class = @response_class.dup
  254. 1725 @response_class.__send__(:include, pl::ResponseMethods) if defined?(pl::ResponseMethods)
  255. 1725 @response_class.extend(pl::ResponseClassMethods) if defined?(pl::ResponseClassMethods)
  256. end
  257. 5588 if defined?(pl::HeadersMethods) || defined?(pl::HeadersClassMethods)
  258. 133 @headers_class = @headers_class.dup
  259. 133 @headers_class.__send__(:include, pl::HeadersMethods) if defined?(pl::HeadersMethods)
  260. 133 @headers_class.extend(pl::HeadersClassMethods) if defined?(pl::HeadersClassMethods)
  261. end
  262. 5588 if defined?(pl::RequestBodyMethods) || defined?(pl::RequestBodyClassMethods)
  263. 142 @request_body_class = @request_body_class.dup
  264. 142 @request_body_class.__send__(:include, pl::RequestBodyMethods) if defined?(pl::RequestBodyMethods)
  265. 142 @request_body_class.extend(pl::RequestBodyClassMethods) if defined?(pl::RequestBodyClassMethods)
  266. end
  267. 5588 if defined?(pl::ResponseBodyMethods) || defined?(pl::ResponseBodyClassMethods)
  268. 468 @response_body_class = @response_body_class.dup
  269. 468 @response_body_class.__send__(:include, pl::ResponseBodyMethods) if defined?(pl::ResponseBodyMethods)
  270. 468 @response_body_class.extend(pl::ResponseBodyClassMethods) if defined?(pl::ResponseBodyClassMethods)
  271. end
  272. 5588 if defined?(pl::ConnectionMethods)
  273. 2492 @connection_class = @connection_class.dup
  274. 2492 @connection_class.__send__(:include, pl::ConnectionMethods)
  275. end
  276. 5588 return unless defined?(pl::OptionsMethods)
  277. 2204 @options_class = @options_class.dup
  278. 2204 @options_class.__send__(:include, pl::OptionsMethods)
  279. end
  280. 24 private
  281. 24 def do_initialize(options = {})
  282. 3599 defaults = DEFAULT_OPTIONS.merge(options)
  283. 3599 defaults.each do |k, v|
  284. 97938 next if v.nil?
  285. 87141 option_method_name = :"option_#{k}"
  286. 87141 raise Error, "unknown option: #{k}" unless respond_to?(option_method_name)
  287. 87134 value = __send__(option_method_name, v)
  288. 87127 instance_variable_set(:"@#{k}", value)
  289. end
  290. end
  291. end
  292. end

lib/httpx/parser/http1.rb

100.0% lines covered

109 relevant lines. 109 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 module Parser
  4. 24 class Error < Error; end
  5. 24 class HTTP1
  6. 24 VERSIONS = %w[1.0 1.1].freeze
  7. 24 attr_reader :status_code, :http_version, :headers
  8. 24 def initialize(observer)
  9. 3647 @observer = observer
  10. 3647 @state = :idle
  11. 3647 @buffer = "".b
  12. 3647 @headers = {}
  13. end
  14. 24 def <<(chunk)
  15. 5921 @buffer << chunk
  16. 5921 parse
  17. end
  18. 24 def reset!
  19. 10430 @state = :idle
  20. 10430 @headers.clear
  21. 10430 @content_length = nil
  22. 10430 @_has_trailers = nil
  23. end
  24. 24 def upgrade?
  25. 3711 @upgrade
  26. end
  27. 24 def upgrade_data
  28. 28 @buffer
  29. end
  30. 24 private
  31. 24 def parse
  32. 5921 loop do
  33. 12506 state = @state
  34. 11035 case @state
  35. when :idle
  36. 4013 parse_headline
  37. when :headers, :trailers
  38. 4091 parse_headers
  39. when :data
  40. 4400 parse_data
  41. end
  42. 9248 return if @buffer.empty? || state == @state
  43. end
  44. end
  45. 24 def parse_headline
  46. 4013 idx = @buffer.index("\n")
  47. 4013 return unless idx
  48. 4013 (m = %r{\AHTTP(?:/(\d+\.\d+))?\s+(\d\d\d)(?:\s+(.*))?}in.match(@buffer)) ||
  49. raise(Error, "wrong head line format")
  50. 4006 version, code, _ = m.captures
  51. 4006 raise(Error, "unsupported HTTP version (HTTP/#{version})") unless version && VERSIONS.include?(version)
  52. 3999 @http_version = version.split(".").map(&:to_i)
  53. 3999 @status_code = code.to_i
  54. 3999 raise(Error, "wrong status code (#{@status_code})") unless (100..599).cover?(@status_code)
  55. 3992 @buffer = @buffer.byteslice((idx + 1)..-1)
  56. 3992 nextstate(:headers)
  57. end
  58. 24 def parse_headers
  59. 4093 headers = @headers
  60. 4093 buffer = @buffer
  61. 31202 while (idx = buffer.index("\n"))
  62. # @type var line: String
  63. 31168 line = buffer.byteslice(0..idx)
  64. 31168 raise Error, "wrong header format" if line.start_with?("\s", "\t")
  65. 31161 line.lstrip!
  66. 31161 buffer = @buffer = buffer.byteslice((idx + 1)..-1)
  67. 31161 if line.empty?
  68. 3531 case @state
  69. when :headers
  70. 3978 prepare_data(headers)
  71. 3978 @observer.on_headers(headers)
  72. 3438 return unless @state == :headers
  73. # state might have been reset
  74. # in the :headers callback
  75. 3373 nextstate(:data)
  76. 3373 headers.clear
  77. when :trailers
  78. 14 @observer.on_trailers(headers)
  79. 14 headers.clear
  80. 14 nextstate(:complete)
  81. end
  82. 3387 return
  83. end
  84. 27169 separator_index = line.index(":")
  85. 27169 raise Error, "wrong header format" unless separator_index
  86. # @type var key: String
  87. 27162 key = line.byteslice(0..(separator_index - 1))
  88. 27162 key.rstrip! # was lstripped previously!
  89. # @type var value: String
  90. 27162 value = line.byteslice((separator_index + 1)..-1)
  91. 27162 value.strip!
  92. 27162 raise Error, "wrong header format" if value.nil?
  93. 27162 (headers[key.downcase] ||= []) << value
  94. end
  95. end
  96. 24 def parse_data
  97. 4400 if @buffer.respond_to?(:each)
  98. 170 @buffer.each do |chunk|
  99. 205 @observer.on_data(chunk)
  100. end
  101. 4229 elsif @content_length
  102. # @type var data: String
  103. 4202 data = @buffer.byteslice(0, @content_length)
  104. 4202 @buffer = @buffer.byteslice(@content_length..-1) || "".b
  105. 3699 @content_length -= data.bytesize
  106. 4202 @observer.on_data(data)
  107. 4190 data.clear
  108. else
  109. 28 @observer.on_data(@buffer)
  110. 28 @buffer.clear
  111. end
  112. 4381 return unless no_more_data?
  113. 3256 @buffer = @buffer.to_s
  114. 3256 if @_has_trailers
  115. 14 nextstate(:trailers)
  116. else
  117. 3242 nextstate(:complete)
  118. end
  119. end
  120. 24 def prepare_data(headers)
  121. 3978 @upgrade = headers.key?("upgrade")
  122. 3978 @_has_trailers = headers.key?("trailer")
  123. 3978 if (tr_encodings = headers["transfer-encoding"])
  124. 100 tr_encodings.reverse_each do |tr_encoding|
  125. 100 tr_encoding.split(/ *, */).each do |encoding|
  126. 86 case encoding
  127. when "chunked"
  128. 100 @buffer = Transcoder::Chunker::Decoder.new(@buffer, @_has_trailers)
  129. end
  130. end
  131. end
  132. else
  133. 3878 @content_length = headers["content-length"][0].to_i if headers.key?("content-length")
  134. end
  135. end
  136. 24 def no_more_data?
  137. 4381 if @content_length
  138. 4190 @content_length <= 0
  139. 190 elsif @buffer.respond_to?(:finished?)
  140. 163 @buffer.finished?
  141. else
  142. 28 false
  143. end
  144. end
  145. 24 def nextstate(state)
  146. 10635 @state = state
  147. 9418 case state
  148. when :headers
  149. 3992 @observer.on_start
  150. when :complete
  151. 3256 @observer.on_complete
  152. 592 reset!
  153. 592 nextstate(:idle) unless @buffer.empty?
  154. end
  155. end
  156. end
  157. end
  158. end

lib/httpx/plugins/auth.rb

100.0% lines covered

9 relevant lines. 9 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin adds a shim +authorization+ method to the session, which will fill
  6. # the HTTP Authorization header, and another, +bearer_auth+, which fill the "Bearer " prefix
  7. # in its value.
  8. #
  9. # https://gitlab.com/os85/httpx/wikis/Auth#auth
  10. #
  11. 7 module Auth
  12. 7 module InstanceMethods
  13. 7 def authorization(token)
  14. 126 with(headers: { "authorization" => token })
  15. end
  16. 7 def bearer_auth(token)
  17. 14 authorization("Bearer #{token}")
  18. end
  19. end
  20. end
  21. 7 register_plugin :auth, Auth
  22. end
  23. end

lib/httpx/plugins/auth/basic.rb

100.0% lines covered

10 relevant lines. 10 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 8 require "httpx/base64"
  3. 8 module HTTPX
  4. 8 module Plugins
  5. 8 module Authentication
  6. 8 class Basic
  7. 8 def initialize(user, password, **)
  8. 236 @user = user
  9. 236 @password = password
  10. end
  11. 8 def authenticate(*)
  12. 209 "Basic #{Base64.strict_encode64("#{@user}:#{@password}")}"
  13. end
  14. end
  15. end
  16. end
  17. end

lib/httpx/plugins/auth/digest.rb

100.0% lines covered

61 relevant lines. 61 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 require "time"
  3. 7 require "securerandom"
  4. 7 require "digest"
  5. 7 module HTTPX
  6. 7 module Plugins
  7. 7 module Authentication
  8. 7 class Digest
  9. 7 def initialize(user, password, hashed: false, **)
  10. 168 @user = user
  11. 168 @password = password
  12. 168 @nonce = 0
  13. 168 @hashed = hashed
  14. end
  15. 7 def can_authenticate?(authenticate)
  16. 140 authenticate && /Digest .*/.match?(authenticate)
  17. end
  18. 7 def authenticate(request, authenticate)
  19. 140 "Digest #{generate_header(request.verb, request.path, authenticate)}"
  20. end
  21. 7 private
  22. 7 def generate_header(meth, uri, authenticate)
  23. # discard first token, it's Digest
  24. 140 auth_info = authenticate[/^(\w+) (.*)/, 2]
  25. 140 params = auth_info.split(/ *, */)
  26. 728 .to_h { |val| val.split("=", 2) }
  27. 728 .transform_values { |v| v.delete("\"") }
  28. 140 nonce = params["nonce"]
  29. 140 nc = next_nonce
  30. # verify qop
  31. 140 qop = params["qop"]
  32. 140 if params["algorithm"] =~ /(.*?)(-sess)?$/
  33. 126 alg = Regexp.last_match(1)
  34. 126 algorithm = ::Digest.const_get(alg)
  35. 126 raise DigestError, "unknown algorithm \"#{alg}\"" unless algorithm
  36. 126 sess = Regexp.last_match(2)
  37. else
  38. 14 algorithm = ::Digest::MD5
  39. end
  40. 140 if qop || sess
  41. 140 cnonce = make_cnonce
  42. 140 nc = format("%<nonce>08x", nonce: nc)
  43. end
  44. 140 a1 = if sess
  45. 4 [
  46. 28 (@hashed ? @password : algorithm.hexdigest("#{@user}:#{params["realm"]}:#{@password}")),
  47. nonce,
  48. cnonce,
  49. 3 ].join ":"
  50. else
  51. 112 @hashed ? @password : "#{@user}:#{params["realm"]}:#{@password}"
  52. end
  53. 140 ha1 = algorithm.hexdigest(a1)
  54. 140 ha2 = algorithm.hexdigest("#{meth}:#{uri}")
  55. 140 request_digest = [ha1, nonce]
  56. 140 request_digest.push(nc, cnonce, qop) if qop
  57. 140 request_digest << ha2
  58. 140 request_digest = request_digest.join(":")
  59. 40 header = [
  60. 120 %(username="#{@user}"),
  61. 20 %(nonce="#{nonce}"),
  62. 20 %(uri="#{uri}"),
  63. 20 %(response="#{algorithm.hexdigest(request_digest)}"),
  64. ]
  65. 140 header << %(realm="#{params["realm"]}") if params.key?("realm")
  66. 140 header << %(algorithm=#{params["algorithm"]}) if params.key?("algorithm")
  67. 140 header << %(cnonce="#{cnonce}") if cnonce
  68. 140 header << %(nc=#{nc})
  69. 140 header << %(qop=#{qop}) if qop
  70. 140 header << %(opaque="#{params["opaque"]}") if params.key?("opaque")
  71. 140 header.join ", "
  72. end
  73. 7 def make_cnonce
  74. 160 ::Digest::MD5.hexdigest [
  75. Time.now.to_i,
  76. Process.pid,
  77. SecureRandom.random_number(2**32),
  78. ].join ":"
  79. end
  80. 7 def next_nonce
  81. 120 @nonce += 1
  82. end
  83. end
  84. end
  85. end
  86. end

lib/httpx/plugins/auth/ntlm.rb

100.0% lines covered

19 relevant lines. 19 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 5 require "httpx/base64"
  3. 5 require "ntlm"
  4. 5 module HTTPX
  5. 5 module Plugins
  6. 5 module Authentication
  7. 5 class Ntlm
  8. 5 def initialize(user, password, domain: nil)
  9. 4 @user = user
  10. 4 @password = password
  11. 4 @domain = domain
  12. end
  13. 5 def can_authenticate?(authenticate)
  14. 2 authenticate && /NTLM .*/.match?(authenticate)
  15. end
  16. 5 def negotiate
  17. 4 "NTLM #{NTLM.negotiate(domain: @domain).to_base64}"
  18. end
  19. 5 def authenticate(_req, www)
  20. 2 challenge = www[/NTLM (.*)/, 1]
  21. 2 challenge = Base64.decode64(challenge)
  22. 2 ntlm_challenge = NTLM.authenticate(challenge, @user, @domain, @password).to_base64
  23. 2 "NTLM #{ntlm_challenge}"
  24. end
  25. end
  26. end
  27. end
  28. end

lib/httpx/plugins/auth/socks5.rb

100.0% lines covered

11 relevant lines. 11 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module HTTPX
  3. 9 module Plugins
  4. 9 module Authentication
  5. 9 class Socks5
  6. 9 def initialize(user, password, **)
  7. 42 @user = user
  8. 42 @password = password
  9. end
  10. 9 def can_authenticate?(*)
  11. 42 @user && @password
  12. end
  13. 9 def authenticate(*)
  14. 42 [0x01, @user.bytesize, @user, @password.bytesize, @password].pack("CCA*CA*")
  15. end
  16. end
  17. end
  18. end
  19. end

lib/httpx/plugins/aws_sdk_authentication.rb

100.0% lines covered

43 relevant lines. 43 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin applies AWS Sigv4 to requests, using the AWS SDK credentials and configuration.
  6. #
  7. # It requires the "aws-sdk-core" gem.
  8. #
  9. 7 module AwsSdkAuthentication
  10. # Mock configuration, to be used only when resolving credentials
  11. 7 class Configuration
  12. 7 attr_reader :profile
  13. 7 def initialize(profile)
  14. 28 @profile = profile
  15. end
  16. 7 def respond_to_missing?(*)
  17. 14 true
  18. end
  19. 7 def method_missing(*); end
  20. end
  21. #
  22. # encapsulates access to an AWS SDK credentials store.
  23. #
  24. 7 class Credentials
  25. 7 def initialize(aws_credentials)
  26. 14 @aws_credentials = aws_credentials
  27. end
  28. 7 def username
  29. 14 @aws_credentials.access_key_id
  30. end
  31. 7 def password
  32. 14 @aws_credentials.secret_access_key
  33. end
  34. 7 def security_token
  35. 14 @aws_credentials.session_token
  36. end
  37. end
  38. 7 class << self
  39. 7 def load_dependencies(_klass)
  40. 14 require "aws-sdk-core"
  41. end
  42. 7 def configure(klass)
  43. 14 klass.plugin(:aws_sigv4)
  44. end
  45. 7 def extra_options(options)
  46. 14 options.merge(max_concurrent_requests: 1)
  47. end
  48. 7 def credentials(profile)
  49. 14 mock_configuration = Configuration.new(profile)
  50. 14 Credentials.new(Aws::CredentialProviderChain.new(mock_configuration).resolve)
  51. end
  52. 7 def region(profile)
  53. # https://github.com/aws/aws-sdk-ruby/blob/version-3/gems/aws-sdk-core/lib/aws-sdk-core/plugins/regional_endpoint.rb#L62
  54. 14 keys = %w[AWS_REGION AMAZON_REGION AWS_DEFAULT_REGION]
  55. 14 env_region = ENV.values_at(*keys).compact.first
  56. 14 env_region = nil if env_region == ""
  57. 14 cfg_region = Aws.shared_config.region(profile: profile)
  58. 14 env_region || cfg_region
  59. end
  60. end
  61. # adds support for the following options:
  62. #
  63. # :aws_profile :: AWS account profile to retrieve credentials from.
  64. 7 module OptionsMethods
  65. 7 def option_aws_profile(value)
  66. 70 String(value)
  67. end
  68. end
  69. 7 module InstanceMethods
  70. #
  71. # aws_authentication
  72. # aws_authentication(credentials: Aws::Credentials.new('akid', 'secret'))
  73. # aws_authentication()
  74. #
  75. 7 def aws_sdk_authentication(
  76. credentials: AwsSdkAuthentication.credentials(@options.aws_profile),
  77. region: AwsSdkAuthentication.region(@options.aws_profile),
  78. **options
  79. )
  80. 14 aws_sigv4_authentication(
  81. credentials: credentials,
  82. region: region,
  83. provider_prefix: "aws",
  84. header_provider_field: "amz",
  85. **options
  86. )
  87. end
  88. 7 alias_method :aws_auth, :aws_sdk_authentication
  89. end
  90. end
  91. 7 register_plugin :aws_sdk_authentication, AwsSdkAuthentication
  92. end
  93. end

lib/httpx/plugins/aws_sigv4.rb

100.0% lines covered

114 relevant lines. 114 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin adds AWS Sigv4 authentication.
  6. #
  7. # https://docs.aws.amazon.com/IAM/latest/UserGuide/signing-elements.html
  8. #
  9. # https://gitlab.com/os85/httpx/wikis/AWS-SigV4
  10. #
  11. 7 module AWSSigV4
  12. 7 Credentials = Struct.new(:username, :password, :security_token)
  13. # Signs requests using the AWS sigv4 signing.
  14. 7 class Signer
  15. 7 def initialize(
  16. service:,
  17. region:,
  18. credentials: nil,
  19. username: nil,
  20. password: nil,
  21. security_token: nil,
  22. provider_prefix: "aws",
  23. header_provider_field: "amz",
  24. unsigned_headers: [],
  25. apply_checksum_header: true,
  26. algorithm: "SHA256"
  27. )
  28. 112 @credentials = credentials || Credentials.new(username, password, security_token)
  29. 112 @service = service
  30. 112 @region = region
  31. 112 @unsigned_headers = Set.new(unsigned_headers.map(&:downcase))
  32. 112 @unsigned_headers << "authorization"
  33. 112 @unsigned_headers << "x-amzn-trace-id"
  34. 112 @unsigned_headers << "expect"
  35. 112 @apply_checksum_header = apply_checksum_header
  36. 112 @provider_prefix = provider_prefix
  37. 112 @header_provider_field = header_provider_field
  38. 112 @algorithm = algorithm
  39. end
  40. 7 def sign!(request)
  41. 112 lower_provider_prefix = "#{@provider_prefix}4"
  42. 112 upper_provider_prefix = lower_provider_prefix.upcase
  43. 112 downcased_algorithm = @algorithm.downcase
  44. 112 datetime = (request.headers["x-#{@header_provider_field}-date"] ||= Time.now.utc.strftime("%Y%m%dT%H%M%SZ"))
  45. 112 date = datetime[0, 8]
  46. 112 content_hashed = request.headers["x-#{@header_provider_field}-content-#{downcased_algorithm}"] || hexdigest(request.body)
  47. 112 request.headers["x-#{@header_provider_field}-content-#{downcased_algorithm}"] ||= content_hashed if @apply_checksum_header
  48. 112 request.headers["x-#{@header_provider_field}-security-token"] ||= @credentials.security_token if @credentials.security_token
  49. 112 signature_headers = request.headers.each.reject do |k, _|
  50. 742 @unsigned_headers.include?(k)
  51. end
  52. # aws sigv4 needs to declare the host, regardless of protocol version
  53. 112 signature_headers << ["host", request.authority] unless request.headers.key?("host")
  54. 112 signature_headers.sort_by!(&:first)
  55. 112 signed_headers = signature_headers.map(&:first).join(";")
  56. 112 canonical_headers = signature_headers.map do |k, v|
  57. # eliminate whitespace between value fields, unless it's a quoted value
  58. 624 "#{k}:#{v.start_with?("\"") && v.end_with?("\"") ? v : v.gsub(/\s+/, " ").strip}\n"
  59. end.join
  60. # canonical request
  61. 112 creq = "#{request.verb}" \
  62. 16 "\n#{request.canonical_path}" \
  63. 16 "\n#{request.canonical_query}" \
  64. 16 "\n#{canonical_headers}" \
  65. 16 "\n#{signed_headers}" \
  66. 16 "\n#{content_hashed}"
  67. 112 credential_scope = "#{date}" \
  68. 16 "/#{@region}" \
  69. 16 "/#{@service}" \
  70. 16 "/#{lower_provider_prefix}_request"
  71. 112 algo_line = "#{upper_provider_prefix}-HMAC-#{@algorithm}"
  72. # string to sign
  73. 112 sts = "#{algo_line}" \
  74. 16 "\n#{datetime}" \
  75. 16 "\n#{credential_scope}" \
  76. 16 "\n#{hexdigest(creq)}"
  77. # signature
  78. 112 k_date = hmac("#{upper_provider_prefix}#{@credentials.password}", date)
  79. 112 k_region = hmac(k_date, @region)
  80. 112 k_service = hmac(k_region, @service)
  81. 112 k_credentials = hmac(k_service, "#{lower_provider_prefix}_request")
  82. 112 sig = hexhmac(k_credentials, sts)
  83. 112 credential = "#{@credentials.username}/#{credential_scope}"
  84. # apply signature
  85. 96 request.headers["authorization"] =
  86. 16 "#{algo_line} " \
  87. 16 "Credential=#{credential}, " \
  88. 16 "SignedHeaders=#{signed_headers}, " \
  89. 16 "Signature=#{sig}"
  90. end
  91. 7 private
  92. 7 def hexdigest(value)
  93. 217 if value.respond_to?(:to_path)
  94. # files, pathnames
  95. 7 OpenSSL::Digest.new(@algorithm).file(value.to_path).hexdigest
  96. 209 elsif value.respond_to?(:each)
  97. 98 digest = OpenSSL::Digest.new(@algorithm)
  98. 98 mb_buffer = value.each.with_object("".b) do |chunk, buffer|
  99. 35 buffer << chunk
  100. 35 break if buffer.bytesize >= 1024 * 1024
  101. end
  102. 98 digest.update(mb_buffer)
  103. 98 value.rewind
  104. 98 digest.hexdigest
  105. else
  106. 112 OpenSSL::Digest.new(@algorithm).hexdigest(value)
  107. end
  108. end
  109. 7 def hmac(key, value)
  110. 448 OpenSSL::HMAC.digest(OpenSSL::Digest.new(@algorithm), key, value)
  111. end
  112. 7 def hexhmac(key, value)
  113. 112 OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new(@algorithm), key, value)
  114. end
  115. end
  116. 7 class << self
  117. 7 def load_dependencies(*)
  118. 112 require "set"
  119. 112 require "digest/sha2"
  120. 112 require "openssl"
  121. end
  122. 7 def configure(klass)
  123. 112 klass.plugin(:expect)
  124. end
  125. end
  126. # adds support for the following options:
  127. #
  128. # :sigv4_signer :: instance of HTTPX::Plugins::AWSSigV4 used to sign requests.
  129. 7 module OptionsMethods
  130. 7 def option_sigv4_signer(value)
  131. 238 value.is_a?(Signer) ? value : Signer.new(value)
  132. end
  133. end
  134. 7 module InstanceMethods
  135. 7 def aws_sigv4_authentication(**options)
  136. 112 with(sigv4_signer: Signer.new(**options))
  137. end
  138. 7 def build_request(*)
  139. 112 request = super
  140. 112 return request if request.headers.key?("authorization")
  141. 112 signer = request.options.sigv4_signer
  142. 112 return request unless signer
  143. 112 signer.sign!(request)
  144. 112 request
  145. end
  146. end
  147. 7 module RequestMethods
  148. 7 def canonical_path
  149. 112 path = uri.path.dup
  150. 112 path << "/" if path.empty?
  151. 140 path.gsub(%r{[^/]+}) { |part| CGI.escape(part.encode("UTF-8")).gsub("+", "%20").gsub("%7E", "~") }
  152. end
  153. 7 def canonical_query
  154. 140 params = query.split("&")
  155. # params = params.map { |p| p.match(/=/) ? p : p + '=' }
  156. # From: https://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html#create-canonical-request
  157. # Sort the parameter names by character code point in ascending order.
  158. # Parameters with duplicate names should be sorted by value.
  159. #
  160. # Default sort <=> in JRuby will swap members
  161. # occasionally when <=> is 0 (considered still sorted), but this
  162. # causes our normalized query string to not match the sent querystring.
  163. # When names match, we then sort by their values. When values also
  164. # match then we sort by their original order
  165. 140 params.each.with_index.sort do |a, b|
  166. 56 a, a_offset = a
  167. 56 b, b_offset = b
  168. 56 a_name, a_value = a.split("=", 2)
  169. 56 b_name, b_value = b.split("=", 2)
  170. 56 if a_name == b_name
  171. 28 if a_value == b_value
  172. 14 a_offset <=> b_offset
  173. else
  174. 14 a_value <=> b_value
  175. end
  176. else
  177. 28 a_name <=> b_name
  178. end
  179. end.map(&:first).join("&")
  180. end
  181. end
  182. end
  183. 7 register_plugin :aws_sigv4, AWSSigV4
  184. end
  185. end

lib/httpx/plugins/basic_auth.rb

100.0% lines covered

12 relevant lines. 12 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin adds helper methods to implement HTTP Basic Auth (https://datatracker.ietf.org/doc/html/rfc7617)
  6. #
  7. # https://gitlab.com/os85/httpx/wikis/Auth#basic-auth
  8. #
  9. 7 module BasicAuth
  10. 7 class << self
  11. 7 def load_dependencies(_klass)
  12. 98 require_relative "auth/basic"
  13. end
  14. 7 def configure(klass)
  15. 98 klass.plugin(:auth)
  16. end
  17. end
  18. 7 module InstanceMethods
  19. 7 def basic_auth(user, password)
  20. 112 authorization(Authentication::Basic.new(user, password).authenticate)
  21. end
  22. end
  23. end
  24. 7 register_plugin :basic_auth, BasicAuth
  25. end
  26. end

lib/httpx/plugins/brotli.rb

100.0% lines covered

25 relevant lines. 25 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 5 module HTTPX
  3. 5 module Plugins
  4. 5 module Brotli
  5. 5 class Deflater < Transcoder::Deflater
  6. 5 def deflate(chunk)
  7. 20 return unless chunk
  8. 10 ::Brotli.deflate(chunk)
  9. end
  10. end
  11. 5 module RequestBodyClassMethods
  12. 5 def initialize_deflater_body(body, encoding)
  13. 20 return Brotli.encode(body) if encoding == "br"
  14. 10 super
  15. end
  16. end
  17. 5 module ResponseBodyClassMethods
  18. 5 def initialize_inflater_by_encoding(encoding, response, **kwargs)
  19. 20 return Brotli.decode(response, **kwargs) if encoding == "br"
  20. 10 super
  21. end
  22. end
  23. 5 module_function
  24. 5 def load_dependencies(*)
  25. 20 require "brotli"
  26. end
  27. 5 def self.extra_options(options)
  28. 20 options.merge(supported_compression_formats: %w[br] + options.supported_compression_formats)
  29. end
  30. 5 def encode(body)
  31. 10 Deflater.new(body)
  32. end
  33. 5 def decode(_response, **)
  34. 10 ::Brotli.method(:inflate)
  35. end
  36. end
  37. 5 register_plugin :brotli, Brotli
  38. end
  39. end

lib/httpx/plugins/callbacks.rb

100.0% lines covered

43 relevant lines. 43 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 module Plugins
  4. #
  5. # This plugin adds suppoort for callbacks around the request/response lifecycle.
  6. #
  7. # https://gitlab.com/os85/httpx/-/wikis/Events
  8. #
  9. 24 module Callbacks
  10. # connection closed user-space errors happen after errors can be surfaced to requests,
  11. # so they need to pierce through the scheduler, which is only possible by simulating an
  12. # interrupt.
  13. 24 class CallbackError < Exception; end # rubocop:disable Lint/InheritException
  14. 24 module InstanceMethods
  15. 24 include HTTPX::Callbacks
  16. 24 %i[
  17. connection_opened connection_closed
  18. request_error
  19. request_started request_body_chunk request_completed
  20. response_started response_body_chunk response_completed
  21. ].each do |meth|
  22. 216 class_eval(<<-MOD, __FILE__, __LINE__ + 1)
  23. 9 def on_#{meth}(&blk) # def on_connection_opened(&blk)
  24. 9 on(:#{meth}, &blk) # on(:connection_opened, &blk)
  25. end # end
  26. MOD
  27. end
  28. 24 private
  29. 24 def init_connection(uri, options)
  30. 183 connection = super
  31. 183 connection.on(:open) do
  32. 171 emit_or_callback_error(:connection_opened, connection.origin, connection.io.socket)
  33. end
  34. 183 connection.on(:close) do
  35. 170 emit_or_callback_error(:connection_closed, connection.origin) if connection.used?
  36. end
  37. 183 connection
  38. end
  39. 24 def set_request_callbacks(request)
  40. 185 super
  41. 185 request.on(:headers) do
  42. 157 emit_or_callback_error(:request_started, request)
  43. end
  44. 185 request.on(:body_chunk) do |chunk|
  45. 14 emit_or_callback_error(:request_body_chunk, request, chunk)
  46. end
  47. 185 request.on(:done) do
  48. 143 emit_or_callback_error(:request_completed, request)
  49. end
  50. 185 request.on(:response_started) do |res|
  51. 143 if res.is_a?(Response)
  52. 129 emit_or_callback_error(:response_started, request, res)
  53. 115 res.on(:chunk_received) do |chunk|
  54. 135 emit_or_callback_error(:response_body_chunk, request, res, chunk)
  55. end
  56. else
  57. 14 emit_or_callback_error(:request_error, request, res.error)
  58. end
  59. end
  60. 185 request.on(:response) do |res|
  61. 115 emit_or_callback_error(:response_completed, request, res)
  62. end
  63. end
  64. 24 def emit_or_callback_error(*args)
  65. 1034 emit(*args)
  66. rescue StandardError => e
  67. 105 ex = CallbackError.new(e.message)
  68. 105 ex.set_backtrace(e.backtrace)
  69. 105 raise ex
  70. end
  71. 24 def receive_requests(*)
  72. 185 super
  73. rescue CallbackError => e
  74. 98 raise e.cause
  75. end
  76. end
  77. end
  78. 24 register_plugin :callbacks, Callbacks
  79. end
  80. end

lib/httpx/plugins/circuit_breaker.rb

97.06% lines covered

68 relevant lines. 66 lines covered and 2 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin implements a circuit breaker around connection errors.
  6. #
  7. # https://gitlab.com/os85/httpx/wikis/Circuit-Breaker
  8. #
  9. 7 module CircuitBreaker
  10. 7 using URIExtensions
  11. 7 def self.load_dependencies(*)
  12. 49 require_relative "circuit_breaker/circuit"
  13. 49 require_relative "circuit_breaker/circuit_store"
  14. end
  15. 7 def self.extra_options(options)
  16. 49 options.merge(
  17. circuit_breaker_max_attempts: 3,
  18. circuit_breaker_reset_attempts_in: 60,
  19. circuit_breaker_break_in: 60,
  20. circuit_breaker_half_open_drip_rate: 1
  21. )
  22. end
  23. 7 module InstanceMethods
  24. 7 include HTTPX::Callbacks
  25. 7 def initialize(*)
  26. 49 super
  27. 49 @circuit_store = CircuitStore.new(@options)
  28. end
  29. 7 def initialize_dup(orig)
  30. super
  31. @circuit_store = orig.instance_variable_get(:@circuit_store).dup
  32. end
  33. 7 %i[circuit_open].each do |meth|
  34. 7 class_eval(<<-MOD, __FILE__, __LINE__ + 1)
  35. 1 def on_#{meth}(&blk) # def on_circuit_open(&blk)
  36. 1 on(:#{meth}, &blk) # on(:circuit_open, &blk)
  37. end # end
  38. MOD
  39. end
  40. 7 private
  41. 7 def send_requests(*requests)
  42. # @type var short_circuit_responses: Array[response]
  43. 196 short_circuit_responses = []
  44. # run all requests through the circuit breaker, see if the circuit is
  45. # open for any of them.
  46. 196 real_requests = requests.each_with_index.with_object([]) do |(req, idx), real_reqs|
  47. 196 short_circuit_response = @circuit_store.try_respond(req)
  48. 196 if short_circuit_response.nil?
  49. 154 real_reqs << req
  50. 154 next
  51. end
  52. 36 short_circuit_responses[idx] = short_circuit_response
  53. end
  54. # run requests for the remainder
  55. 196 unless real_requests.empty?
  56. 154 responses = super(*real_requests)
  57. 154 real_requests.each_with_index do |request, idx|
  58. 132 short_circuit_responses[requests.index(request)] = responses[idx]
  59. end
  60. end
  61. 196 short_circuit_responses
  62. end
  63. 7 def on_response(request, response)
  64. 154 emit(:circuit_open, request) if try_circuit_open(request, response)
  65. 154 super
  66. end
  67. 7 def try_circuit_open(request, response)
  68. 154 if response.is_a?(ErrorResponse)
  69. 96 case response.error
  70. when RequestTimeoutError
  71. 70 @circuit_store.try_open(request.uri, response)
  72. else
  73. 42 @circuit_store.try_open(request.origin, response)
  74. end
  75. 42 elsif (break_on = request.options.circuit_breaker_break_on) && break_on.call(response)
  76. 14 @circuit_store.try_open(request.uri, response)
  77. else
  78. 28 @circuit_store.try_close(request.uri)
  79. 8 nil
  80. end
  81. end
  82. end
  83. # adds support for the following options:
  84. #
  85. # :circuit_breaker_max_attempts :: the number of attempts the circuit allows, before it is opened (defaults to <tt>3</tt>).
  86. # :circuit_breaker_reset_attempts_in :: the time a circuit stays open at most, before it resets (defaults to <tt>60</tt>).
  87. # :circuit_breaker_break_on :: callable defining an alternative rule for a response to break
  88. # (i.e. <tt>->(res) { res.status == 429 } </tt>)
  89. # :circuit_breaker_break_in :: the time that must elapse before an open circuit can transit to the half-open state
  90. # (defaults to <tt><60</tt>).
  91. # :circuit_breaker_half_open_drip_rate :: the rate of requests a circuit allows to be performed when in an half-open state
  92. # (defaults to <tt>1</tt>).
  93. 7 module OptionsMethods
  94. 7 def option_circuit_breaker_max_attempts(value)
  95. 98 attempts = Integer(value)
  96. 98 raise TypeError, ":circuit_breaker_max_attempts must be positive" unless attempts.positive?
  97. 98 attempts
  98. end
  99. 7 def option_circuit_breaker_reset_attempts_in(value)
  100. 56 timeout = Float(value)
  101. 56 raise TypeError, ":circuit_breaker_reset_attempts_in must be positive" unless timeout.positive?
  102. 56 timeout
  103. end
  104. 7 def option_circuit_breaker_break_in(value)
  105. 77 timeout = Float(value)
  106. 77 raise TypeError, ":circuit_breaker_break_in must be positive" unless timeout.positive?
  107. 77 timeout
  108. end
  109. 7 def option_circuit_breaker_half_open_drip_rate(value)
  110. 77 ratio = Float(value)
  111. 77 raise TypeError, ":circuit_breaker_half_open_drip_rate must be a number between 0 and 1" unless (0..1).cover?(ratio)
  112. 77 ratio
  113. end
  114. 7 def option_circuit_breaker_break_on(value)
  115. 14 raise TypeError, ":circuit_breaker_break_on must be called with the response" unless value.respond_to?(:call)
  116. 14 value
  117. end
  118. end
  119. end
  120. 7 register_plugin :circuit_breaker, CircuitBreaker
  121. end
  122. end

lib/httpx/plugins/circuit_breaker/circuit.rb

100.0% lines covered

47 relevant lines. 47 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins::CircuitBreaker
  4. #
  5. # A circuit is assigned to a given absoolute url or origin.
  6. #
  7. # It sets +max_attempts+, the number of attempts the circuit allows, before it is opened.
  8. # It sets +reset_attempts_in+, the time a circuit stays open at most, before it resets.
  9. # It sets +break_in+, the time that must elapse before an open circuit can transit to the half-open state.
  10. # It sets +circuit_breaker_half_open_drip_rate+, the rate of requests a circuit allows to be performed when in an half-open state.
  11. #
  12. 7 class Circuit
  13. 7 def initialize(max_attempts, reset_attempts_in, break_in, circuit_breaker_half_open_drip_rate)
  14. 49 @max_attempts = max_attempts
  15. 49 @reset_attempts_in = reset_attempts_in
  16. 49 @break_in = break_in
  17. 49 @circuit_breaker_half_open_drip_rate = circuit_breaker_half_open_drip_rate
  18. 49 @attempts = 0
  19. 49 total_real_attempts = @max_attempts * @circuit_breaker_half_open_drip_rate
  20. 49 @drip_factor = (@max_attempts / total_real_attempts).round
  21. 49 @state = :closed
  22. end
  23. 7 def respond
  24. 196 try_close
  25. 168 case @state
  26. when :closed
  27. 34 nil
  28. when :half_open
  29. 42 @attempts += 1
  30. # do real requests while drip rate valid
  31. 49 if (@real_attempts % @drip_factor).zero?
  32. 30 @real_attempts += 1
  33. 30 return
  34. end
  35. 14 @response
  36. when :open
  37. 28 @response
  38. end
  39. end
  40. 7 def try_open(response)
  41. 108 case @state
  42. when :closed
  43. 105 now = Utils.now
  44. 105 if @attempts.positive?
  45. # reset if error happened long ago
  46. 42 @attempts = 0 if now - @attempted_at > @reset_attempts_in
  47. else
  48. 63 @attempted_at = now
  49. end
  50. 90 @attempts += 1
  51. 105 return unless @attempts >= @max_attempts
  52. 56 @state = :open
  53. 56 @opened_at = now
  54. 56 @response = response
  55. when :half_open
  56. # open immediately
  57. 21 @state = :open
  58. 21 @attempted_at = @opened_at = Utils.now
  59. 21 @response = response
  60. end
  61. end
  62. 7 def try_close
  63. 192 case @state
  64. when :closed
  65. 34 nil
  66. when :half_open
  67. # do not close circuit unless attempts exhausted
  68. 42 return unless @attempts >= @max_attempts
  69. # reset!
  70. 14 @attempts = 0
  71. 14 @opened_at = @attempted_at = @response = nil
  72. 14 @state = :closed
  73. when :open
  74. 63 if Utils.elapsed_time(@opened_at) > @break_in
  75. 35 @state = :half_open
  76. 35 @attempts = 0
  77. 35 @real_attempts = 0
  78. end
  79. end
  80. end
  81. end
  82. end
  83. end

lib/httpx/plugins/circuit_breaker/circuit_store.rb

100.0% lines covered

23 relevant lines. 23 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX::Plugins::CircuitBreaker
  3. 7 using HTTPX::URIExtensions
  4. 7 class CircuitStore
  5. 7 def initialize(options)
  6. 49 @circuits = Hash.new do |h, k|
  7. 42 h[k] = Circuit.new(
  8. options.circuit_breaker_max_attempts,
  9. options.circuit_breaker_reset_attempts_in,
  10. options.circuit_breaker_break_in,
  11. options.circuit_breaker_half_open_drip_rate
  12. )
  13. end
  14. 49 @circuits_mutex = Thread::Mutex.new
  15. end
  16. 7 def try_open(uri, response)
  17. 252 circuit = @circuits_mutex.synchronize { get_circuit_for_uri(uri) }
  18. 126 circuit.try_open(response)
  19. end
  20. 7 def try_close(uri)
  21. 28 circuit = @circuits_mutex.synchronize do
  22. 28 return unless @circuits.key?(uri.origin) || @circuits.key?(uri.to_s)
  23. 28 get_circuit_for_uri(uri)
  24. end
  25. 28 circuit.try_close
  26. end
  27. # if circuit is open, it'll respond with the stored response.
  28. # if not, nil.
  29. 7 def try_respond(request)
  30. 392 circuit = @circuits_mutex.synchronize { get_circuit_for_uri(request.uri) }
  31. 196 circuit.respond
  32. end
  33. 7 private
  34. 7 def get_circuit_for_uri(uri)
  35. 350 if uri.respond_to?(:origin) && @circuits.key?(uri.origin)
  36. 252 @circuits[uri.origin]
  37. else
  38. 98 @circuits[uri.to_s]
  39. end
  40. end
  41. end
  42. end

lib/httpx/plugins/cookies.rb

100.0% lines covered

51 relevant lines. 51 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 require "forwardable"
  3. 7 module HTTPX
  4. 7 module Plugins
  5. #
  6. # This plugin implements a persistent cookie jar for the duration of a session.
  7. #
  8. # It also adds a *#cookies* helper, so that you can pre-fill the cookies of a session.
  9. #
  10. # https://gitlab.com/os85/httpx/wikis/Cookies
  11. #
  12. 7 module Cookies
  13. 7 def self.load_dependencies(*)
  14. 126 require "httpx/plugins/cookies/jar"
  15. 126 require "httpx/plugins/cookies/cookie"
  16. 126 require "httpx/plugins/cookies/set_cookie_parser"
  17. end
  18. 7 module InstanceMethods
  19. 7 extend Forwardable
  20. 7 def_delegator :@options, :cookies
  21. 7 def initialize(options = {}, &blk)
  22. 252 super({ cookies: Jar.new }.merge(options), &blk)
  23. end
  24. 7 def wrap
  25. 14 return super unless block_given?
  26. 14 super do |session|
  27. 14 old_cookies_jar = @options.cookies.dup
  28. 1 begin
  29. 14 yield session
  30. ensure
  31. 14 @options = @options.merge(cookies: old_cookies_jar)
  32. end
  33. end
  34. end
  35. 7 def build_request(*)
  36. 280 request = super
  37. 280 request.headers.set_cookie(request.options.cookies[request.uri])
  38. 280 request
  39. end
  40. 7 private
  41. 7 def on_response(_request, response)
  42. 280 if response && response.respond_to?(:headers) && (set_cookie = response.headers["set-cookie"])
  43. 56 log { "cookies: set-cookie is over #{Cookie::MAX_LENGTH}" } if set_cookie.bytesize > Cookie::MAX_LENGTH
  44. 56 @options.cookies.parse(set_cookie)
  45. end
  46. 280 super
  47. end
  48. end
  49. 7 module HeadersMethods
  50. 7 def set_cookie(cookies)
  51. 280 return if cookies.empty?
  52. 238 header_value = cookies.sort.join("; ")
  53. 238 add("cookie", header_value)
  54. end
  55. end
  56. # adds support for the following options:
  57. #
  58. # :cookies :: cookie jar for the session (can be a Hash, an Array, an instance of HTTPX::Plugins::Cookies::CookieJar)
  59. 7 module OptionsMethods
  60. 7 def option_headers(*)
  61. 280 value = super
  62. 280 merge_cookie_in_jar(value.delete("cookie"), @cookies) if defined?(@cookies) && value.key?("cookie")
  63. 280 value
  64. end
  65. 7 def option_cookies(value)
  66. 420 jar = value.is_a?(Jar) ? value : Jar.new(value)
  67. 420 merge_cookie_in_jar(@headers.delete("cookie"), jar) if defined?(@headers) && @headers.key?("cookie")
  68. 420 jar
  69. end
  70. 7 private
  71. 7 def merge_cookie_in_jar(cookies, jar)
  72. 14 cookies.each do |ck|
  73. 14 ck.split(/ *; */).each do |cookie|
  74. 28 name, value = cookie.split("=", 2)
  75. 28 jar.add(Cookie.new(name, value))
  76. end
  77. end
  78. end
  79. end
  80. end
  81. 7 register_plugin :cookies, Cookies
  82. end
  83. end

lib/httpx/plugins/cookies/cookie.rb

100.0% lines covered

77 relevant lines. 77 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins::Cookies
  4. # The HTTP Cookie.
  5. #
  6. # Contains the single cookie info: name, value and attributes.
  7. 7 class Cookie
  8. 7 include Comparable
  9. # Maximum number of bytes per cookie (RFC 6265 6.1 requires 4096 at
  10. # least)
  11. 7 MAX_LENGTH = 4096
  12. 7 attr_reader :domain, :path, :name, :value, :created_at
  13. 7 def path=(path)
  14. 161 path = String(path)
  15. 161 @path = path.start_with?("/") ? path : "/"
  16. end
  17. # See #domain.
  18. 7 def domain=(domain)
  19. 35 domain = String(domain)
  20. 35 if domain.start_with?(".")
  21. 14 @for_domain = true
  22. 14 domain = domain[1..-1]
  23. end
  24. 35 return if domain.empty?
  25. 35 @domain_name = DomainName.new(domain)
  26. # RFC 6265 5.3 5.
  27. 35 @for_domain = false if @domain_name.domain.nil? # a public suffix or IP address
  28. 35 @domain = @domain_name.hostname
  29. end
  30. # Compares the cookie with another. When there are many cookies with
  31. # the same name for a URL, the value of the smallest must be used.
  32. 7 def <=>(other)
  33. # RFC 6265 5.4
  34. # Precedence: 1. longer path 2. older creation
  35. 608 (@name <=> other.name).nonzero? ||
  36. 53 (other.path.length <=> @path.length).nonzero? ||
  37. 31 (@created_at <=> other.created_at).nonzero? || 0
  38. end
  39. 7 class << self
  40. 7 def new(cookie, *args)
  41. 441 return cookie if cookie.is_a?(self)
  42. 441 super
  43. end
  44. # Tests if +target_path+ is under +base_path+ as described in RFC
  45. # 6265 5.1.4. +base_path+ must be an absolute path.
  46. # +target_path+ may be empty, in which case it is treated as the
  47. # root path.
  48. #
  49. # e.g.
  50. #
  51. # path_match?('/admin/', '/admin/index') == true
  52. # path_match?('/admin/', '/Admin/index') == false
  53. # path_match?('/admin/', '/admin/') == true
  54. # path_match?('/admin/', '/admin') == false
  55. #
  56. # path_match?('/admin', '/admin') == true
  57. # path_match?('/admin', '/Admin') == false
  58. # path_match?('/admin', '/admins') == false
  59. # path_match?('/admin', '/admin/') == true
  60. # path_match?('/admin', '/admin/index') == true
  61. 7 def path_match?(base_path, target_path)
  62. 1183 base_path.start_with?("/") || (return false)
  63. # RFC 6265 5.1.4
  64. 1183 bsize = base_path.size
  65. 1183 tsize = target_path.size
  66. 1183 return bsize == 1 if tsize.zero? # treat empty target_path as "/"
  67. 1183 return false unless target_path.start_with?(base_path)
  68. 1176 return true if bsize == tsize || base_path.end_with?("/")
  69. 14 target_path[bsize] == "/"
  70. end
  71. end
  72. 7 def initialize(arg, *attrs)
  73. 441 @created_at = Time.now
  74. 441 if attrs.empty?
  75. 21 attr_hash = Hash.try_convert(arg)
  76. else
  77. 420 @name = arg
  78. 420 @value, attr_hash = attrs
  79. 420 attr_hash = Hash.try_convert(attr_hash)
  80. end
  81. 33 attr_hash.each do |key, val|
  82. 273 key = key.downcase.tr("-", "_").to_sym unless key.is_a?(Symbol)
  83. 234 case key
  84. when :domain, :path
  85. 173 __send__(:"#{key}=", val)
  86. else
  87. 77 instance_variable_set(:"@#{key}", val)
  88. end
  89. 440 end if attr_hash
  90. 441 @path ||= "/"
  91. 441 raise ArgumentError, "name must be specified" if @name.nil?
  92. 441 @name = @name.to_s
  93. end
  94. 7 def expires
  95. 665 @expires || (@created_at && @max_age ? @created_at + @max_age : nil)
  96. end
  97. 7 def expired?(time = Time.now)
  98. 637 return false unless expires
  99. 28 expires <= time
  100. end
  101. # Returns a string for use in the Cookie header, i.e. `name=value`
  102. # or `name="value"`.
  103. 7 def cookie_value
  104. 414 "#{@name}=#{Scanner.quote(@value.to_s)}"
  105. end
  106. 7 alias_method :to_s, :cookie_value
  107. # Tests if it is OK to send this cookie to a given `uri`. A
  108. # RuntimeError is raised if the cookie's domain is unknown.
  109. 7 def valid_for_uri?(uri)
  110. 623 uri = URI(uri)
  111. # RFC 6265 5.4
  112. 623 return false if @secure && uri.scheme != "https"
  113. 616 acceptable_from_uri?(uri) && Cookie.path_match?(@path, uri.path)
  114. end
  115. 7 private
  116. # Tests if it is OK to accept this cookie if it is sent from a given
  117. # URI/URL, `uri`.
  118. 7 def acceptable_from_uri?(uri)
  119. 644 uri = URI(uri)
  120. 644 host = DomainName.new(uri.host)
  121. # RFC 6265 5.3
  122. 644 if host.hostname == @domain
  123. 14 true
  124. 629 elsif @for_domain # !host-only-flag
  125. 28 host.cookie_domain?(@domain_name)
  126. else
  127. 602 @domain.nil?
  128. end
  129. end
  130. 7 module Scanner
  131. 7 RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/.freeze
  132. 7 module_function
  133. 7 def quote(s)
  134. 483 return s unless s.match(RE_BAD_CHAR)
  135. 7 "\"#{s.gsub(/([\\"])/, "\\\\\\1")}\""
  136. end
  137. end
  138. end
  139. end
  140. end

lib/httpx/plugins/cookies/jar.rb

100.0% lines covered

47 relevant lines. 47 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins::Cookies
  4. # The Cookie Jar
  5. #
  6. # It holds a bunch of cookies.
  7. 7 class Jar
  8. 7 using URIExtensions
  9. 7 include Enumerable
  10. 7 def initialize_dup(orig)
  11. 189 super
  12. 189 @cookies = orig.instance_variable_get(:@cookies).dup
  13. end
  14. 7 def initialize(cookies = nil)
  15. 469 @cookies = []
  16. 120 cookies.each do |elem|
  17. 154 cookie = case elem
  18. when Cookie
  19. 14 elem
  20. when Array
  21. 126 Cookie.new(*elem)
  22. else
  23. 14 Cookie.new(elem)
  24. end
  25. 154 @cookies << cookie
  26. 468 end if cookies
  27. end
  28. 7 def parse(set_cookie)
  29. 126 SetCookieParser.call(set_cookie) do |name, value, attrs|
  30. 182 add(Cookie.new(name, value, attrs))
  31. end
  32. end
  33. 7 def add(cookie, path = nil)
  34. 399 c = cookie.dup
  35. 399 c.path = path if path && c.path == "/"
  36. # If the user agent receives a new cookie with the same cookie-name, domain-value, and path-value
  37. # as a cookie that it has already stored, the existing cookie is evicted and replaced with the new cookie.
  38. 756 @cookies.delete_if { |ck| ck.name == c.name && ck.domain == c.domain && ck.path == c.path }
  39. 399 @cookies << c
  40. end
  41. 7 def [](uri)
  42. 413 each(uri).sort
  43. end
  44. 7 def each(uri = nil, &blk)
  45. 1036 return enum_for(__method__, uri) unless blk
  46. 595 return @cookies.each(&blk) unless uri
  47. 413 uri = URI(uri)
  48. 413 now = Time.now
  49. 413 tpath = uri.path
  50. 413 @cookies.delete_if do |cookie|
  51. 637 if cookie.expired?(now)
  52. 14 true
  53. else
  54. 623 yield cookie if cookie.valid_for_uri?(uri) && Cookie.path_match?(cookie.path, tpath)
  55. 623 false
  56. end
  57. end
  58. end
  59. 7 def merge(other)
  60. 175 cookies_dup = dup
  61. 175 other.each do |elem|
  62. 189 cookie = case elem
  63. when Cookie
  64. 175 elem
  65. when Array
  66. 7 Cookie.new(*elem)
  67. else
  68. 7 Cookie.new(elem)
  69. end
  70. 189 cookies_dup.add(cookie)
  71. end
  72. 175 cookies_dup
  73. end
  74. end
  75. end
  76. end

lib/httpx/plugins/cookies/set_cookie_parser.rb

100.0% lines covered

70 relevant lines. 70 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 require "strscan"
  3. 7 require "time"
  4. 7 module HTTPX
  5. 7 module Plugins::Cookies
  6. 7 module SetCookieParser
  7. # Whitespace.
  8. 7 RE_WSP = /[ \t]+/.freeze
  9. # A pattern that matches a cookie name or attribute name which may
  10. # be empty, capturing trailing whitespace.
  11. 7 RE_NAME = /(?!#{RE_WSP})[^,;\\"=]*/.freeze
  12. 7 RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/.freeze
  13. # A pattern that matches the comma in a (typically date) value.
  14. 7 RE_COOKIE_COMMA = /,(?=#{RE_WSP}?#{RE_NAME}=)/.freeze
  15. 7 module_function
  16. 7 def scan_dquoted(scanner)
  17. 14 s = +""
  18. 20 until scanner.eos?
  19. 56 break if scanner.skip(/"/)
  20. 42 if scanner.skip(/\\/)
  21. 14 s << scanner.getch
  22. 27 elsif scanner.scan(/[^"\\]+/)
  23. 28 s << scanner.matched
  24. end
  25. end
  26. 14 s
  27. end
  28. 7 def scan_value(scanner, comma_as_separator = false)
  29. 385 value = +""
  30. 443 until scanner.eos?
  31. 665 if scanner.scan(/[^,;"]+/)
  32. 378 value << scanner.matched
  33. 286 elsif scanner.skip(/"/)
  34. # RFC 6265 2.2
  35. # A cookie-value may be DQUOTE'd.
  36. 14 value << scan_dquoted(scanner)
  37. 272 elsif scanner.check(/;/)
  38. 203 break
  39. 69 elsif comma_as_separator && scanner.check(RE_COOKIE_COMMA)
  40. 56 break
  41. else
  42. 14 value << scanner.getch
  43. end
  44. end
  45. 385 value.rstrip!
  46. 385 value
  47. end
  48. 7 def scan_name_value(scanner, comma_as_separator = false)
  49. 385 name = scanner.scan(RE_NAME)
  50. 385 name.rstrip! if name
  51. 385 if scanner.skip(/=/)
  52. 378 value = scan_value(scanner, comma_as_separator)
  53. else
  54. 7 scan_value(scanner, comma_as_separator)
  55. 7 value = nil
  56. end
  57. 385 [name, value]
  58. end
  59. 7 def call(set_cookie)
  60. 126 scanner = StringScanner.new(set_cookie)
  61. # RFC 6265 4.1.1 & 5.2
  62. 152 until scanner.eos?
  63. 182 start = scanner.pos
  64. 182 len = nil
  65. 182 scanner.skip(RE_WSP)
  66. 182 name, value = scan_name_value(scanner, true)
  67. 182 value = nil if name.empty?
  68. 182 attrs = {}
  69. 211 until scanner.eos?
  70. 259 if scanner.skip(/,/)
  71. # The comma is used as separator for concatenating multiple
  72. # values of a header.
  73. 56 len = (scanner.pos - 1) - start
  74. 56 break
  75. 202 elsif scanner.skip(/;/)
  76. 203 scanner.skip(RE_WSP)
  77. 203 aname, avalue = scan_name_value(scanner, true)
  78. 203 next if aname.empty? || value.nil?
  79. 203 aname.downcase!
  80. 174 case aname
  81. when "expires"
  82. # RFC 6265 5.2.1
  83. 14 (avalue &&= Time.parse(avalue)) || next
  84. when "max-age"
  85. # RFC 6265 5.2.2
  86. 7 next unless /\A-?\d+\z/.match?(avalue)
  87. 7 avalue = Integer(avalue)
  88. when "domain"
  89. # RFC 6265 5.2.3
  90. # An empty value SHOULD be ignored.
  91. 21 next if avalue.nil? || avalue.empty?
  92. when "path"
  93. # RFC 6265 5.2.4
  94. # A relative path must be ignored rather than normalizing it
  95. # to "/".
  96. 154 next unless avalue.start_with?("/")
  97. when "secure", "httponly"
  98. # RFC 6265 5.2.5, 5.2.6
  99. 6 avalue = true
  100. end
  101. 174 attrs[aname] = avalue
  102. end
  103. end
  104. 182 len ||= scanner.pos - start
  105. 182 next if len > Cookie::MAX_LENGTH
  106. 182 yield(name, value, attrs) if name && !name.empty? && value
  107. end
  108. end
  109. end
  110. end
  111. end

lib/httpx/plugins/digest_auth.rb

100.0% lines covered

29 relevant lines. 29 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin adds helper methods to implement HTTP Digest Auth (https://datatracker.ietf.org/doc/html/rfc7616)
  6. #
  7. # https://gitlab.com/os85/httpx/wikis/Auth#digest-auth
  8. #
  9. 7 module DigestAuth
  10. 7 DigestError = Class.new(Error)
  11. 7 class << self
  12. 7 def extra_options(options)
  13. 140 options.merge(max_concurrent_requests: 1)
  14. end
  15. 7 def load_dependencies(*)
  16. 140 require_relative "auth/digest"
  17. end
  18. end
  19. # adds support for the following options:
  20. #
  21. # :digest :: instance of HTTPX::Plugins::Authentication::Digest, used to authenticate requests in the session.
  22. 7 module OptionsMethods
  23. 7 def option_digest(value)
  24. 280 raise TypeError, ":digest must be a #{Authentication::Digest}" unless value.is_a?(Authentication::Digest)
  25. 280 value
  26. end
  27. end
  28. 7 module InstanceMethods
  29. 7 def digest_auth(user, password, hashed: false)
  30. 140 with(digest: Authentication::Digest.new(user, password, hashed: hashed))
  31. end
  32. 7 private
  33. 7 def send_requests(*requests)
  34. 168 requests.flat_map do |request|
  35. 168 digest = request.options.digest
  36. 168 next super(request) unless digest
  37. 280 probe_response = wrap { super(request).first }
  38. 140 return probe_response unless probe_response.is_a?(Response)
  39. 140 if probe_response.status == 401 && digest.can_authenticate?(probe_response.headers["www-authenticate"])
  40. 126 request.transition(:idle)
  41. 108 request.headers["authorization"] = digest.authenticate(request, probe_response.headers["www-authenticate"])
  42. 126 super(request)
  43. else
  44. 14 probe_response
  45. end
  46. end
  47. end
  48. end
  49. end
  50. 7 register_plugin :digest_auth, DigestAuth
  51. end
  52. end

lib/httpx/plugins/expect.rb

100.0% lines covered

56 relevant lines. 56 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin makes all HTTP/1.1 requests with a body send the "Expect: 100-continue".
  6. #
  7. # https://gitlab.com/os85/httpx/wikis/Expect#expect
  8. #
  9. 7 module Expect
  10. 7 EXPECT_TIMEOUT = 2
  11. 7 class << self
  12. 7 def no_expect_store
  13. 133 @no_expect_store ||= []
  14. end
  15. 7 def extra_options(options)
  16. 168 options.merge(expect_timeout: EXPECT_TIMEOUT)
  17. end
  18. end
  19. # adds support for the following options:
  20. #
  21. # :expect_timeout :: time (in seconds) to wait for a 100-expect response,
  22. # before retrying without the Expect header (defaults to <tt>2</tt>).
  23. # :expect_threshold_size :: min threshold (in bytes) of the request payload to enable the 100-continue negotiation on.
  24. 7 module OptionsMethods
  25. 7 def option_expect_timeout(value)
  26. 294 seconds = Float(value)
  27. 294 raise TypeError, ":expect_timeout must be positive" unless seconds.positive?
  28. 294 seconds
  29. end
  30. 7 def option_expect_threshold_size(value)
  31. 14 bytes = Integer(value)
  32. 14 raise TypeError, ":expect_threshold_size must be positive" unless bytes.positive?
  33. 14 bytes
  34. end
  35. end
  36. 7 module RequestMethods
  37. 7 def initialize(*)
  38. 196 super
  39. 196 return if @body.empty?
  40. 126 threshold = @options.expect_threshold_size
  41. 126 return if threshold && !@body.unbounded_body? && @body.bytesize < threshold
  42. 112 return if Expect.no_expect_store.include?(origin)
  43. 90 @headers["expect"] = "100-continue"
  44. end
  45. 7 def response=(response)
  46. 161 if response.is_a?(Response) &&
  47. response.status == 100 &&
  48. !@headers.key?("expect") &&
  49. 2 (@state == :body || @state == :done)
  50. # if we're past this point, this means that we just received a 100-Continue response,
  51. # but the request doesn't have the expect flag, and is already flushing (or flushed) the body.
  52. #
  53. # this means that expect was deactivated for this request too soon, i.e. response took longer.
  54. #
  55. # so we have to reactivate it again.
  56. 6 @headers["expect"] = "100-continue"
  57. 7 @informational_status = 100
  58. 7 Expect.no_expect_store.delete(origin)
  59. end
  60. 161 super
  61. end
  62. end
  63. 7 module ConnectionMethods
  64. 7 def send_request_to_parser(request)
  65. 98 super
  66. 98 return unless request.headers["expect"] == "100-continue"
  67. 70 expect_timeout = request.options.expect_timeout
  68. 70 return if expect_timeout.nil? || expect_timeout.infinite?
  69. 70 set_request_timeout(request, expect_timeout, :expect, %i[body response]) do
  70. # expect timeout expired
  71. 14 if request.state == :expect && !request.expects?
  72. 14 Expect.no_expect_store << request.origin
  73. 14 request.headers.delete("expect")
  74. 14 consume
  75. end
  76. end
  77. end
  78. end
  79. 7 module InstanceMethods
  80. 7 def fetch_response(request, connections, options)
  81. 364 response = @responses.delete(request)
  82. 364 return unless response
  83. 98 if response.is_a?(Response) && response.status == 417 && request.headers.key?("expect")
  84. 14 response.close
  85. 14 request.headers.delete("expect")
  86. 14 request.transition(:idle)
  87. 14 send_request(request, connections, options)
  88. 12 return
  89. end
  90. 84 response
  91. end
  92. end
  93. end
  94. 7 register_plugin :expect, Expect
  95. end
  96. end

lib/httpx/plugins/follow_redirects.rb

100.0% lines covered

105 relevant lines. 105 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 module HTTPX
  3. 13 InsecureRedirectError = Class.new(Error)
  4. 13 module Plugins
  5. #
  6. # This plugin adds support for automatically following redirect (status 30X) responses.
  7. #
  8. # It has a default upper bound of followed redirects (see *MAX_REDIRECTS* and the *max_redirects* option),
  9. # after which it will return the last redirect response. It will **not** raise an exception.
  10. #
  11. # It doesn't follow insecure redirects (https -> http) by default (see *follow_insecure_redirects*).
  12. #
  13. # It doesn't propagate authorization related headers to requests redirecting to different origins
  14. # (see *allow_auth_to_other_origins*) to override.
  15. #
  16. # It allows customization of when to redirect via the *redirect_on* callback option).
  17. #
  18. # https://gitlab.com/os85/httpx/wikis/Follow-Redirects
  19. #
  20. 13 module FollowRedirects
  21. 13 MAX_REDIRECTS = 3
  22. 13 REDIRECT_STATUS = (300..399).freeze
  23. 13 REQUEST_BODY_HEADERS = %w[transfer-encoding content-encoding content-type content-length content-language content-md5 trailer].freeze
  24. 13 using URIExtensions
  25. # adds support for the following options:
  26. #
  27. # :max_redirects :: max number of times a request will be redirected (defaults to <tt>3</tt>).
  28. # :follow_insecure_redirects :: whether redirects to an "http://" URI, when coming from an "https//", are allowed
  29. # (defaults to <tt>false</tt>).
  30. # :allow_auth_to_other_origins :: whether auth-related headers, such as "Authorization", are propagated on redirection
  31. # (defaults to <tt>false</tt>).
  32. # :redirect_on :: optional callback which receives the redirect location and can halt the redirect chain if it returns <tt>false</tt>.
  33. 13 module OptionsMethods
  34. 13 def option_max_redirects(value)
  35. 403 num = Integer(value)
  36. 403 raise TypeError, ":max_redirects must be positive" if num.negative?
  37. 403 num
  38. end
  39. 13 def option_follow_insecure_redirects(value)
  40. 21 value
  41. end
  42. 13 def option_allow_auth_to_other_origins(value)
  43. 21 value
  44. end
  45. 13 def option_redirect_on(value)
  46. 42 raise TypeError, ":redirect_on must be callable" unless value.respond_to?(:call)
  47. 42 value
  48. end
  49. end
  50. 13 module InstanceMethods
  51. # returns a session with the *max_redirects* option set to +n+
  52. 13 def max_redirects(n)
  53. 42 with(max_redirects: n.to_i)
  54. end
  55. 13 private
  56. 13 def fetch_response(request, connections, options)
  57. 133974 redirect_request = request.redirect_request
  58. 133974 response = super(redirect_request, connections, options)
  59. 133974 return unless response
  60. 495 max_redirects = redirect_request.max_redirects
  61. 495 return response unless response.is_a?(Response)
  62. 481 return response unless REDIRECT_STATUS.include?(response.status) && response.headers.key?("location")
  63. 314 return response unless max_redirects.positive?
  64. 286 redirect_uri = __get_location_from_response(response)
  65. 286 if options.redirect_on
  66. 28 redirect_allowed = options.redirect_on.call(redirect_uri)
  67. 28 return response unless redirect_allowed
  68. end
  69. # build redirect request
  70. 272 request_body = redirect_request.body
  71. 272 redirect_method = "GET"
  72. 272 redirect_params = {}
  73. 272 if response.status == 305 && options.respond_to?(:proxy)
  74. 7 request_body.rewind
  75. # The requested resource MUST be accessed through the proxy given by
  76. # the Location field. The Location field gives the URI of the proxy.
  77. 7 redirect_options = options.merge(headers: redirect_request.headers,
  78. proxy: { uri: redirect_uri },
  79. max_redirects: max_redirects - 1)
  80. 6 redirect_params[:body] = request_body
  81. 7 redirect_uri = redirect_request.uri
  82. 7 options = redirect_options
  83. else
  84. 265 redirect_headers = redirect_request_headers(redirect_request.uri, redirect_uri, request.headers, options)
  85. 265 redirect_opts = Hash[options]
  86. 228 redirect_params[:max_redirects] = max_redirects - 1
  87. 265 unless request_body.empty?
  88. 21 if response.status == 307
  89. # The method and the body of the original request are reused to perform the redirected request.
  90. 7 redirect_method = redirect_request.verb
  91. 7 request_body.rewind
  92. 6 redirect_params[:body] = request_body
  93. else
  94. # redirects are **ALWAYS** GET, so remove body-related headers
  95. 14 REQUEST_BODY_HEADERS.each do |h|
  96. 98 redirect_headers.delete(h)
  97. end
  98. 12 redirect_params[:body] = nil
  99. end
  100. end
  101. 265 options = options.class.new(redirect_opts.merge(headers: redirect_headers.to_h))
  102. end
  103. 272 redirect_uri = Utils.to_uri(redirect_uri)
  104. 272 if !options.follow_insecure_redirects &&
  105. response.uri.scheme == "https" &&
  106. redirect_uri.scheme == "http"
  107. 7 error = InsecureRedirectError.new(redirect_uri.to_s)
  108. 7 error.set_backtrace(caller)
  109. 6 return ErrorResponse.new(request, error)
  110. end
  111. 265 retry_request = build_request(redirect_method, redirect_uri, redirect_params, options)
  112. 265 request.redirect_request = retry_request
  113. 265 redirect_after = response.headers["retry-after"]
  114. 265 if redirect_after
  115. # Servers send the "Retry-After" header field to indicate how long the
  116. # user agent ought to wait before making a follow-up request.
  117. # When sent with any 3xx (Redirection) response, Retry-After indicates
  118. # the minimum time that the user agent is asked to wait before issuing
  119. # the redirected request.
  120. #
  121. 25 redirect_after = Utils.parse_retry_after(redirect_after)
  122. 25 log { "redirecting after #{redirect_after} secs..." }
  123. 25 deactivate_connection(request, connections, options)
  124. 25 pool.after(redirect_after) do
  125. 25 if request.response
  126. # request has terminated abruptly meanwhile
  127. 11 retry_request.emit(:response, request.response)
  128. else
  129. 14 send_request(retry_request, connections, options)
  130. end
  131. end
  132. else
  133. 240 send_request(retry_request, connections, options)
  134. end
  135. 74 nil
  136. end
  137. # :nodoc:
  138. 13 def redirect_request_headers(original_uri, redirect_uri, headers, options)
  139. 265 headers = headers.dup
  140. 265 return headers if options.allow_auth_to_other_origins
  141. 258 return headers unless headers.key?("authorization")
  142. 7 return headers if original_uri.origin == redirect_uri.origin
  143. 7 headers.delete("authorization")
  144. 7 headers
  145. end
  146. # :nodoc:
  147. 13 def __get_location_from_response(response)
  148. # @type var location_uri: http_uri
  149. 286 location_uri = URI(response.headers["location"])
  150. 286 location_uri = response.uri.merge(location_uri) if location_uri.relative?
  151. 286 location_uri
  152. end
  153. end
  154. 13 module RequestMethods
  155. # returns the top-most original HTTPX::Request from the redirect chain
  156. 13 attr_accessor :root_request
  157. # returns the follow-up redirect request, or itself
  158. 13 def redirect_request
  159. 133974 @redirect_request || self
  160. end
  161. # sets the follow-up redirect request
  162. 13 def redirect_request=(req)
  163. 265 @redirect_request = req
  164. 265 req.root_request = @root_request || self
  165. 265 @response = nil
  166. end
  167. 13 def response
  168. 1639 return super unless @redirect_request && @response.nil?
  169. 57 @redirect_request.response
  170. end
  171. 13 def max_redirects
  172. 495 @options.max_redirects || MAX_REDIRECTS
  173. end
  174. end
  175. 13 module ConnectionMethods
  176. 13 private
  177. 13 def set_request_request_timeout(request)
  178. 474 return unless request.root_request.nil?
  179. 225 super
  180. end
  181. end
  182. end
  183. 13 register_plugin :follow_redirects, FollowRedirects
  184. end
  185. end

lib/httpx/plugins/grpc.rb

100.0% lines covered

133 relevant lines. 133 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 5 module HTTPX
  3. 5 GRPCError = Class.new(Error) do
  4. 5 attr_reader :status, :details, :metadata
  5. 5 def initialize(status, details, metadata)
  6. 20 @status = status
  7. 20 @details = details
  8. 20 @metadata = metadata
  9. 20 super("GRPC error, code=#{status}, details=#{details}, metadata=#{metadata}")
  10. end
  11. end
  12. 5 module Plugins
  13. #
  14. # This plugin adds DSL to build GRPC interfaces.
  15. #
  16. # https://gitlab.com/os85/httpx/wikis/GRPC
  17. #
  18. 5 module GRPC
  19. 5 unless String.method_defined?(:underscore)
  20. 5 module StringExtensions
  21. 5 refine String do
  22. 5 def underscore
  23. 260 s = dup # Avoid mutating the argument, as it might be frozen.
  24. 260 s.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
  25. 260 s.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
  26. 260 s.tr!("-", "_")
  27. 260 s.downcase!
  28. 260 s
  29. end
  30. end
  31. end
  32. 5 using StringExtensions
  33. end
  34. 5 DEADLINE = 60
  35. 5 MARSHAL_METHOD = :encode
  36. 5 UNMARSHAL_METHOD = :decode
  37. 5 HEADERS = {
  38. "content-type" => "application/grpc",
  39. "te" => "trailers",
  40. "accept" => "application/grpc",
  41. # metadata fits here
  42. # ex "foo-bin" => base64("bar")
  43. }.freeze
  44. 5 class << self
  45. 5 def load_dependencies(*)
  46. 115 require "stringio"
  47. 115 require "httpx/plugins/grpc/grpc_encoding"
  48. 115 require "httpx/plugins/grpc/message"
  49. 115 require "httpx/plugins/grpc/call"
  50. end
  51. 5 def configure(klass)
  52. 115 klass.plugin(:persistent)
  53. 115 klass.plugin(:stream)
  54. end
  55. 5 def extra_options(options)
  56. 115 options.merge(
  57. fallback_protocol: "h2",
  58. grpc_rpcs: {}.freeze,
  59. grpc_compression: false,
  60. grpc_deadline: DEADLINE
  61. )
  62. end
  63. end
  64. 5 module OptionsMethods
  65. 5 def option_grpc_service(value)
  66. 100 String(value)
  67. end
  68. 5 def option_grpc_compression(value)
  69. 135 case value
  70. when true, false
  71. 115 value
  72. else
  73. 20 value.to_s
  74. end
  75. end
  76. 5 def option_grpc_rpcs(value)
  77. 930 Hash[value]
  78. end
  79. 5 def option_grpc_deadline(value)
  80. 670 raise TypeError, ":grpc_deadline must be positive" unless value.positive?
  81. 670 value
  82. end
  83. 5 def option_call_credentials(value)
  84. 15 raise TypeError, ":call_credentials must respond to #call" unless value.respond_to?(:call)
  85. 15 value
  86. end
  87. end
  88. 5 module ResponseMethods
  89. 5 attr_reader :trailing_metadata
  90. 5 def merge_headers(trailers)
  91. 95 @trailing_metadata = Hash[trailers]
  92. 95 super
  93. end
  94. end
  95. 5 module RequestBodyMethods
  96. 5 def initialize(*, **)
  97. 105 super
  98. 105 if (compression = @headers["grpc-encoding"])
  99. 10 deflater_body = self.class.initialize_deflater_body(@body, compression)
  100. 10 @body = Transcoder::GRPCEncoding.encode(deflater_body || @body, compressed: !deflater_body.nil?)
  101. else
  102. 95 @body = Transcoder::GRPCEncoding.encode(@body, compressed: false)
  103. end
  104. end
  105. end
  106. 5 module InstanceMethods
  107. 5 def with_channel_credentials(ca_path, key = nil, cert = nil, **ssl_opts)
  108. # @type var ssl_params: ::Hash[::Symbol, untyped]
  109. 60 ssl_params = {
  110. **ssl_opts,
  111. ca_file: ca_path,
  112. }
  113. 60 if key
  114. 60 key = File.read(key) if File.file?(key)
  115. 60 ssl_params[:key] = OpenSSL::PKey.read(key)
  116. end
  117. 60 if cert
  118. 60 cert = File.read(cert) if File.file?(cert)
  119. 60 ssl_params[:cert] = OpenSSL::X509::Certificate.new(cert)
  120. end
  121. 60 with(ssl: ssl_params)
  122. end
  123. 5 def rpc(rpc_name, input, output, **opts)
  124. 260 rpc_name = rpc_name.to_s
  125. 260 raise Error, "rpc #{rpc_name} already defined" if @options.grpc_rpcs.key?(rpc_name)
  126. rpc_opts = {
  127. 260 deadline: @options.grpc_deadline,
  128. }.merge(opts)
  129. 260 local_rpc_name = rpc_name.underscore
  130. 260 session_class = Class.new(self.class) do
  131. # define rpc method with ruby style name
  132. 260 class_eval(<<-OUT, __FILE__, __LINE__ + 1)
  133. def #{local_rpc_name}(input, **opts) # def grpc_action(input, **opts)
  134. rpc_execute("#{local_rpc_name}", input, **opts) # rpc_execute("grpc_action", input, **opts)
  135. end # end
  136. OUT
  137. # define rpc method with original name
  138. 260 unless local_rpc_name == rpc_name
  139. 10 class_eval(<<-OUT, __FILE__, __LINE__ + 1)
  140. def #{rpc_name}(input, **opts) # def grpcAction(input, **opts)
  141. rpc_execute("#{local_rpc_name}", input, **opts) # rpc_execute("grpc_action", input, **opts)
  142. end # end
  143. OUT
  144. end
  145. end
  146. 260 session_class.new(@options.merge(
  147. grpc_rpcs: @options.grpc_rpcs.merge(
  148. local_rpc_name => [rpc_name, input, output, rpc_opts]
  149. ).freeze
  150. ))
  151. end
  152. 5 def build_stub(origin, service: nil, compression: false)
  153. 115 scheme = @options.ssl.empty? ? "http" : "https"
  154. 115 origin = URI.parse("#{scheme}://#{origin}")
  155. 115 session = self
  156. 115 if service && service.respond_to?(:rpc_descs)
  157. # it's a grpc generic service
  158. 50 service.rpc_descs.each do |rpc_name, rpc_desc|
  159. rpc_opts = {
  160. 250 marshal_method: rpc_desc.marshal_method,
  161. unmarshal_method: rpc_desc.unmarshal_method,
  162. }
  163. 250 input = rpc_desc.input
  164. 250 input = input.type if input.respond_to?(:type)
  165. 250 output = rpc_desc.output
  166. 250 if output.respond_to?(:type)
  167. 100 rpc_opts[:stream] = true
  168. 100 output = output.type
  169. end
  170. 250 session = session.rpc(rpc_name, input, output, **rpc_opts)
  171. end
  172. 50 service = service.service_name
  173. end
  174. 115 session.with(origin: origin, grpc_service: service, grpc_compression: compression)
  175. end
  176. 5 def execute(rpc_method, input,
  177. deadline: DEADLINE,
  178. metadata: nil,
  179. **opts)
  180. 105 grpc_request = build_grpc_request(rpc_method, input, deadline: deadline, metadata: metadata, **opts)
  181. 105 response = request(grpc_request, **opts)
  182. 105 response.raise_for_status unless opts[:stream]
  183. 95 GRPC::Call.new(response)
  184. end
  185. 5 private
  186. 5 def rpc_execute(rpc_name, input, **opts)
  187. 50 rpc_name, input_enc, output_enc, rpc_opts = @options.grpc_rpcs[rpc_name]
  188. 50 exec_opts = rpc_opts.merge(opts)
  189. 50 marshal_method ||= exec_opts.delete(:marshal_method) || MARSHAL_METHOD
  190. 50 unmarshal_method ||= exec_opts.delete(:unmarshal_method) || UNMARSHAL_METHOD
  191. 50 messages = if input.respond_to?(:each)
  192. 20 Enumerator.new do |y|
  193. 20 input.each do |message|
  194. 40 y << input_enc.__send__(marshal_method, message)
  195. end
  196. end
  197. else
  198. 30 input_enc.__send__(marshal_method, input)
  199. end
  200. 50 call = execute(rpc_name, messages, **exec_opts)
  201. 50 call.decoder = output_enc.method(unmarshal_method)
  202. 50 call
  203. end
  204. 5 def build_grpc_request(rpc_method, input, deadline:, metadata: nil, **)
  205. 105 uri = @options.origin.dup
  206. 105 rpc_method = "/#{rpc_method}" unless rpc_method.start_with?("/")
  207. 105 rpc_method = "/#{@options.grpc_service}#{rpc_method}" if @options.grpc_service
  208. 105 uri.path = rpc_method
  209. 105 headers = HEADERS.merge(
  210. "grpc-accept-encoding" => ["identity", *@options.supported_compression_formats]
  211. )
  212. 105 unless deadline == Float::INFINITY
  213. # convert to milliseconds
  214. 105 deadline = (deadline * 1000.0).to_i
  215. 105 headers["grpc-timeout"] = "#{deadline}m"
  216. end
  217. 105 headers = headers.merge(metadata.transform_keys(&:to_s)) if metadata
  218. # prepare compressor
  219. 105 compression = @options.grpc_compression == true ? "gzip" : @options.grpc_compression
  220. 105 headers["grpc-encoding"] = compression if compression
  221. 105 headers.merge!(@options.call_credentials.call.transform_keys(&:to_s)) if @options.call_credentials
  222. 105 build_request("POST", uri, headers: headers, body: input)
  223. end
  224. end
  225. end
  226. 5 register_plugin :grpc, GRPC
  227. end
  228. end

lib/httpx/plugins/grpc/call.rb

90.91% lines covered

33 relevant lines. 30 lines covered and 3 lines missed.
    
  1. # frozen_string_literal: true
  2. 5 module HTTPX
  3. 5 module Plugins
  4. 5 module GRPC
  5. # Encapsulates call information
  6. 5 class Call
  7. 5 attr_writer :decoder
  8. 5 def initialize(response)
  9. 95 @response = response
  10. 130 @decoder = ->(z) { z }
  11. 95 @consumed = false
  12. 95 @grpc_response = nil
  13. end
  14. 5 def inspect
  15. "#GRPC::Call(#{grpc_response})"
  16. end
  17. 5 def to_s
  18. 55 grpc_response.to_s
  19. end
  20. 5 def metadata
  21. response.headers
  22. end
  23. 5 def trailing_metadata
  24. 60 return unless @consumed
  25. 40 @response.trailing_metadata
  26. end
  27. 5 private
  28. 5 def grpc_response
  29. 155 @grpc_response ||= if @response.respond_to?(:each)
  30. 20 Enumerator.new do |y|
  31. 20 Message.stream(@response).each do |message|
  32. 40 y << @decoder.call(message)
  33. end
  34. 20 @consumed = true
  35. end
  36. else
  37. 75 @consumed = true
  38. 75 @decoder.call(Message.unary(@response))
  39. end
  40. end
  41. 5 def respond_to_missing?(meth, *args, &blk)
  42. 20 grpc_response.respond_to?(meth, *args) || super
  43. end
  44. 5 def method_missing(meth, *args, &blk)
  45. 40 return grpc_response.__send__(meth, *args, &blk) if grpc_response.respond_to?(meth)
  46. super
  47. end
  48. end
  49. end
  50. end
  51. end

lib/httpx/plugins/grpc/grpc_encoding.rb

97.83% lines covered

46 relevant lines. 45 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 5 module HTTPX
  3. 5 module Transcoder
  4. 5 module GRPCEncoding
  5. 5 class Deflater
  6. 5 extend Forwardable
  7. 5 attr_reader :content_type
  8. 5 def initialize(body, compressed:)
  9. 105 @content_type = body.content_type
  10. 105 @body = BodyReader.new(body)
  11. 105 @compressed = compressed
  12. end
  13. 5 def bytesize
  14. 335 return @body.bytesize if @body.respond_to?(:bytesize)
  15. Float::INFINITY
  16. end
  17. 5 def read(length = nil, outbuf = nil)
  18. 220 buf = @body.read(length, outbuf)
  19. 210 return unless buf
  20. 115 compressed_flag = @compressed ? 1 : 0
  21. 115 buf = outbuf if outbuf
  22. 115 buf.prepend([compressed_flag, buf.bytesize].pack("CL>"))
  23. 115 buf
  24. end
  25. end
  26. 5 class Inflater
  27. 5 def initialize(response)
  28. 75 @response = response
  29. 75 @grpc_encodings = nil
  30. end
  31. 5 def call(message, &blk)
  32. 95 data = "".b
  33. 95 until message.empty?
  34. 95 compressed, size = message.unpack("CL>")
  35. 95 encoded_data = message.byteslice(5..size + 5 - 1)
  36. 95 if compressed == 1
  37. 10 grpc_encodings.reverse_each do |encoding|
  38. 10 decoder = @response.body.class.initialize_inflater_by_encoding(encoding, @response, bytesize: encoded_data.bytesize)
  39. 10 encoded_data = decoder.call(encoded_data)
  40. 10 blk.call(encoded_data) if blk
  41. 10 data << encoded_data
  42. end
  43. else
  44. 85 blk.call(encoded_data) if blk
  45. 85 data << encoded_data
  46. end
  47. 95 message = message.byteslice((size + 5)..-1)
  48. end
  49. 95 data
  50. end
  51. 5 private
  52. 5 def grpc_encodings
  53. 10 @grpc_encodings ||= @response.headers.get("grpc-encoding")
  54. end
  55. end
  56. 5 def self.encode(*args, **kwargs)
  57. 105 Deflater.new(*args, **kwargs)
  58. end
  59. 5 def self.decode(response)
  60. 75 Inflater.new(response)
  61. end
  62. end
  63. end
  64. end

lib/httpx/plugins/grpc/message.rb

95.83% lines covered

24 relevant lines. 23 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 5 module HTTPX
  3. 5 module Plugins
  4. 5 module GRPC
  5. # Encoding module for GRPC responses
  6. #
  7. # Can encode and decode grpc messages.
  8. 5 module Message
  9. 5 module_function
  10. # decodes a unary grpc response
  11. 5 def unary(response)
  12. 75 verify_status(response)
  13. 55 decoder = Transcoder::GRPCEncoding.decode(response)
  14. 55 decoder.call(response.to_s)
  15. end
  16. # lazy decodes a grpc stream response
  17. 5 def stream(response, &block)
  18. 40 return enum_for(__method__, response) unless block
  19. 20 decoder = Transcoder::GRPCEncoding.decode(response)
  20. 20 response.each do |frame|
  21. 40 decoder.call(frame, &block)
  22. end
  23. 20 verify_status(response)
  24. end
  25. 5 def cancel(request)
  26. request.emit(:refuse, :client_cancellation)
  27. end
  28. # interprets the grpc call trailing metadata, and raises an
  29. # exception in case of error code
  30. 5 def verify_status(response)
  31. # return standard errors if need be
  32. 95 response.raise_for_status
  33. 95 status = Integer(response.headers["grpc-status"])
  34. 95 message = response.headers["grpc-message"]
  35. 95 return if status.zero?
  36. 20 response.close
  37. 20 raise GRPCError.new(status, message, response.trailing_metadata)
  38. end
  39. end
  40. end
  41. end
  42. end

lib/httpx/plugins/h2c.rb

94.44% lines covered

54 relevant lines. 51 lines covered and 3 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin adds support for upgrading a plaintext HTTP/1.1 connection to HTTP/2
  6. # (https://datatracker.ietf.org/doc/html/rfc7540#section-3.2)
  7. #
  8. # https://gitlab.com/os85/httpx/wikis/Connection-Upgrade#h2c
  9. #
  10. 7 module H2C
  11. 7 VALID_H2C_VERBS = %w[GET OPTIONS HEAD].freeze
  12. 7 class << self
  13. 7 def load_dependencies(klass)
  14. 14 klass.plugin(:upgrade)
  15. end
  16. 7 def call(connection, request, response)
  17. 14 connection.upgrade_to_h2c(request, response)
  18. end
  19. 7 def extra_options(options)
  20. 14 options.merge(max_concurrent_requests: 1, upgrade_handlers: options.upgrade_handlers.merge("h2c" => self))
  21. end
  22. end
  23. 7 module InstanceMethods
  24. 7 def send_requests(*requests)
  25. 21 upgrade_request, *remainder = requests
  26. 21 return super unless VALID_H2C_VERBS.include?(upgrade_request.verb) && upgrade_request.scheme == "http"
  27. 21 connection = pool.find_connection(upgrade_request.uri, upgrade_request.options)
  28. 21 return super if connection && connection.upgrade_protocol == "h2c"
  29. # build upgrade request
  30. 14 upgrade_request.headers.add("connection", "upgrade")
  31. 14 upgrade_request.headers.add("connection", "http2-settings")
  32. 12 upgrade_request.headers["upgrade"] = "h2c"
  33. 12 upgrade_request.headers["http2-settings"] = ::HTTP2::Client.settings_header(upgrade_request.options.http2_settings)
  34. 14 super(upgrade_request, *remainder)
  35. end
  36. end
  37. 7 class H2CParser < Connection::HTTP2
  38. 7 def upgrade(request, response)
  39. # skip checks, it is assumed that this is the first
  40. # request in the connection
  41. 14 stream = @connection.upgrade
  42. # on_settings
  43. 14 handle_stream(stream, request)
  44. 12 @streams[request] = stream
  45. # clean up data left behind in the buffer, if the server started
  46. # sending frames
  47. 14 data = response.read
  48. 14 @connection << data
  49. end
  50. end
  51. 7 module ConnectionMethods
  52. 7 using URIExtensions
  53. 7 def upgrade_to_h2c(request, response)
  54. 14 prev_parser = @parser
  55. 14 if prev_parser
  56. 14 prev_parser.reset
  57. 12 @inflight -= prev_parser.requests.size
  58. end
  59. 14 @parser = H2CParser.new(@write_buffer, @options)
  60. 14 set_parser_callbacks(@parser)
  61. 12 @inflight += 1
  62. 14 @parser.upgrade(request, response)
  63. 14 @upgrade_protocol = "h2c"
  64. 14 prev_parser.requests.each do |req|
  65. 14 req.transition(:idle)
  66. 14 send(req)
  67. end
  68. end
  69. 7 private
  70. 7 def send_request_to_parser(request)
  71. 49 super
  72. 49 return unless request.headers["upgrade"] == "h2c" && parser.is_a?(Connection::HTTP1)
  73. 14 max_concurrent_requests = parser.max_concurrent_requests
  74. 14 return if max_concurrent_requests == 1
  75. parser.max_concurrent_requests = 1
  76. request.once(:response) do
  77. parser.max_concurrent_requests = max_concurrent_requests
  78. end
  79. end
  80. end
  81. end
  82. 7 register_plugin(:h2c, H2C)
  83. end
  84. end

lib/httpx/plugins/ntlm_auth.rb

100.0% lines covered

30 relevant lines. 30 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 5 module HTTPX
  3. 5 module Plugins
  4. #
  5. # https://gitlab.com/os85/httpx/wikis/Auth#ntlm-auth
  6. #
  7. 5 module NTLMAuth
  8. 5 class << self
  9. 5 def load_dependencies(_klass)
  10. 2 require_relative "auth/ntlm"
  11. end
  12. 5 def extra_options(options)
  13. 2 options.merge(max_concurrent_requests: 1)
  14. end
  15. end
  16. 5 module OptionsMethods
  17. 5 def option_ntlm(value)
  18. 8 raise TypeError, ":ntlm must be a #{Authentication::Ntlm}" unless value.is_a?(Authentication::Ntlm)
  19. 8 value
  20. end
  21. end
  22. 5 module InstanceMethods
  23. 5 def ntlm_auth(user, password, domain = nil)
  24. 4 with(ntlm: Authentication::Ntlm.new(user, password, domain: domain))
  25. end
  26. 5 private
  27. 5 def send_requests(*requests)
  28. 8 requests.flat_map do |request|
  29. 8 ntlm = request.options.ntlm
  30. 8 if ntlm
  31. 4 request.headers["authorization"] = ntlm.negotiate
  32. 8 probe_response = wrap { super(request).first }
  33. 4 return probe_response unless probe_response.is_a?(Response)
  34. 4 if probe_response.status == 401 && ntlm.can_authenticate?(probe_response.headers["www-authenticate"])
  35. 2 request.transition(:idle)
  36. 2 request.headers["authorization"] = ntlm.authenticate(request, probe_response.headers["www-authenticate"])
  37. 2 super(request)
  38. else
  39. 2 probe_response
  40. end
  41. else
  42. 4 super(request)
  43. end
  44. end
  45. end
  46. end
  47. end
  48. 5 register_plugin :ntlm_auth, NTLMAuth
  49. end
  50. end

lib/httpx/plugins/oauth.rb

89.53% lines covered

86 relevant lines. 77 lines covered and 9 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # https://gitlab.com/os85/httpx/wikis/OAuth
  6. #
  7. 7 module OAuth
  8. 7 class << self
  9. 7 def load_dependencies(_klass)
  10. 70 require_relative "auth/basic"
  11. end
  12. end
  13. 7 SUPPORTED_GRANT_TYPES = %w[client_credentials refresh_token].freeze
  14. 7 SUPPORTED_AUTH_METHODS = %w[client_secret_basic client_secret_post].freeze
  15. 7 class OAuthSession
  16. 7 attr_reader :grant_type, :client_id, :client_secret, :access_token, :refresh_token, :scope
  17. 7 def initialize(
  18. issuer:,
  19. client_id:,
  20. client_secret:,
  21. access_token: nil,
  22. refresh_token: nil,
  23. scope: nil,
  24. token_endpoint: nil,
  25. response_type: nil,
  26. grant_type: nil,
  27. token_endpoint_auth_method: nil
  28. )
  29. 70 @issuer = URI(issuer)
  30. 70 @client_id = client_id
  31. 70 @client_secret = client_secret
  32. 70 @token_endpoint = URI(token_endpoint) if token_endpoint
  33. 70 @response_type = response_type
  34. 70 @scope = case scope
  35. when String
  36. 28 scope.split
  37. when Array
  38. 28 scope
  39. end
  40. 70 @access_token = access_token
  41. 70 @refresh_token = refresh_token
  42. 70 @token_endpoint_auth_method = String(token_endpoint_auth_method) if token_endpoint_auth_method
  43. 70 @grant_type = grant_type || (@refresh_token ? "refresh_token" : "client_credentials")
  44. 70 unless @token_endpoint_auth_method.nil? || SUPPORTED_AUTH_METHODS.include?(@token_endpoint_auth_method)
  45. 14 raise Error, "#{@token_endpoint_auth_method} is not a supported auth method"
  46. end
  47. 56 return if SUPPORTED_GRANT_TYPES.include?(@grant_type)
  48. raise Error, "#{@grant_type} is not a supported grant type"
  49. end
  50. 7 def token_endpoint
  51. 56 @token_endpoint || "#{@issuer}/token"
  52. end
  53. 7 def token_endpoint_auth_method
  54. 84 @token_endpoint_auth_method || "client_secret_basic"
  55. end
  56. 7 def load(http)
  57. 28 return if @grant_type && @scope
  58. metadata = http.get("#{@issuer}/.well-known/oauth-authorization-server").raise_for_status.json
  59. @token_endpoint = metadata["token_endpoint"]
  60. @scope = metadata["scopes_supported"]
  61. @grant_type = Array(metadata["grant_types_supported"]).find { |gr| SUPPORTED_GRANT_TYPES.include?(gr) }
  62. @token_endpoint_auth_method = Array(metadata["token_endpoint_auth_methods_supported"]).find do |am|
  63. SUPPORTED_AUTH_METHODS.include?(am)
  64. end
  65. nil
  66. end
  67. 7 def merge(other)
  68. 56 obj = dup
  69. 48 case other
  70. when OAuthSession
  71. 28 other.instance_variables.each do |ivar|
  72. 238 val = other.instance_variable_get(ivar)
  73. 238 next unless val
  74. 182 obj.instance_variable_set(ivar, val)
  75. end
  76. when Hash
  77. 28 other.each do |k, v|
  78. 56 obj.instance_variable_set(:"@#{k}", v) if obj.instance_variable_defined?(:"@#{k}")
  79. end
  80. end
  81. 56 obj
  82. end
  83. end
  84. 7 module OptionsMethods
  85. 7 def option_oauth_session(value)
  86. 144 case value
  87. when Hash
  88. OAuthSession.new(**value)
  89. when OAuthSession
  90. 168 value
  91. else
  92. raise TypeError, ":oauth_session must be a #{OAuthSession}"
  93. end
  94. end
  95. end
  96. 7 module InstanceMethods
  97. 7 def oauth_auth(**args)
  98. 70 with(oauth_session: OAuthSession.new(**args))
  99. end
  100. 7 def with_access_token
  101. 28 oauth_session = @options.oauth_session
  102. 28 oauth_session.load(self)
  103. 28 grant_type = oauth_session.grant_type
  104. 28 headers = {}
  105. 28 form_post = { "grant_type" => grant_type, "scope" => Array(oauth_session.scope).join(" ") }.compact
  106. # auth
  107. 24 case oauth_session.token_endpoint_auth_method
  108. when "client_secret_post"
  109. 12 form_post["client_id"] = oauth_session.client_id
  110. 12 form_post["client_secret"] = oauth_session.client_secret
  111. when "client_secret_basic"
  112. 12 headers["authorization"] = Authentication::Basic.new(oauth_session.client_id, oauth_session.client_secret).authenticate
  113. end
  114. 24 case grant_type
  115. when "client_credentials"
  116. # do nothing
  117. when "refresh_token"
  118. 12 form_post["refresh_token"] = oauth_session.refresh_token
  119. end
  120. 28 token_request = build_request("POST", oauth_session.token_endpoint, headers: headers, form: form_post)
  121. 28 token_request.headers.delete("authorization") unless oauth_session.token_endpoint_auth_method == "client_secret_basic"
  122. 28 token_response = request(token_request)
  123. 28 token_response.raise_for_status
  124. 28 payload = token_response.json
  125. 28 access_token = payload["access_token"]
  126. 28 refresh_token = payload["refresh_token"]
  127. 28 with(oauth_session: oauth_session.merge(access_token: access_token, refresh_token: refresh_token))
  128. end
  129. 7 def build_request(*)
  130. 84 request = super
  131. 84 return request if request.headers.key?("authorization")
  132. 70 oauth_session = @options.oauth_session
  133. 70 return request unless oauth_session && oauth_session.access_token
  134. 48 request.headers["authorization"] = "Bearer #{oauth_session.access_token}"
  135. 56 request
  136. end
  137. end
  138. end
  139. 7 register_plugin :oauth, OAuth
  140. end
  141. end

lib/httpx/plugins/persistent.rb

100.0% lines covered

11 relevant lines. 11 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module HTTPX
  3. 9 module Plugins
  4. # This plugin implements a session that persists connections over the duration of the process.
  5. #
  6. # This will improve connection reuse in a long-running process.
  7. #
  8. # One important caveat to note is, although this session might not close connections,
  9. # other sessions from the same process that don't have this plugin turned on might.
  10. #
  11. # This session will still be able to work with it, as if, when expecting a connection
  12. # terminated by a different session, it will just retry on a new one and keep it open.
  13. #
  14. # This plugin is also not recommendable when connecting to >9000 (like, a lot) different origins.
  15. # So when you use this, make sure that you don't fall into this trap.
  16. #
  17. # https://gitlab.com/os85/httpx/wikis/Persistent
  18. #
  19. 9 module Persistent
  20. 9 def self.load_dependencies(klass)
  21. 354 max_retries = if klass.default_options.respond_to?(:max_retries)
  22. 7 [klass.default_options.max_retries, 1].max
  23. else
  24. 347 1
  25. end
  26. 354 klass.plugin(:retries, max_retries: max_retries, retry_change_requests: true)
  27. end
  28. 9 def self.extra_options(options)
  29. 354 options.merge(persistent: true)
  30. end
  31. end
  32. 9 register_plugin :persistent, Persistent
  33. end
  34. end

lib/httpx/plugins/proxy.rb

97.35% lines covered

151 relevant lines. 147 lines covered and 4 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module HTTPX
  3. 9 class HTTPProxyError < ConnectionError; end
  4. 9 module Plugins
  5. #
  6. # This plugin adds support for proxies. It ships with support for:
  7. #
  8. # * HTTP proxies
  9. # * HTTPS proxies
  10. # * Socks4/4a proxies
  11. # * Socks5 proxies
  12. #
  13. # https://gitlab.com/os85/httpx/wikis/Proxy
  14. #
  15. 9 module Proxy
  16. 9 Error = HTTPProxyError
  17. 9 PROXY_ERRORS = [TimeoutError, IOError, SystemCallError, Error].freeze
  18. 9 class << self
  19. 9 def configure(klass)
  20. 295 klass.plugin(:"proxy/http")
  21. 295 klass.plugin(:"proxy/socks4")
  22. 295 klass.plugin(:"proxy/socks5")
  23. end
  24. 9 def extra_options(options)
  25. 295 options.merge(supported_proxy_protocols: [])
  26. end
  27. end
  28. 9 class Parameters
  29. 9 attr_reader :uri, :username, :password, :scheme
  30. 9 def initialize(uri:, scheme: nil, username: nil, password: nil, **extra)
  31. 377 @uri = uri.is_a?(URI::Generic) ? uri : URI(uri)
  32. 377 @username = username || @uri.user
  33. 377 @password = password || @uri.password
  34. 377 return unless @username && @password
  35. 222 scheme ||= case @uri.scheme
  36. when "socks5"
  37. 42 @uri.scheme
  38. when "http", "https"
  39. 97 "basic"
  40. else
  41. 42 return
  42. end
  43. 180 @scheme = scheme
  44. 180 auth_scheme = scheme.to_s.capitalize
  45. 180 require_relative "auth/#{scheme}" unless defined?(Authentication) && Authentication.const_defined?(auth_scheme, false)
  46. 180 @authenticator = Authentication.const_get(auth_scheme).new(@username, @password, **extra)
  47. end
  48. 9 def can_authenticate?(*args)
  49. 154 return false unless @authenticator
  50. 56 @authenticator.can_authenticate?(*args)
  51. end
  52. 9 def authenticate(*args)
  53. 139 return unless @authenticator
  54. 139 @authenticator.authenticate(*args)
  55. end
  56. 9 def ==(other)
  57. 71 case other
  58. when Parameters
  59. 53 @uri == other.uri &&
  60. @username == other.username &&
  61. @password == other.password &&
  62. @scheme == other.scheme
  63. when URI::Generic, String
  64. 21 proxy_uri = @uri.dup
  65. 21 proxy_uri.user = @username
  66. 21 proxy_uri.password = @password
  67. 21 other_uri = other.is_a?(URI::Generic) ? other : URI.parse(other)
  68. 21 proxy_uri == other_uri
  69. else
  70. 7 super
  71. end
  72. end
  73. end
  74. # adds support for the following options:
  75. #
  76. # :proxy :: proxy options defining *:uri*, *:username*, *:password* or
  77. # *:scheme* (i.e. <tt>{ uri: "http://proxy" }</tt>)
  78. 9 module OptionsMethods
  79. 9 def option_proxy(value)
  80. 933 value.is_a?(Parameters) ? value : Hash[value]
  81. end
  82. 9 def option_supported_proxy_protocols(value)
  83. 1487 raise TypeError, ":supported_proxy_protocols must be an Array" unless value.is_a?(Array)
  84. 1487 value.map(&:to_s)
  85. end
  86. end
  87. 9 module InstanceMethods
  88. 9 private
  89. 9 def find_connection(request, connections, options)
  90. 365 return super unless options.respond_to?(:proxy)
  91. 365 uri = request.uri
  92. 365 proxy_options = proxy_options(uri, options)
  93. 344 return super(request, connections, proxy_options) unless proxy_options.proxy
  94. 328 connection = pool.find_connection(uri, proxy_options) || init_connection(uri, proxy_options)
  95. 328 unless connections.nil? || connections.include?(connection)
  96. 320 connections << connection
  97. 320 set_connection_callbacks(connection, connections, options)
  98. end
  99. 328 connection
  100. end
  101. 9 def proxy_options(request_uri, options)
  102. 386 proxy_opts = if (next_proxy = request_uri.find_proxy)
  103. 4 { uri: next_proxy }
  104. else
  105. 382 proxy = options.proxy
  106. 382 return options unless proxy
  107. 373 return options.merge(proxy: nil) unless proxy.key?(:uri)
  108. 373 @_proxy_uris ||= Array(proxy[:uri])
  109. 373 next_proxy = @_proxy_uris.first
  110. 373 raise Error, "Failed to connect to proxy" unless next_proxy
  111. 359 next_proxy = URI(next_proxy)
  112. 1 raise Error,
  113. 359 "#{next_proxy.scheme}: unsupported proxy protocol" unless options.supported_proxy_protocols.include?(next_proxy.scheme)
  114. 352 if proxy.key?(:no_proxy)
  115. 14 no_proxy = proxy[:no_proxy]
  116. 14 no_proxy = no_proxy.join(",") if no_proxy.is_a?(Array)
  117. 14 return options.merge(proxy: nil) unless URI::Generic.use_proxy?(request_uri.host, next_proxy.host,
  118. next_proxy.port, no_proxy)
  119. end
  120. 345 proxy.merge(uri: next_proxy)
  121. end
  122. 349 proxy = Parameters.new(**proxy_opts)
  123. 349 options.merge(proxy: proxy)
  124. end
  125. 9 def fetch_response(request, connections, options)
  126. 1288 response = super
  127. 1288 if response.is_a?(ErrorResponse) && proxy_error?(request, response)
  128. 85 return response unless @_proxy_uris
  129. 84 @_proxy_uris.shift
  130. # return last error response if no more proxies to try
  131. 84 return response if @_proxy_uris.empty?
  132. 14 log { "failed connecting to proxy, trying next..." }
  133. 14 request.transition(:idle)
  134. 14 send_request(request, connections, options)
  135. 12 return
  136. end
  137. 1203 response
  138. end
  139. 9 def proxy_error?(_request, response)
  140. 127 error = response.error
  141. 109 case error
  142. when NativeResolveError
  143. 14 return false unless @_proxy_uris && !@_proxy_uris.empty?
  144. 14 proxy_uri = URI(@_proxy_uris.first)
  145. 14 origin = error.connection.origin
  146. # failed resolving proxy domain
  147. 14 origin.host == proxy_uri.host && origin.port == proxy_uri.port
  148. when ResolveError
  149. return false unless @_proxy_uris && !@_proxy_uris.empty?
  150. proxy_uri = URI(@_proxy_uris.first)
  151. error.message.end_with?(proxy_uri.to_s)
  152. when *PROXY_ERRORS
  153. # timeout errors connecting to proxy
  154. 113 true
  155. else
  156. false
  157. end
  158. end
  159. end
  160. 9 module ConnectionMethods
  161. 9 using URIExtensions
  162. 9 def initialize(*)
  163. 336 super
  164. 336 return unless @options.proxy
  165. # redefining the connection origin as the proxy's URI,
  166. # as this will be used as the tcp peer ip.
  167. 320 proxy_uri = URI(@options.proxy.uri)
  168. 320 @origin.host = proxy_uri.host
  169. 320 @origin.port = proxy_uri.port
  170. end
  171. 9 def coalescable?(connection)
  172. 10 return super unless @options.proxy
  173. 10 if @io.protocol == "h2" &&
  174. @origin.scheme == "https" &&
  175. connection.origin.scheme == "https" &&
  176. @io.can_verify_peer?
  177. # in proxied connections, .origin is the proxy ; Given names
  178. # are stored in .origins, this is what is used.
  179. 5 origin = URI(connection.origins.first)
  180. 5 @io.verify_hostname(origin.host)
  181. else
  182. 5 @origin == connection.origin
  183. end
  184. end
  185. 9 def connecting?
  186. 3913 return super unless @options.proxy
  187. 3771 super || @state == :connecting || @state == :connected
  188. end
  189. 9 def call
  190. 894 super
  191. 894 return unless @options.proxy
  192. 767 case @state
  193. when :connecting
  194. 174 consume
  195. end
  196. end
  197. 9 def reset
  198. 450 return super unless @options.proxy
  199. 420 @state = :open
  200. 420 super
  201. 420 emit(:close)
  202. end
  203. 9 private
  204. 9 def initialize_type(uri, options)
  205. 336 return super unless options.proxy
  206. 320 "tcp"
  207. end
  208. 9 def connect
  209. 912 return super unless @options.proxy
  210. 765 case @state
  211. when :idle
  212. 623 transition(:connecting)
  213. when :connected
  214. 259 transition(:open)
  215. end
  216. end
  217. 9 def handle_transition(nextstate)
  218. 2136 return super unless @options.proxy
  219. 1785 case nextstate
  220. when :closing
  221. # this is a hack so that we can use the super method
  222. # and it'll think that the current state is open
  223. 477 @state = :open if @state == :connecting
  224. end
  225. 2058 super
  226. end
  227. end
  228. end
  229. 9 register_plugin :proxy, Proxy
  230. end
  231. 9 class ProxySSL < SSL
  232. 9 def initialize(tcp, request_uri, options)
  233. 78 @io = tcp.to_io
  234. 78 super(request_uri, tcp.addresses, options)
  235. 78 @hostname = request_uri.host
  236. 78 @state = :connected
  237. end
  238. end
  239. end

lib/httpx/plugins/proxy/http.rb

100.0% lines covered

102 relevant lines. 102 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module HTTPX
  3. 9 module Plugins
  4. 9 module Proxy
  5. 9 module HTTP
  6. 9 class << self
  7. 9 def extra_options(options)
  8. 295 options.merge(supported_proxy_protocols: options.supported_proxy_protocols + %w[http])
  9. end
  10. end
  11. 9 module InstanceMethods
  12. 9 def with_proxy_basic_auth(opts)
  13. 7 with(proxy: opts.merge(scheme: "basic"))
  14. end
  15. 9 def with_proxy_digest_auth(opts)
  16. 21 with(proxy: opts.merge(scheme: "digest"))
  17. end
  18. 9 def with_proxy_ntlm_auth(opts)
  19. 7 with(proxy: opts.merge(scheme: "ntlm"))
  20. end
  21. 9 def fetch_response(request, connections, options)
  22. 1288 response = super
  23. 1288 if response &&
  24. response.is_a?(Response) &&
  25. response.status == 407 &&
  26. !request.headers.key?("proxy-authorization") &&
  27. response.headers.key?("proxy-authenticate")
  28. 21 uri = request.uri
  29. 21 proxy_options = proxy_options(uri, options)
  30. 21 connection = connections.find do |conn|
  31. 21 conn.match?(uri, proxy_options)
  32. end
  33. 21 if connection && connection.options.proxy.can_authenticate?(response.headers["proxy-authenticate"])
  34. 7 request.transition(:idle)
  35. 6 request.headers["proxy-authorization"] =
  36. connection.options.proxy.authenticate(request, response.headers["proxy-authenticate"])
  37. 7 send_request(request, connections)
  38. 7 return
  39. end
  40. end
  41. 1281 response
  42. end
  43. end
  44. 9 module ConnectionMethods
  45. 9 def connecting?
  46. 3913 super || @state == :connecting || @state == :connected
  47. end
  48. 9 private
  49. 9 def handle_transition(nextstate)
  50. 2345 return super unless @options.proxy && @options.proxy.uri.scheme == "http"
  51. 1064 case nextstate
  52. when :connecting
  53. 266 return unless @state == :idle
  54. 266 @io.connect
  55. 266 return unless @io.connected?
  56. 133 @parser || begin
  57. 126 @parser = self.class.parser_type(@io.protocol).new(@write_buffer, @options.merge(max_concurrent_requests: 1))
  58. 126 parser = @parser
  59. 126 parser.extend(ProxyParser)
  60. 126 parser.on(:response, &method(:__http_on_connect))
  61. 176 parser.on(:close) { transition(:closing) }
  62. 126 parser.on(:reset) do
  63. 14 if parser.empty?
  64. 7 reset
  65. else
  66. 7 transition(:closing)
  67. 7 transition(:closed)
  68. 7 parser.reset if @parser
  69. 7 transition(:idle)
  70. 7 transition(:connecting)
  71. end
  72. end
  73. 126 __http_proxy_connect(parser)
  74. end
  75. 133 return if @state == :connected
  76. when :connected
  77. 119 return unless @state == :idle || @state == :connecting
  78. 104 case @state
  79. when :connecting
  80. 43 @parser.close
  81. 43 @parser = nil
  82. when :idle
  83. 76 @parser.callbacks.clear
  84. 76 set_parser_callbacks(@parser)
  85. end
  86. end
  87. 1004 super
  88. end
  89. 9 def __http_proxy_connect(parser)
  90. 126 req = @pending.first
  91. 126 if req && req.uri.scheme == "https"
  92. # if the first request after CONNECT is to an https address, it is assumed that
  93. # all requests in the queue are not only ALL HTTPS, but they also share the certificate,
  94. # and therefore, will share the connection.
  95. #
  96. 50 connect_request = ConnectRequest.new(req.uri, @options)
  97. 44 @inflight += 1
  98. 50 parser.send(connect_request)
  99. else
  100. 76 handle_transition(:connected)
  101. end
  102. end
  103. 9 def __http_on_connect(request, response)
  104. 50 @inflight -= 1
  105. 57 if response.is_a?(Response) && response.status == 200
  106. 43 req = @pending.first
  107. 43 request_uri = req.uri
  108. 43 @io = ProxySSL.new(@io, request_uri, @options)
  109. 43 transition(:connected)
  110. 43 throw(:called)
  111. 13 elsif response.is_a?(Response) &&
  112. response.status == 407 &&
  113. !request.headers.key?("proxy-authorization") &&
  114. @options.proxy.can_authenticate?(response.headers["proxy-authenticate"])
  115. 7 request.transition(:idle)
  116. 6 request.headers["proxy-authorization"] = @options.proxy.authenticate(request, response.headers["proxy-authenticate"])
  117. 7 @parser.send(request)
  118. 6 @inflight += 1
  119. else
  120. 7 pending = @pending + @parser.pending
  121. 18 while (req = pending.shift)
  122. 7 req.emit(:response, response)
  123. end
  124. 7 reset
  125. end
  126. end
  127. end
  128. 9 module ProxyParser
  129. 9 def join_headline(request)
  130. 126 return super if request.verb == "CONNECT"
  131. 60 "#{request.verb} #{request.uri} HTTP/#{@version.join(".")}"
  132. end
  133. 9 def set_protocol_headers(request)
  134. 133 extra_headers = super
  135. 133 proxy_params = @options.proxy
  136. 133 if proxy_params.scheme == "basic"
  137. # opt for basic auth
  138. 73 extra_headers["proxy-authorization"] = proxy_params.authenticate(extra_headers)
  139. end
  140. 133 extra_headers["proxy-connection"] = extra_headers.delete("connection") if extra_headers.key?("connection")
  141. 133 extra_headers
  142. end
  143. end
  144. 9 class ConnectRequest < Request
  145. 9 def initialize(uri, options)
  146. 50 super("CONNECT", uri, options)
  147. 50 @headers.delete("accept")
  148. end
  149. 9 def path
  150. 56 "#{@uri.hostname}:#{@uri.port}"
  151. end
  152. end
  153. end
  154. end
  155. 9 register_plugin :"proxy/http", Proxy::HTTP
  156. end
  157. end

lib/httpx/plugins/proxy/socks4.rb

98.73% lines covered

79 relevant lines. 78 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 require "resolv"
  3. 9 require "ipaddr"
  4. 9 module HTTPX
  5. 9 class Socks4Error < HTTPProxyError; end
  6. 9 module Plugins
  7. 9 module Proxy
  8. 9 module Socks4
  9. 9 VERSION = 4
  10. 9 CONNECT = 1
  11. 9 GRANTED = 0x5A
  12. 9 PROTOCOLS = %w[socks4 socks4a].freeze
  13. 9 Error = Socks4Error
  14. 9 class << self
  15. 9 def extra_options(options)
  16. 295 options.merge(supported_proxy_protocols: options.supported_proxy_protocols + PROTOCOLS)
  17. end
  18. end
  19. 9 module ConnectionMethods
  20. 9 def interests
  21. 3310 if @state == :connecting
  22. return @write_buffer.empty? ? :r : :w
  23. end
  24. 3310 super
  25. end
  26. 9 private
  27. 9 def handle_transition(nextstate)
  28. 2401 return super unless @options.proxy && PROTOCOLS.include?(@options.proxy.uri.scheme)
  29. 364 case nextstate
  30. when :connecting
  31. 112 return unless @state == :idle
  32. 112 @io.connect
  33. 112 return unless @io.connected?
  34. 56 req = @pending.first
  35. 56 return unless req
  36. 56 request_uri = req.uri
  37. 56 @write_buffer << Packet.connect(@options.proxy, request_uri)
  38. 56 __socks4_proxy_connect
  39. when :connected
  40. 42 return unless @state == :connecting
  41. 42 @parser = nil
  42. end
  43. 369 log(level: 1) { "SOCKS4: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
  44. 369 super
  45. end
  46. 9 def __socks4_proxy_connect
  47. 56 @parser = SocksParser.new(@write_buffer, @options)
  48. 56 @parser.once(:packet, &method(:__socks4_on_packet))
  49. end
  50. 9 def __socks4_on_packet(packet)
  51. 56 _version, status, _port, _ip = packet.unpack("CCnN")
  52. 56 if status == GRANTED
  53. 42 req = @pending.first
  54. 42 request_uri = req.uri
  55. 42 @io = ProxySSL.new(@io, request_uri, @options) if request_uri.scheme == "https"
  56. 42 transition(:connected)
  57. 42 throw(:called)
  58. else
  59. 14 on_socks4_error("socks error: #{status}")
  60. end
  61. end
  62. 9 def on_socks4_error(message)
  63. 14 ex = Error.new(message)
  64. 14 ex.set_backtrace(caller)
  65. 14 on_error(ex)
  66. 14 throw(:called)
  67. end
  68. end
  69. 9 class SocksParser
  70. 9 include HTTPX::Callbacks
  71. 9 def initialize(buffer, options)
  72. 56 @buffer = buffer
  73. 56 @options = options
  74. end
  75. 9 def close; end
  76. 9 def consume(*); end
  77. 9 def empty?
  78. 14 true
  79. end
  80. 9 def <<(packet)
  81. 56 emit(:packet, packet)
  82. end
  83. end
  84. 9 module Packet
  85. 9 module_function
  86. 9 def connect(parameters, uri)
  87. 56 packet = [VERSION, CONNECT, uri.port].pack("CCn")
  88. 48 case parameters.uri.scheme
  89. when "socks4"
  90. 42 socks_host = uri.host
  91. 5 begin
  92. 84 ip = IPAddr.new(socks_host)
  93. 42 packet << ip.hton
  94. rescue IPAddr::InvalidAddressError
  95. 42 socks_host = Resolv.getaddress(socks_host)
  96. 42 retry
  97. end
  98. 42 packet << [parameters.username].pack("Z*")
  99. when "socks4a"
  100. 14 packet << "\x0\x0\x0\x1" << [parameters.username].pack("Z*") << uri.host << "\x0"
  101. end
  102. 56 packet
  103. end
  104. end
  105. end
  106. end
  107. 9 register_plugin :"proxy/socks4", Proxy::Socks4
  108. end
  109. end

lib/httpx/plugins/proxy/socks5.rb

100.0% lines covered

113 relevant lines. 113 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module HTTPX
  3. 9 class Socks5Error < HTTPProxyError; end
  4. 9 module Plugins
  5. 9 module Proxy
  6. 9 module Socks5
  7. 9 VERSION = 5
  8. 9 NOAUTH = 0
  9. 9 PASSWD = 2
  10. 9 NONE = 0xff
  11. 9 CONNECT = 1
  12. 9 IPV4 = 1
  13. 9 DOMAIN = 3
  14. 9 IPV6 = 4
  15. 9 SUCCESS = 0
  16. 9 Error = Socks5Error
  17. 9 class << self
  18. 9 def load_dependencies(*)
  19. 295 require_relative "../auth/socks5"
  20. end
  21. 9 def extra_options(options)
  22. 295 options.merge(supported_proxy_protocols: options.supported_proxy_protocols + %w[socks5])
  23. end
  24. end
  25. 9 module ConnectionMethods
  26. 9 def call
  27. 894 super
  28. 894 return unless @options.proxy && @options.proxy.uri.scheme == "socks5"
  29. 236 case @state
  30. when :connecting,
  31. :negotiating,
  32. :authenticating
  33. 87 consume
  34. end
  35. end
  36. 9 def connecting?
  37. 3913 super || @state == :authenticating || @state == :negotiating
  38. end
  39. 9 def interests
  40. 5209 if @state == :connecting || @state == :authenticating || @state == :negotiating
  41. 1694 return @write_buffer.empty? ? :r : :w
  42. end
  43. 3310 super
  44. end
  45. 9 private
  46. 9 def handle_transition(nextstate)
  47. 2653 return super unless @options.proxy && @options.proxy.uri.scheme == "socks5"
  48. 803 case nextstate
  49. when :connecting
  50. 252 return unless @state == :idle
  51. 252 @io.connect
  52. 252 return unless @io.connected?
  53. 126 @write_buffer << Packet.negotiate(@options.proxy)
  54. 126 __socks5_proxy_connect
  55. when :authenticating
  56. 42 return unless @state == :connecting
  57. 42 @write_buffer << Packet.authenticate(@options.proxy)
  58. when :negotiating
  59. 168 return unless @state == :connecting || @state == :authenticating
  60. 42 req = @pending.first
  61. 42 request_uri = req.uri
  62. 42 @write_buffer << Packet.connect(request_uri)
  63. when :connected
  64. 28 return unless @state == :negotiating
  65. 28 @parser = nil
  66. end
  67. 685 log(level: 1) { "SOCKS5: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
  68. 685 super
  69. end
  70. 9 def __socks5_proxy_connect
  71. 126 @parser = SocksParser.new(@write_buffer, @options)
  72. 126 @parser.on(:packet, &method(:__socks5_on_packet))
  73. 126 transition(:negotiating)
  74. end
  75. 9 def __socks5_on_packet(packet)
  76. 180 case @state
  77. when :connecting
  78. 126 version, method = packet.unpack("CC")
  79. 126 __socks5_check_version(version)
  80. 108 case method
  81. when PASSWD
  82. 42 transition(:authenticating)
  83. 12 nil
  84. when NONE
  85. 70 __on_socks5_error("no supported authorization methods")
  86. else
  87. 14 transition(:negotiating)
  88. end
  89. when :authenticating
  90. 42 _, status = packet.unpack("CC")
  91. 42 return transition(:negotiating) if status == SUCCESS
  92. 14 __on_socks5_error("socks authentication error: #{status}")
  93. when :negotiating
  94. 42 version, reply, = packet.unpack("CC")
  95. 42 __socks5_check_version(version)
  96. 42 __on_socks5_error("socks5 negotiation error: #{reply}") unless reply == SUCCESS
  97. 28 req = @pending.first
  98. 28 request_uri = req.uri
  99. 28 @io = ProxySSL.new(@io, request_uri, @options) if request_uri.scheme == "https"
  100. 28 transition(:connected)
  101. 28 throw(:called)
  102. end
  103. end
  104. 9 def __socks5_check_version(version)
  105. 168 __on_socks5_error("invalid SOCKS version (#{version})") if version != 5
  106. end
  107. 9 def __on_socks5_error(message)
  108. 98 ex = Error.new(message)
  109. 98 ex.set_backtrace(caller)
  110. 98 on_error(ex)
  111. 98 throw(:called)
  112. end
  113. end
  114. 9 class SocksParser
  115. 9 include HTTPX::Callbacks
  116. 9 def initialize(buffer, options)
  117. 126 @buffer = buffer
  118. 126 @options = options
  119. end
  120. 9 def close; end
  121. 9 def consume(*); end
  122. 9 def empty?
  123. 98 true
  124. end
  125. 9 def <<(packet)
  126. 210 emit(:packet, packet)
  127. end
  128. end
  129. 9 module Packet
  130. 9 module_function
  131. 9 def negotiate(parameters)
  132. 126 methods = [NOAUTH]
  133. 126 methods << PASSWD if parameters.can_authenticate?
  134. 126 methods.unshift(methods.size)
  135. 126 methods.unshift(VERSION)
  136. 126 methods.pack("C*")
  137. end
  138. 9 def authenticate(parameters)
  139. 42 parameters.authenticate
  140. end
  141. 9 def connect(uri)
  142. 42 packet = [VERSION, CONNECT, 0].pack("C*")
  143. 5 begin
  144. 42 ip = IPAddr.new(uri.host)
  145. 14 ipcode = ip.ipv6? ? IPV6 : IPV4
  146. 14 packet << [ipcode].pack("C") << ip.hton
  147. rescue IPAddr::InvalidAddressError
  148. 28 packet << [DOMAIN, uri.host.bytesize, uri.host].pack("CCA*")
  149. end
  150. 42 packet << [uri.port].pack("n")
  151. 42 packet
  152. end
  153. end
  154. end
  155. end
  156. 9 register_plugin :"proxy/socks5", Proxy::Socks5
  157. end
  158. end

lib/httpx/plugins/proxy/ssh.rb

92.31% lines covered

52 relevant lines. 48 lines covered and 4 lines missed.
    
  1. # frozen_string_literal: true
  2. 5 require "httpx/plugins/proxy"
  3. 5 module HTTPX
  4. 5 module Plugins
  5. 5 module Proxy
  6. 5 module SSH
  7. 5 class << self
  8. 5 def load_dependencies(*)
  9. 10 require "net/ssh/gateway"
  10. end
  11. end
  12. 5 module OptionsMethods
  13. 5 def option_proxy(value)
  14. 20 Hash[value]
  15. end
  16. end
  17. 5 module InstanceMethods
  18. 5 def request(*args, **options)
  19. 10 raise ArgumentError, "must perform at least one request" if args.empty?
  20. 10 requests = args.first.is_a?(Request) ? args : build_requests(*args, options)
  21. 10 request = requests.first or return super
  22. 10 request_options = request.options
  23. 10 return super unless request_options.proxy
  24. 10 ssh_options = request_options.proxy
  25. 10 ssh_uris = ssh_options.delete(:uri)
  26. 10 ssh_uri = URI.parse(ssh_uris.shift)
  27. 10 return super unless ssh_uri.scheme == "ssh"
  28. 10 ssh_username = ssh_options.delete(:username)
  29. 10 ssh_options[:port] ||= ssh_uri.port || 22
  30. 10 if request_options.debug
  31. ssh_options[:verbose] = request_options.debug_level == 2 ? :debug : :info
  32. end
  33. 10 request_uri = URI(requests.first.uri)
  34. 10 @_gateway = Net::SSH::Gateway.new(ssh_uri.host, ssh_username, ssh_options)
  35. begin
  36. 10 @_gateway.open(request_uri.host, request_uri.port) do |local_port|
  37. 10 io = build_gateway_socket(local_port, request_uri, request_options)
  38. 10 super(*args, **options.merge(io: io))
  39. end
  40. ensure
  41. 10 @_gateway.shutdown!
  42. end
  43. end
  44. 5 private
  45. 5 def build_gateway_socket(port, request_uri, options)
  46. 10 case request_uri.scheme
  47. when "https"
  48. 5 ctx = OpenSSL::SSL::SSLContext.new
  49. 5 ctx_options = SSL::TLS_OPTIONS.merge(options.ssl)
  50. 5 ctx.set_params(ctx_options) unless ctx_options.empty?
  51. 5 sock = TCPSocket.open("localhost", port)
  52. 5 io = OpenSSL::SSL::SSLSocket.new(sock, ctx)
  53. 5 io.hostname = request_uri.host
  54. 5 io.sync_close = true
  55. 5 io.connect
  56. 5 io.post_connection_check(request_uri.host) if ctx.verify_mode != OpenSSL::SSL::VERIFY_NONE
  57. 5 io
  58. when "http"
  59. 5 TCPSocket.open("localhost", port)
  60. else
  61. raise TypeError, "unexpected scheme: #{request_uri.scheme}"
  62. end
  63. end
  64. end
  65. 5 module ConnectionMethods
  66. # should not coalesce connections here, as the IP is the IP of the proxy
  67. 5 def coalescable?(*)
  68. return super unless @options.proxy
  69. false
  70. end
  71. end
  72. end
  73. end
  74. 5 register_plugin :"proxy/ssh", Proxy::SSH
  75. end
  76. end

lib/httpx/plugins/push_promise.rb

100.0% lines covered

41 relevant lines. 41 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin adds support for HTTP/2 Push responses.
  6. #
  7. # In order to benefit from this, requests are sent one at a time, so that
  8. # no push responses are received after corresponding request has been sent.
  9. #
  10. # https://gitlab.com/os85/httpx/wikis/Server-Push
  11. #
  12. 7 module PushPromise
  13. 7 def self.extra_options(options)
  14. 14 options.merge(http2_settings: { settings_enable_push: 1 },
  15. max_concurrent_requests: 1)
  16. end
  17. 7 module ResponseMethods
  18. 7 def pushed?
  19. 14 @__pushed
  20. end
  21. 7 def mark_as_pushed!
  22. 7 @__pushed = true
  23. end
  24. end
  25. 7 module InstanceMethods
  26. 7 private
  27. 7 def promise_headers
  28. 14 @promise_headers ||= {}
  29. end
  30. 7 def on_promise(parser, stream)
  31. 14 stream.on(:promise_headers) do |h|
  32. 14 __on_promise_request(parser, stream, h)
  33. end
  34. 14 stream.on(:headers) do |h|
  35. 7 __on_promise_response(parser, stream, h)
  36. end
  37. end
  38. 7 def __on_promise_request(parser, stream, h)
  39. 14 log(level: 1, color: :yellow) do
  40. skipped # :nocov:
  41. skipped h.map { |k, v| "#{stream.id}: -> PROMISE HEADER: #{k}: #{v}" }.join("\n")
  42. skipped # :nocov:
  43. end
  44. 14 headers = @options.headers_class.new(h)
  45. 14 path = headers[":path"]
  46. 14 authority = headers[":authority"]
  47. 21 request = parser.pending.find { |r| r.authority == authority && r.path == path }
  48. 14 if request
  49. 7 request.merge_headers(headers)
  50. 6 promise_headers[stream] = request
  51. 7 parser.pending.delete(request)
  52. 6 parser.streams[request] = stream
  53. 7 request.transition(:done)
  54. else
  55. 7 stream.refuse
  56. end
  57. end
  58. 7 def __on_promise_response(parser, stream, h)
  59. 7 request = promise_headers.delete(stream)
  60. 7 return unless request
  61. 7 parser.__send__(:on_stream_headers, stream, request, h)
  62. 7 response = request.response
  63. 7 response.mark_as_pushed!
  64. 7 stream.on(:data, &parser.method(:on_stream_data).curry(3)[stream, request])
  65. 7 stream.on(:close, &parser.method(:on_stream_close).curry(3)[stream, request])
  66. end
  67. end
  68. end
  69. 7 register_plugin(:push_promise, PushPromise)
  70. end
  71. end

lib/httpx/plugins/rate_limiter.rb

100.0% lines covered

18 relevant lines. 18 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin adds support for retrying requests when the request:
  6. #
  7. # * is rate limited;
  8. # * when the server is unavailable (503);
  9. # * when a 3xx request comes with a "retry-after" value
  10. #
  11. # https://gitlab.com/os85/httpx/wikis/Rate-Limiter
  12. #
  13. 7 module RateLimiter
  14. 7 class << self
  15. 7 RATE_LIMIT_CODES = [429, 503].freeze
  16. 7 def configure(klass)
  17. 56 klass.plugin(:retries,
  18. retry_change_requests: true,
  19. 7 retry_on: method(:retry_on_rate_limited_response),
  20. retry_after: method(:retry_after_rate_limit))
  21. end
  22. 7 def retry_on_rate_limited_response(response)
  23. 112 return false unless response.is_a?(Response)
  24. 112 status = response.status
  25. 112 RATE_LIMIT_CODES.include?(status)
  26. end
  27. # Servers send the "Retry-After" header field to indicate how long the
  28. # user agent ought to wait before making a follow-up request. When
  29. # sent with a 503 (Service Unavailable) response, Retry-After indicates
  30. # how long the service is expected to be unavailable to the client.
  31. # When sent with any 3xx (Redirection) response, Retry-After indicates
  32. # the minimum time that the user agent is asked to wait before issuing
  33. # the redirected request.
  34. #
  35. 7 def retry_after_rate_limit(_, response)
  36. 56 return unless response.is_a?(Response)
  37. 56 retry_after = response.headers["retry-after"]
  38. 56 return unless retry_after
  39. 28 Utils.parse_retry_after(retry_after)
  40. end
  41. end
  42. end
  43. 7 register_plugin :rate_limiter, RateLimiter
  44. end
  45. end

lib/httpx/plugins/response_cache.rb

100.0% lines covered

82 relevant lines. 82 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin adds support for retrying requests when certain errors happen.
  6. #
  7. # https://gitlab.com/os85/httpx/wikis/Response-Cache
  8. #
  9. 7 module ResponseCache
  10. 7 CACHEABLE_VERBS = %w[GET HEAD].freeze
  11. 7 CACHEABLE_STATUS_CODES = [200, 203, 206, 300, 301, 410].freeze
  12. 7 private_constant :CACHEABLE_VERBS
  13. 7 private_constant :CACHEABLE_STATUS_CODES
  14. 7 class << self
  15. 7 def load_dependencies(*)
  16. 154 require_relative "response_cache/store"
  17. end
  18. 7 def cacheable_request?(request)
  19. 217 CACHEABLE_VERBS.include?(request.verb) &&
  20. (
  21. 217 !request.headers.key?("cache-control") || !request.headers.get("cache-control").include?("no-store")
  22. )
  23. end
  24. 7 def cacheable_response?(response)
  25. 147 response.is_a?(Response) &&
  26. (
  27. 147 response.cache_control.nil? ||
  28. # TODO: !response.cache_control.include?("private") && is shared cache
  29. !response.cache_control.include?("no-store")
  30. ) &&
  31. CACHEABLE_STATUS_CODES.include?(response.status) &&
  32. # RFC 2616 13.4 - A response received with a status code of 200, 203, 206, 300, 301 or
  33. # 410 MAY be stored by a cache and used in reply to a subsequent
  34. # request, subject to the expiration mechanism, unless a cache-control
  35. # directive prohibits caching. However, a cache that does not support
  36. # the Range and Content-Range headers MUST NOT cache 206 (Partial
  37. # Content) responses.
  38. response.status != 206 && (
  39. 114 response.headers.key?("etag") || response.headers.key?("last-modified") || response.fresh?
  40. )
  41. end
  42. 7 def cached_response?(response)
  43. 70 response.is_a?(Response) && response.status == 304
  44. end
  45. 7 def extra_options(options)
  46. 154 options.merge(response_cache_store: Store.new)
  47. end
  48. end
  49. 7 module OptionsMethods
  50. 7 def option_response_cache_store(value)
  51. 154 raise TypeError, "must be an instance of #{Store}" unless value.is_a?(Store)
  52. 154 value
  53. end
  54. end
  55. 7 module InstanceMethods
  56. 7 def clear_response_cache
  57. 14 @options.response_cache_store.clear
  58. end
  59. 7 def build_request(*)
  60. 70 request = super
  61. 70 return request unless ResponseCache.cacheable_request?(request) && @options.response_cache_store.cached?(request)
  62. 28 @options.response_cache_store.prepare(request)
  63. 28 request
  64. end
  65. 7 def fetch_response(request, *)
  66. 236 response = super
  67. 236 return unless response
  68. 70 if ResponseCache.cached_response?(response)
  69. 28 log { "returning cached response for #{request.uri}" }
  70. 28 cached_response = @options.response_cache_store.lookup(request)
  71. 28 response.copy_from_cached(cached_response)
  72. else
  73. 42 @options.response_cache_store.cache(request, response)
  74. end
  75. 70 response
  76. end
  77. end
  78. 7 module RequestMethods
  79. 7 def response_cache_key
  80. 448 @response_cache_key ||= Digest::SHA1.hexdigest("httpx-response-cache-#{@verb}-#{@uri}")
  81. end
  82. end
  83. 7 module ResponseMethods
  84. 7 def copy_from_cached(other)
  85. # 304 responses do not have content-type, which are needed for decoding.
  86. 28 @headers = @headers.class.new(other.headers.merge(@headers))
  87. 28 @body = other.body.dup
  88. 28 @body.rewind
  89. end
  90. # A response is fresh if its age has not yet exceeded its freshness lifetime.
  91. 7 def fresh?
  92. 224 if cache_control
  93. 35 return false if cache_control.include?("no-cache")
  94. # check age: max-age
  95. 42 max_age = cache_control.find { |directive| directive.start_with?("s-maxage") }
  96. 42 max_age ||= cache_control.find { |directive| directive.start_with?("max-age") }
  97. 21 max_age = max_age[/age=(\d+)/, 1] if max_age
  98. 21 max_age = max_age.to_i if max_age
  99. 21 return max_age > age if max_age
  100. end
  101. # check age: expires
  102. 189 if @headers.key?("expires")
  103. 2 begin
  104. 21 expires = Time.httpdate(@headers["expires"])
  105. rescue ArgumentError
  106. 7 return true
  107. end
  108. 12 return (expires - Time.now).to_i.positive?
  109. end
  110. 168 true
  111. end
  112. 7 def cache_control
  113. 483 return @cache_control if defined?(@cache_control)
  114. 48 @cache_control = begin
  115. 336 return unless @headers.key?("cache-control")
  116. 35 @headers["cache-control"].split(/ *, */)
  117. end
  118. end
  119. 7 def vary
  120. 245 return @vary if defined?(@vary)
  121. 28 @vary = begin
  122. 196 return unless @headers.key?("vary")
  123. 14 @headers["vary"].split(/ *, */)
  124. end
  125. end
  126. 7 private
  127. 7 def age
  128. 21 return @headers["age"].to_i if @headers.key?("age")
  129. 21 (Time.now - date).to_i
  130. end
  131. 7 def date
  132. 21 @date ||= Time.httpdate(@headers["date"])
  133. rescue NoMethodError, ArgumentError
  134. 7 Time.now
  135. end
  136. end
  137. end
  138. 7 register_plugin :response_cache, ResponseCache
  139. end
  140. end

lib/httpx/plugins/response_cache/store.rb

100.0% lines covered

47 relevant lines. 47 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX::Plugins
  3. 7 module ResponseCache
  4. 7 class Store
  5. 7 def initialize
  6. 217 @store = {}
  7. 217 @store_mutex = Thread::Mutex.new
  8. end
  9. 7 def clear
  10. 28 @store_mutex.synchronize { @store.clear }
  11. end
  12. 7 def lookup(request)
  13. 273 responses = _get(request)
  14. 273 return unless responses
  15. 210 responses.find(&method(:match_by_vary?).curry(2)[request])
  16. end
  17. 7 def cached?(request)
  18. 98 lookup(request)
  19. end
  20. 7 def cache(request, response)
  21. 147 return unless ResponseCache.cacheable_request?(request) && ResponseCache.cacheable_response?(response)
  22. 133 _set(request, response)
  23. end
  24. 7 def prepare(request)
  25. 70 cached_response = lookup(request)
  26. 70 return unless cached_response
  27. 49 return unless match_by_vary?(request, cached_response)
  28. 49 if !request.headers.key?("if-modified-since") && (last_modified = cached_response.headers["last-modified"])
  29. 28 request.headers.add("if-modified-since", last_modified)
  30. end
  31. 49 if !request.headers.key?("if-none-match") && (etag = cached_response.headers["etag"]) # rubocop:disable Style/GuardClause
  32. 49 request.headers.add("if-none-match", etag)
  33. end
  34. end
  35. 7 private
  36. 7 def match_by_vary?(request, response)
  37. 245 vary = response.vary
  38. 245 return true unless vary
  39. 63 original_request = response.instance_variable_get(:@request)
  40. 63 return request.headers.same_headers?(original_request.headers) if vary == %w[*]
  41. 35 vary.all? do |cache_field|
  42. 35 cache_field.downcase!
  43. 35 !original_request.headers.key?(cache_field) || request.headers[cache_field] == original_request.headers[cache_field]
  44. end
  45. end
  46. 7 def _get(request)
  47. 273 @store_mutex.synchronize do
  48. 273 responses = @store[request.response_cache_key]
  49. 273 return unless responses
  50. 210 responses.select! do |res|
  51. 210 !res.body.closed? && res.fresh?
  52. end
  53. 210 responses
  54. end
  55. end
  56. 7 def _set(request, response)
  57. 133 @store_mutex.synchronize do
  58. 133 responses = (@store[request.response_cache_key] ||= [])
  59. 133 responses.reject! do |res|
  60. 14 res.body.closed? || !res.fresh? || match_by_vary?(request, res)
  61. end
  62. 133 responses << response
  63. end
  64. end
  65. end
  66. end
  67. end

lib/httpx/plugins/retries.rb

95.83% lines covered

96 relevant lines. 92 lines covered and 4 lines missed.
    
  1. # frozen_string_literal: true
  2. 14 module HTTPX
  3. 14 module Plugins
  4. #
  5. # This plugin adds support for retrying requests when errors happen.
  6. #
  7. # It has a default max number of retries (see *MAX_RETRIES* and the *max_retries* option),
  8. # after which it will return the last response, error or not. It will **not** raise an exception.
  9. #
  10. # It does not retry which are not considered idempotent (see *retry_change_requests* to override).
  11. #
  12. # https://gitlab.com/os85/httpx/wikis/Retries
  13. #
  14. 14 module Retries
  15. 14 MAX_RETRIES = 3
  16. # TODO: pass max_retries in a configure/load block
  17. 14 IDEMPOTENT_METHODS = %w[GET OPTIONS HEAD PUT DELETE].freeze
  18. 2 RETRYABLE_ERRORS = [
  19. 12 IOError,
  20. EOFError,
  21. Errno::ECONNRESET,
  22. Errno::ECONNABORTED,
  23. Errno::EPIPE,
  24. Errno::EINVAL,
  25. Errno::ETIMEDOUT,
  26. Parser::Error,
  27. TLSError,
  28. TimeoutError,
  29. ConnectionError,
  30. Connection::HTTP2::GoawayError,
  31. ].freeze
  32. 14 DEFAULT_JITTER = ->(interval) { interval * ((rand + 1) * 0.5) }
  33. 14 if ENV.key?("HTTPX_NO_JITTER")
  34. 14 def self.extra_options(options)
  35. 588 options.merge(max_retries: MAX_RETRIES)
  36. end
  37. else
  38. def self.extra_options(options)
  39. options.merge(max_retries: MAX_RETRIES, retry_jitter: DEFAULT_JITTER)
  40. end
  41. end
  42. # adds support for the following options:
  43. #
  44. # :max_retries :: max number of times a request will be retried (defaults to <tt>3</tt>).
  45. # :retry_change_requests :: whether idempotent requests are retried (defaults to <tt>false</tt>).
  46. # :retry_after:: seconds after which a request is retried; can also be a callable object (i.e. <tt>->(req, res) { ... } </tt>)
  47. # :retry_jitter :: number of seconds applied to *:retry_after* (must be a callable, i.e. <tt>->(retry_after) { ... } </tt>).
  48. # :retry_on :: callable which alternatively defines a different rule for when a response is to be retried
  49. # (i.e. <tt>->(res) { ... }</tt>).
  50. 14 module OptionsMethods
  51. 14 def option_retry_after(value)
  52. # return early if callable
  53. 182 unless value.respond_to?(:call)
  54. 84 value = Float(value)
  55. 84 raise TypeError, ":retry_after must be positive" unless value.positive?
  56. end
  57. 182 value
  58. end
  59. 14 def option_retry_jitter(value)
  60. # return early if callable
  61. 42 raise TypeError, ":retry_jitter must be callable" unless value.respond_to?(:call)
  62. 42 value
  63. end
  64. 14 def option_max_retries(value)
  65. 1799 num = Integer(value)
  66. 1799 raise TypeError, ":max_retries must be positive" unless num >= 0
  67. 1799 num
  68. end
  69. 14 def option_retry_change_requests(v)
  70. 954 v
  71. end
  72. 14 def option_retry_on(value)
  73. 201 raise TypeError, ":retry_on must be called with the response" unless value.respond_to?(:call)
  74. 201 value
  75. end
  76. end
  77. 14 module InstanceMethods
  78. 14 def max_retries(n)
  79. 84 with(max_retries: n)
  80. end
  81. 14 private
  82. 14 def fetch_response(request, connections, options)
  83. 2078621 response = super
  84. 2078621 if response &&
  85. request.retries.positive? &&
  86. __repeatable_request?(request, options) &&
  87. (
  88. 96 (
  89. 221 response.is_a?(ErrorResponse) && __retryable_error?(response.error)
  90. ) ||
  91. (
  92. 159 options.retry_on && options.retry_on.call(response)
  93. )
  94. )
  95. 397 __try_partial_retry(request, response)
  96. 397 log { "failed to get response, #{request.retries} tries to go..." }
  97. 397 request.retries -= 1
  98. 397 request.transition(:idle)
  99. 397 retry_after = options.retry_after
  100. 397 retry_after = retry_after.call(request, response) if retry_after.respond_to?(:call)
  101. 397 if retry_after
  102. # apply jitter
  103. 84 if (jitter = request.options.retry_jitter)
  104. 14 retry_after = jitter.call(retry_after)
  105. end
  106. 84 retry_start = Utils.now
  107. 84 log { "retrying after #{retry_after} secs..." }
  108. 84 deactivate_connection(request, connections, options)
  109. 84 pool.after(retry_after) do
  110. 84 if request.response
  111. # request has terminated abruptly meanwhile
  112. request.emit(:response, request.response)
  113. else
  114. 84 log { "retrying (elapsed time: #{Utils.elapsed_time(retry_start)})!!" }
  115. 84 send_request(request, connections, options)
  116. end
  117. end
  118. else
  119. 313 send_request(request, connections, options)
  120. end
  121. 343 return
  122. end
  123. 2078224 response
  124. end
  125. 14 def __repeatable_request?(request, options)
  126. 817 IDEMPOTENT_METHODS.include?(request.verb) || options.retry_change_requests
  127. end
  128. 14 def __retryable_error?(ex)
  129. 2866 RETRYABLE_ERRORS.any? { |klass| ex.is_a?(klass) }
  130. end
  131. 14 def proxy_error?(request, response)
  132. 56 super && !request.retries.positive?
  133. end
  134. #
  135. # Atttempt to set the request to perform a partial range request.
  136. # This happens if the peer server accepts byte-range requests, and
  137. # the last response contains some body payload.
  138. #
  139. 14 def __try_partial_retry(request, response)
  140. 397 response = response.response if response.is_a?(ErrorResponse)
  141. 397 return unless response
  142. 178 unless response.headers.key?("accept-ranges") &&
  143. response.headers["accept-ranges"] == "bytes" && # there's nothing else supported though...
  144. 14 (original_body = response.body)
  145. 164 response.close if response.respond_to?(:close)
  146. 142 return
  147. end
  148. 14 request.partial_response = response
  149. 14 size = original_body.bytesize
  150. 12 request.headers["range"] = "bytes=#{size}-"
  151. end
  152. end
  153. 14 module RequestMethods
  154. 14 attr_accessor :retries
  155. 14 attr_writer :partial_response
  156. 14 def initialize(*args)
  157. 606 super
  158. 606 @retries = @options.max_retries
  159. end
  160. 14 def response=(response)
  161. 1017 if @partial_response
  162. 14 if response.is_a?(Response) && response.status == 206
  163. 14 response.from_partial_response(@partial_response)
  164. else
  165. @partial_response.close
  166. end
  167. 14 @partial_response = nil
  168. end
  169. 1017 super
  170. end
  171. end
  172. 14 module ResponseMethods
  173. 14 def from_partial_response(response)
  174. 14 @status = response.status
  175. 14 @headers = response.headers
  176. 14 @body = response.body
  177. end
  178. end
  179. end
  180. 14 register_plugin :retries, Retries
  181. end
  182. end

lib/httpx/plugins/ssrf_filter.rb

100.0% lines covered

61 relevant lines. 61 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 class ServerSideRequestForgeryError < Error; end
  4. 7 module Plugins
  5. #
  6. # This plugin adds support for preventing Server-Side Request Forgery attacks.
  7. #
  8. # https://gitlab.com/os85/httpx/wikis/Server-Side-Request-Forgery-Filter
  9. #
  10. 7 module SsrfFilter
  11. 7 module IPAddrExtensions
  12. 7 refine IPAddr do
  13. 7 def prefixlen
  14. 112 mask_addr = @mask_addr
  15. 112 raise "Invalid mask" if mask_addr.zero?
  16. 371 mask_addr >>= 1 while (mask_addr & 0x1).zero?
  17. 112 length = 0
  18. 365 while mask_addr & 0x1 == 0x1
  19. 1518 length += 1
  20. 1518 mask_addr >>= 1
  21. end
  22. 112 length
  23. end
  24. end
  25. end
  26. 7 using IPAddrExtensions
  27. # https://en.wikipedia.org/wiki/Reserved_IP_addresses
  28. 2 IPV4_BLACKLIST = [
  29. 5 IPAddr.new("0.0.0.0/8"), # Current network (only valid as source address)
  30. IPAddr.new("10.0.0.0/8"), # Private network
  31. IPAddr.new("100.64.0.0/10"), # Shared Address Space
  32. IPAddr.new("127.0.0.0/8"), # Loopback
  33. IPAddr.new("169.254.0.0/16"), # Link-local
  34. IPAddr.new("172.16.0.0/12"), # Private network
  35. IPAddr.new("192.0.0.0/24"), # IETF Protocol Assignments
  36. IPAddr.new("192.0.2.0/24"), # TEST-NET-1, documentation and examples
  37. IPAddr.new("192.88.99.0/24"), # IPv6 to IPv4 relay (includes 2002::/16)
  38. IPAddr.new("192.168.0.0/16"), # Private network
  39. IPAddr.new("198.18.0.0/15"), # Network benchmark tests
  40. IPAddr.new("198.51.100.0/24"), # TEST-NET-2, documentation and examples
  41. IPAddr.new("203.0.113.0/24"), # TEST-NET-3, documentation and examples
  42. IPAddr.new("224.0.0.0/4"), # IP multicast (former Class D network)
  43. IPAddr.new("240.0.0.0/4"), # Reserved (former Class E network)
  44. IPAddr.new("255.255.255.255"), # Broadcast
  45. ].freeze
  46. 3 IPV6_BLACKLIST = ([
  47. 5 IPAddr.new("::1/128"), # Loopback
  48. IPAddr.new("64:ff9b::/96"), # IPv4/IPv6 translation (RFC 6052)
  49. IPAddr.new("100::/64"), # Discard prefix (RFC 6666)
  50. IPAddr.new("2001::/32"), # Teredo tunneling
  51. IPAddr.new("2001:10::/28"), # Deprecated (previously ORCHID)
  52. IPAddr.new("2001:20::/28"), # ORCHIDv2
  53. IPAddr.new("2001:db8::/32"), # Addresses used in documentation and example source code
  54. IPAddr.new("2002::/16"), # 6to4
  55. IPAddr.new("fc00::/7"), # Unique local address
  56. IPAddr.new("fe80::/10"), # Link-local address
  57. IPAddr.new("ff00::/8"), # Multicast
  58. ] + IPV4_BLACKLIST.flat_map do |ipaddr|
  59. 112 prefixlen = ipaddr.prefixlen
  60. 112 ipv4_compatible = ipaddr.ipv4_compat.mask(96 + prefixlen)
  61. 112 ipv4_mapped = ipaddr.ipv4_mapped.mask(80 + prefixlen)
  62. 112 [ipv4_compatible, ipv4_mapped]
  63. end).freeze
  64. 7 class << self
  65. 7 def extra_options(options)
  66. 61 options.merge(allowed_schemes: %w[https http])
  67. end
  68. 7 def unsafe_ip_address?(ipaddr)
  69. 82 range = ipaddr.to_range
  70. 82 return true if range.first != range.last
  71. 96 return IPV6_BLACKLIST.any? { |r| r.include?(ipaddr) } if ipaddr.ipv6?
  72. 822 IPV4_BLACKLIST.any? { |r| r.include?(ipaddr) } # then it's IPv4
  73. end
  74. end
  75. # adds support for the following options:
  76. #
  77. # :allowed_schemes :: list of URI schemes allowed (defaults to <tt>["https", "http"]</tt>)
  78. 7 module OptionsMethods
  79. 7 def option_allowed_schemes(value)
  80. 68 Array(value)
  81. end
  82. end
  83. 7 module InstanceMethods
  84. 7 def send_requests(*requests)
  85. 75 responses = requests.map do |request|
  86. 75 next if @options.allowed_schemes.include?(request.uri.scheme)
  87. 7 error = ServerSideRequestForgeryError.new("#{request.uri} URI scheme not allowed")
  88. 7 error.set_backtrace(caller)
  89. 7 response = ErrorResponse.new(request, error)
  90. 7 request.emit(:response, response)
  91. 7 response
  92. end
  93. 150 allowed_requests = requests.select { |req| responses[requests.index(req)].nil? }
  94. 75 allowed_responses = super(*allowed_requests)
  95. 75 allowed_responses.each_with_index do |res, idx|
  96. 68 req = allowed_requests[idx]
  97. 58 responses[requests.index(req)] = res
  98. end
  99. 75 responses
  100. end
  101. end
  102. 7 module ConnectionMethods
  103. 7 def initialize(*)
  104. begin
  105. 68 super
  106. 8 rescue ServerSideRequestForgeryError => e
  107. # may raise when IPs are passed as options via :addresses
  108. 14 throw(:resolve_error, e)
  109. end
  110. end
  111. 7 def addresses=(addrs)
  112. 150 addrs = addrs.map { |addr| addr.is_a?(IPAddr) ? addr : IPAddr.new(addr) }
  113. 68 addrs.reject!(&SsrfFilter.method(:unsafe_ip_address?))
  114. 68 raise ServerSideRequestForgeryError, "#{@origin.host} has no public IP addresses" if addrs.empty?
  115. 14 super
  116. end
  117. end
  118. end
  119. 7 register_plugin :ssrf_filter, SsrfFilter
  120. end
  121. end

lib/httpx/plugins/stream.rb

100.0% lines covered

74 relevant lines. 74 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 12 module HTTPX
  3. 12 class StreamResponse
  4. 12 def initialize(request, session)
  5. 147 @request = request
  6. 147 @session = session
  7. 147 @response = nil
  8. end
  9. 12 def each(&block)
  10. 189 return enum_for(__method__) unless block
  11. 133 @request.stream = self
  12. 13 begin
  13. 133 @on_chunk = block
  14. 133 if @request.response
  15. # if we've already started collecting the payload, yield it first
  16. # before proceeding.
  17. 14 body = @request.response.body
  18. 14 body.each do |chunk|
  19. 14 on_chunk(chunk)
  20. end
  21. end
  22. 133 response.raise_for_status
  23. ensure
  24. 133 @on_chunk = nil
  25. end
  26. end
  27. 12 def each_line
  28. 94 return enum_for(__method__) unless block_given?
  29. 47 line = "".b
  30. 47 each do |chunk|
  31. 38 line << chunk
  32. 106 while (idx = line.index("\n"))
  33. 47 yield line.byteslice(0..idx - 1)
  34. 47 line = line.byteslice(idx + 1..-1)
  35. end
  36. end
  37. 19 yield line unless line.empty?
  38. end
  39. # This is a ghost method. It's to be used ONLY internally, when processing streams
  40. 12 def on_chunk(chunk)
  41. 187 raise NoMethodError unless @on_chunk
  42. 187 @on_chunk.call(chunk)
  43. end
  44. skipped # :nocov:
  45. skipped def inspect
  46. skipped "#<StreamResponse:#{object_id}>"
  47. skipped end
  48. skipped # :nocov:
  49. 12 def to_s
  50. 14 response.to_s
  51. end
  52. 12 private
  53. 12 def response
  54. 463 return @response if @response
  55. 177 @request.response || begin
  56. 147 @response = @session.request(@request)
  57. end
  58. end
  59. 12 def respond_to_missing?(meth, *args)
  60. 14 response.respond_to?(meth, *args) || super
  61. end
  62. 12 def method_missing(meth, *args, &block)
  63. 151 return super unless response.respond_to?(meth)
  64. 151 response.__send__(meth, *args, &block)
  65. end
  66. end
  67. 12 module Plugins
  68. #
  69. # This plugin adds support for stream response (text/event-stream).
  70. #
  71. # https://gitlab.com/os85/httpx/wikis/Stream
  72. #
  73. 12 module Stream
  74. 12 def self.extra_options(options)
  75. 256 options.merge(timeout: { read_timeout: Float::INFINITY, operation_timeout: 60 })
  76. end
  77. 12 module InstanceMethods
  78. 12 def request(*args, stream: false, **options)
  79. 407 return super(*args, **options) unless stream
  80. 161 requests = args.first.is_a?(Request) ? args : build_requests(*args, options)
  81. 161 raise Error, "only 1 response at a time is supported for streaming requests" unless requests.size == 1
  82. 147 request = requests.first
  83. 147 StreamResponse.new(request, self)
  84. end
  85. end
  86. 12 module RequestMethods
  87. 12 attr_accessor :stream
  88. end
  89. 12 module ResponseMethods
  90. 12 def stream
  91. 241 request = @request.root_request if @request.respond_to?(:root_request)
  92. 241 request ||= @request
  93. 241 request.stream
  94. end
  95. end
  96. 12 module ResponseBodyMethods
  97. 12 def initialize(*)
  98. 241 super
  99. 241 @stream = @response.stream
  100. end
  101. 12 def write(chunk)
  102. 320 return super unless @stream
  103. 196 return 0 if chunk.empty?
  104. 173 chunk = decode_chunk(chunk)
  105. 173 @stream.on_chunk(chunk.dup)
  106. 173 chunk.size
  107. end
  108. 12 private
  109. 12 def transition(*)
  110. 155 return if @stream
  111. 155 super
  112. end
  113. end
  114. end
  115. 12 register_plugin :stream, Stream
  116. end
  117. end

lib/httpx/plugins/upgrade.rb

100.0% lines covered

37 relevant lines. 37 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin helps negotiating a new protocol from an HTTP/1.1 connection, via the
  6. # Upgrade header.
  7. #
  8. # https://gitlab.com/os85/httpx/wikis/Upgrade
  9. #
  10. 7 module Upgrade
  11. 7 class << self
  12. 7 def configure(klass)
  13. 28 klass.plugin(:"upgrade/h2")
  14. end
  15. 7 def extra_options(options)
  16. 28 options.merge(upgrade_handlers: {})
  17. end
  18. end
  19. 7 module OptionsMethods
  20. 7 def option_upgrade_handlers(value)
  21. 77 raise TypeError, ":upgrade_handlers must be a Hash" unless value.is_a?(Hash)
  22. 77 value
  23. end
  24. end
  25. 7 module InstanceMethods
  26. 7 def fetch_response(request, connections, options)
  27. 236 response = super
  28. 236 if response
  29. 77 return response unless response.is_a?(Response)
  30. 77 return response unless response.headers.key?("upgrade")
  31. 28 upgrade_protocol = response.headers["upgrade"].split(/ *, */).first
  32. 28 return response unless upgrade_protocol && options.upgrade_handlers.key?(upgrade_protocol)
  33. 28 protocol_handler = options.upgrade_handlers[upgrade_protocol]
  34. 28 return response unless protocol_handler
  35. 28 log { "upgrading to #{upgrade_protocol}..." }
  36. 28 connection = find_connection(request, connections, options)
  37. # do not upgrade already upgraded connections
  38. 28 return if connection.upgrade_protocol == upgrade_protocol
  39. 28 protocol_handler.call(connection, request, response)
  40. # keep in the loop if the server is switching, unless
  41. # the connection has been hijacked, in which case you want
  42. # to terminante immediately
  43. 28 return if response.status == 101 && !connection.hijacked
  44. end
  45. 173 response
  46. end
  47. 7 def close(*args)
  48. 35 return super if args.empty?
  49. 21 connections, = args
  50. 21 pool.close(connections.reject(&:hijacked))
  51. end
  52. end
  53. 7 module ConnectionMethods
  54. 7 attr_reader :upgrade_protocol, :hijacked
  55. 7 def hijack_io
  56. 7 @hijacked = true
  57. end
  58. end
  59. end
  60. 7 register_plugin(:upgrade, Upgrade)
  61. end
  62. end

lib/httpx/plugins/upgrade/h2.rb

91.67% lines covered

24 relevant lines. 22 lines covered and 2 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin adds support for upgrading an HTTP/1.1 connection to HTTP/2
  6. # via an Upgrade: h2 response declaration
  7. #
  8. # https://gitlab.com/os85/httpx/wikis/Connection-Upgrade#h2
  9. #
  10. 7 module H2
  11. 7 class << self
  12. 7 def extra_options(options)
  13. 28 options.merge(upgrade_handlers: options.upgrade_handlers.merge("h2" => self))
  14. end
  15. 7 def call(connection, _request, _response)
  16. 7 connection.upgrade_to_h2
  17. end
  18. end
  19. 7 module ConnectionMethods
  20. 7 using URIExtensions
  21. 7 def upgrade_to_h2
  22. 7 prev_parser = @parser
  23. 7 if prev_parser
  24. 7 prev_parser.reset
  25. 6 @inflight -= prev_parser.requests.size
  26. end
  27. 7 @parser = Connection::HTTP2.new(@write_buffer, @options)
  28. 7 set_parser_callbacks(@parser)
  29. 7 @upgrade_protocol = "h2"
  30. # what's happening here:
  31. # a deviation from the state machine is done to perform the actions when a
  32. # connection is closed, without transitioning, so the connection is kept in the pool.
  33. # the state is reset to initial, so that the socket reconnect works out of the box,
  34. # while the parser is already here.
  35. 7 purge_after_closed
  36. 7 transition(:idle)
  37. 7 prev_parser.requests.each do |req|
  38. req.transition(:idle)
  39. send(req)
  40. end
  41. end
  42. end
  43. end
  44. 7 register_plugin(:"upgrade/h2", H2)
  45. end
  46. end

lib/httpx/plugins/webdav.rb

100.0% lines covered

36 relevant lines. 36 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin implements convenience methods for performing WEBDAV requests.
  6. #
  7. # https://gitlab.com/os85/httpx/wikis/WebDav
  8. #
  9. 7 module WebDav
  10. 7 module InstanceMethods
  11. 7 def copy(src, dest)
  12. 14 request("COPY", src, headers: { "destination" => @options.origin.merge(dest) })
  13. end
  14. 7 def move(src, dest)
  15. 14 request("MOVE", src, headers: { "destination" => @options.origin.merge(dest) })
  16. end
  17. 7 def lock(path, timeout: nil, &blk)
  18. 42 headers = {}
  19. 36 headers["timeout"] = if timeout && timeout.positive?
  20. 14 "Second-#{timeout}"
  21. else
  22. 28 "Infinite, Second-4100000000"
  23. end
  24. 42 xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" \
  25. "<D:lockinfo xmlns:D=\"DAV:\">" \
  26. "<D:lockscope><D:exclusive/></D:lockscope>" \
  27. "<D:locktype><D:write/></D:locktype>" \
  28. "<D:owner>null</D:owner>" \
  29. "</D:lockinfo>"
  30. 42 response = request("LOCK", path, headers: headers, xml: xml)
  31. 42 return response unless response.is_a?(Response)
  32. 42 return response unless blk && response.status == 200
  33. 14 lock_token = response.headers["lock-token"]
  34. 1 begin
  35. 14 blk.call(response)
  36. ensure
  37. 14 unlock(path, lock_token)
  38. end
  39. end
  40. 7 def unlock(path, lock_token)
  41. 28 request("UNLOCK", path, headers: { "lock-token" => lock_token })
  42. end
  43. 7 def mkcol(dir)
  44. 14 request("MKCOL", dir)
  45. end
  46. 7 def propfind(path, xml = nil)
  47. 56 body = case xml
  48. when :acl
  49. 14 '<?xml version="1.0" encoding="utf-8" ?><D:propfind xmlns:D="DAV:"><D:prop><D:owner/>' \
  50. "<D:supported-privilege-set/><D:current-user-privilege-set/><D:acl/></D:prop></D:propfind>"
  51. when nil
  52. 28 '<?xml version="1.0" encoding="utf-8"?><DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
  53. else
  54. 14 xml
  55. end
  56. 56 request("PROPFIND", path, headers: { "depth" => "1" }, xml: body)
  57. end
  58. 7 def proppatch(path, xml)
  59. 4 body = "<?xml version=\"1.0\"?>" \
  60. 12 "<D:propertyupdate xmlns:D=\"DAV:\" xmlns:Z=\"http://ns.example.com/standards/z39.50/\">#{xml}</D:propertyupdate>"
  61. 14 request("PROPPATCH", path, xml: body)
  62. end
  63. # %i[ orderpatch acl report search]
  64. end
  65. end
  66. 7 register_plugin(:webdav, WebDav)
  67. end
  68. end

lib/httpx/pmatch_extensions.rb

100.0% lines covered

17 relevant lines. 17 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 module ResponsePatternMatchExtensions
  4. 24 def deconstruct
  5. 36 [@status, @headers, @body]
  6. end
  7. 24 def deconstruct_keys(_keys)
  8. 60 { status: @status, headers: @headers, body: @body }
  9. end
  10. end
  11. 24 module ErrorResponsePatternMatchExtensions
  12. 24 def deconstruct
  13. 10 [@error]
  14. end
  15. 24 def deconstruct_keys(_keys)
  16. 30 { error: @error }
  17. end
  18. end
  19. 24 module HeadersPatternMatchExtensions
  20. 24 def deconstruct
  21. 6 to_a
  22. end
  23. end
  24. 24 Headers.include HeadersPatternMatchExtensions
  25. 24 Response.include ResponsePatternMatchExtensions
  26. 24 ErrorResponse.include ErrorResponsePatternMatchExtensions
  27. end

lib/httpx/pool.rb

82.46% lines covered

171 relevant lines. 141 lines covered and 30 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "forwardable"
  3. 24 require "httpx/selector"
  4. 24 require "httpx/connection"
  5. 24 require "httpx/resolver"
  6. 24 module HTTPX
  7. 24 class Pool
  8. 24 using ArrayExtensions::FilterMap
  9. 24 extend Forwardable
  10. 24 def_delegator :@timers, :after
  11. 24 def initialize
  12. 548 @resolvers = {}
  13. 548 @timers = Timers.new
  14. 548 @selector = Selector.new
  15. 548 @connections = []
  16. end
  17. 24 def wrap
  18. 425 connections = @connections
  19. 425 @connections = []
  20. 46 begin
  21. 425 yield self
  22. ensure
  23. 425 @connections.unshift(*connections)
  24. end
  25. end
  26. 24 def empty?
  27. 786 @connections.empty?
  28. end
  29. 24 def next_tick
  30. 2229253 catch(:jump_tick) do
  31. 2229253 timeout = next_timeout
  32. 2229253 if timeout && timeout.negative?
  33. @timers.fire
  34. throw(:jump_tick)
  35. end
  36. 1068202 begin
  37. 2229253 @selector.select(timeout, &:call)
  38. 2229138 @timers.fire
  39. rescue TimeoutError => e
  40. 5 @timers.fire(e)
  41. end
  42. end
  43. rescue StandardError => e
  44. 24 @connections.each do |connection|
  45. 28 connection.emit(:error, e)
  46. end
  47. rescue Exception # rubocop:disable Lint/RescueException
  48. 91 @connections.each(&:force_reset)
  49. 84 raise
  50. end
  51. 24 def close(connections = @connections)
  52. 5619 return if connections.empty?
  53. 5477 connections = connections.reject(&:inflight?)
  54. 5477 connections.each(&:terminate)
  55. 11097 next_tick until connections.none? { |c| c.state != :idle && @connections.include?(c) }
  56. # close resolvers
  57. 5470 outstanding_connections = @connections
  58. 5470 resolver_connections = @resolvers.each_value.flat_map(&:connections).compact
  59. 4753 outstanding_connections -= resolver_connections
  60. 5470 return unless outstanding_connections.empty?
  61. 2928 @resolvers.each_value do |resolver|
  62. 2768 resolver.close unless resolver.closed?
  63. end
  64. # for https resolver
  65. 2928 resolver_connections.each(&:terminate)
  66. 2963 next_tick until resolver_connections.none? { |c| c.state != :idle && @connections.include?(c) }
  67. end
  68. 24 def init_connection(connection, _options)
  69. 5922 connection.timers = @timers
  70. 5922 connection.on(:activate) do
  71. 493 select_connection(connection)
  72. end
  73. 5922 connection.on(:exhausted) do
  74. 6 case connection.state
  75. when :closed
  76. 7 connection.idling
  77. 7 @connections << connection
  78. 7 select_connection(connection)
  79. when :closing
  80. connection.once(:close) do
  81. connection.idling
  82. @connections << connection
  83. select_connection(connection)
  84. end
  85. end
  86. end
  87. 5922 connection.on(:close) do
  88. 6616 unregister_connection(connection)
  89. end
  90. 5922 connection.on(:terminate) do
  91. 5280 unregister_connection(connection, true)
  92. end
  93. 5922 resolve_connection(connection) unless connection.family
  94. end
  95. 24 def deactivate(*connections)
  96. 978 connections.each do |connection|
  97. 1013 connection.deactivate
  98. 1013 deselect_connection(connection) if connection.state == :inactive
  99. end
  100. end
  101. # opens a connection to the IP reachable through +uri+.
  102. # Many hostnames are reachable through the same IP, so we try to
  103. # maximize pipelining by opening as few connections as possible.
  104. #
  105. 24 def find_connection(uri, options)
  106. 7437 conn = @connections.find do |connection|
  107. 12583 connection.match?(uri, options)
  108. end
  109. 7437 return unless conn
  110. 1373 case conn.state
  111. when :closed
  112. 396 conn.idling
  113. 396 select_connection(conn)
  114. when :closing
  115. conn.once(:close) do
  116. conn.idling
  117. select_connection(conn)
  118. end
  119. end
  120. 1494 conn
  121. end
  122. 24 private
  123. 24 def resolve_connection(connection)
  124. 5942 @connections << connection unless @connections.include?(connection)
  125. 5942 if connection.addresses || connection.open?
  126. #
  127. # there are two cases in which we want to activate initialization of
  128. # connection immediately:
  129. #
  130. # 1. when the connection already has addresses, i.e. it doesn't need to
  131. # resolve a name (not the same as name being an IP, yet)
  132. # 2. when the connection is initialized with an external already open IO.
  133. #
  134. 206 connection.once(:connect_error, &connection.method(:handle_error))
  135. 206 on_resolver_connection(connection)
  136. 197 return
  137. end
  138. 5736 find_resolver_for(connection) do |resolver|
  139. 400 resolver << try_clone_connection(connection, resolver.family)
  140. 390 next if resolver.empty?
  141. 319 select_connection(resolver)
  142. end
  143. end
  144. 24 def try_clone_connection(connection, family)
  145. 400 connection.family ||= family
  146. 400 return connection if connection.family == family
  147. new_connection = connection.class.new(connection.origin, connection.options)
  148. new_connection.family = family
  149. connection.once(:tcp_open) { new_connection.force_reset }
  150. connection.once(:connect_error) do |err|
  151. if new_connection.connecting?
  152. new_connection.merge(connection)
  153. connection.emit(:cloned, new_connection)
  154. connection.force_reset
  155. else
  156. connection.__send__(:handle_error, err)
  157. end
  158. end
  159. new_connection.once(:tcp_open) do |new_conn|
  160. if new_conn != connection
  161. new_conn.merge(connection)
  162. connection.force_reset
  163. end
  164. end
  165. new_connection.once(:connect_error) do |err|
  166. if connection.connecting?
  167. # main connection has the requests
  168. connection.merge(new_connection)
  169. new_connection.emit(:cloned, connection)
  170. new_connection.force_reset
  171. else
  172. new_connection.__send__(:handle_error, err)
  173. end
  174. end
  175. init_connection(new_connection, connection.options)
  176. new_connection
  177. end
  178. 24 def on_resolver_connection(connection)
  179. 5927 @connections << connection unless @connections.include?(connection)
  180. 5927 found_connection = @connections.find do |ch|
  181. 15857 ch != connection && ch.mergeable?(connection)
  182. end
  183. 5927 return register_connection(connection) unless found_connection
  184. 23 if found_connection.open?
  185. 22 coalesce_connections(found_connection, connection)
  186. 22 throw(:coalesced, found_connection) unless @connections.include?(connection)
  187. else
  188. 1 found_connection.once(:open) do
  189. 1 coalesce_connections(found_connection, connection)
  190. end
  191. end
  192. end
  193. 24 def on_resolver_error(connection, error)
  194. 160 return connection.emit(:connect_error, error) if connection.connecting? && connection.callbacks_for?(:connect_error)
  195. 160 connection.emit(:error, error)
  196. end
  197. 24 def on_resolver_close(resolver)
  198. 205 resolver_type = resolver.class
  199. 205 return if resolver.closed?
  200. 205 @resolvers.delete(resolver_type)
  201. 205 deselect_connection(resolver)
  202. 205 resolver.close unless resolver.closed?
  203. end
  204. 24 def register_connection(connection)
  205. 5916 select_connection(connection)
  206. end
  207. 24 def unregister_connection(connection, cleanup = !connection.used?)
  208. 11916 @connections.delete(connection) if cleanup
  209. 11916 deselect_connection(connection)
  210. end
  211. 24 def select_connection(connection)
  212. 7131 @selector.register(connection)
  213. end
  214. 24 def deselect_connection(connection)
  215. 12683 @selector.deregister(connection)
  216. end
  217. 24 def coalesce_connections(conn1, conn2)
  218. 23 return register_connection(conn2) unless conn1.coalescable?(conn2)
  219. 11 conn2.emit(:tcp_open, conn1)
  220. 11 conn1.merge(conn2)
  221. 11 @connections.delete(conn2)
  222. end
  223. 24 def next_timeout
  224. 1128608 [
  225. 32442 @timers.wait_interval,
  226. *@resolvers.values.reject(&:closed?).filter_map(&:timeout),
  227. *@connections.filter_map(&:timeout),
  228. 1068202 ].compact.min
  229. end
  230. 24 def find_resolver_for(connection)
  231. 5736 connection_options = connection.options
  232. 5736 resolver_type = connection_options.resolver_class
  233. 5736 resolver_type = Resolver.resolver_for(resolver_type)
  234. 5736 @resolvers[resolver_type] ||= begin
  235. 668 resolver_manager = if resolver_type.multi?
  236. 647 Resolver::Multi.new(resolver_type, connection_options)
  237. else
  238. 21 resolver_type.new(connection_options)
  239. end
  240. 668 resolver_manager.on(:resolve, &method(:on_resolver_connection))
  241. 668 resolver_manager.on(:error, &method(:on_resolver_error))
  242. 668 resolver_manager.on(:close, &method(:on_resolver_close))
  243. 668 resolver_manager
  244. end
  245. 5736 manager = @resolvers[resolver_type]
  246. 5736 (manager.is_a?(Resolver::Multi) && manager.early_resolve(connection)) || manager.resolvers.each do |resolver|
  247. 400 resolver.pool = self
  248. 400 yield resolver
  249. end
  250. 5687 manager
  251. end
  252. end
  253. end

lib/httpx/punycode.rb

100.0% lines covered

9 relevant lines. 9 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 module Punycode
  4. 24 module_function
  5. begin
  6. 24 require "idnx"
  7. 23 def encode_hostname(hostname)
  8. 28 Idnx.to_punycode(hostname)
  9. end
  10. rescue LoadError
  11. 1 def encode_hostname(hostname)
  12. 1 warn "#{hostname} cannot be converted to punycode. Install the " \
  13. "\"idnx\" gem: https://github.com/HoneyryderChuck/idnx"
  14. 1 hostname
  15. end
  16. end
  17. end
  18. end

lib/httpx/request.rb

100.0% lines covered

114 relevant lines. 114 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "delegate"
  3. 24 require "forwardable"
  4. 24 module HTTPX
  5. # Defines how an HTTP request is handled internally, both in terms of making attributes accessible,
  6. # as well as maintaining the state machine which manages streaming the request onto the wire.
  7. 24 class Request
  8. 24 extend Forwardable
  9. 24 include Callbacks
  10. 24 using URIExtensions
  11. # default value used for "user-agent" header, when not overridden.
  12. 24 USER_AGENT = "httpx.rb/#{VERSION}"
  13. # the upcased string HTTP verb for this request.
  14. 24 attr_reader :verb
  15. # the absolute URI object for this request.
  16. 24 attr_reader :uri
  17. # an HTTPX::Headers object containing the request HTTP headers.
  18. 24 attr_reader :headers
  19. # an HTTPX::Request::Body object containing the request body payload (or +nil+, whenn there is none).
  20. 24 attr_reader :body
  21. # a symbol describing which frame is currently being flushed.
  22. 24 attr_reader :state
  23. # an HTTPX::Options object containing request options.
  24. 24 attr_reader :options
  25. # the corresponding HTTPX::Response object, when there is one.
  26. 24 attr_reader :response
  27. # Exception raised during enumerable body writes.
  28. 24 attr_reader :drain_error
  29. # The IP address from the peer server.
  30. 24 attr_accessor :peer_address
  31. 24 attr_writer :persistent
  32. # will be +true+ when request body has been completely flushed.
  33. 24 def_delegator :@body, :empty?
  34. # initializes the instance with the given +verb+ (an upppercase String, ex. 'GEt'),
  35. # an absolute or relative +uri+ (either as String or URI::HTTP object), the
  36. # request +options+ (instance of HTTPX::Options) and an optional Hash of +params+.
  37. #
  38. # Besides any of the options documented in HTTPX::Options (which would override or merge with what
  39. # +options+ sets), it accepts also the following:
  40. #
  41. # :params :: hash or array of key-values which will be encoded and set in the query string of request uris.
  42. # :body :: to be encoded in the request body payload. can be a String, an IO object (i.e. a File), or an Enumerable.
  43. # :form :: hash of array of key-values which will be form-urlencoded- or multipart-encoded in requests body payload.
  44. # :json :: hash of array of key-values which will be JSON-encoded in requests body payload.
  45. # :xml :: Nokogiri XML nodes which will be encoded in requests body payload.
  46. #
  47. # :body, :form, :json and :xml are all mutually exclusive, i.e. only one of them gets picked up.
  48. 24 def initialize(verb, uri, options, params = EMPTY_HASH)
  49. 7975 @verb = verb.to_s.upcase
  50. 7975 @uri = Utils.to_uri(uri)
  51. 7974 @headers = options.headers.dup
  52. 7974 merge_headers(params.delete(:headers)) if params.key?(:headers)
  53. 7974 @headers["user-agent"] ||= USER_AGENT
  54. 7974 @headers["accept"] ||= "*/*"
  55. # forego compression in the Range request case
  56. 7974 if @headers.key?("range")
  57. 7 @headers.delete("accept-encoding")
  58. else
  59. 7967 @headers["accept-encoding"] ||= options.supported_compression_formats
  60. end
  61. 7974 @query_params = params.delete(:params) if params.key?(:params)
  62. 7974 @body = options.request_body_class.new(@headers, options, **params)
  63. 7967 @options = @body.options
  64. 7967 if @uri.relative? || @uri.host.nil?
  65. 524 origin = @options.origin
  66. 524 raise(Error, "invalid URI: #{@uri}") unless origin
  67. 504 base_path = @options.base_path
  68. 504 @uri = origin.merge("#{base_path}#{@uri}")
  69. end
  70. 7947 @state = :idle
  71. 7947 @response = nil
  72. 7947 @peer_address = nil
  73. 7947 @persistent = @options.persistent
  74. end
  75. # the read timeout defined for this requet.
  76. 24 def read_timeout
  77. 17419 @options.timeout[:read_timeout]
  78. end
  79. # the write timeout defined for this requet.
  80. 24 def write_timeout
  81. 17419 @options.timeout[:write_timeout]
  82. end
  83. # the request timeout defined for this requet.
  84. 24 def request_timeout
  85. 17170 @options.timeout[:request_timeout]
  86. end
  87. 24 def persistent?
  88. 3951 @persistent
  89. end
  90. # if the request contains trailer headers
  91. 24 def trailers?
  92. 2448 defined?(@trailers)
  93. end
  94. # returns an instance of HTTPX::Headers containing the trailer headers
  95. 24 def trailers
  96. 77 @trailers ||= @options.headers_class.new
  97. end
  98. # returns +:r+ or +:w+, depending on whether the request is waiting for a response or flushing.
  99. 24 def interests
  100. 20598 return :r if @state == :done || @state == :expect
  101. 2725 :w
  102. end
  103. # merges +h+ into the instance of HTTPX::Headers of the request.
  104. 24 def merge_headers(h)
  105. 671 @headers = @headers.merge(h)
  106. end
  107. # the URI scheme of the request +uri+.
  108. 24 def scheme
  109. 2941 @uri.scheme
  110. end
  111. # sets the +response+ on this request.
  112. 24 def response=(response)
  113. 7549 return unless response
  114. 7549 if response.is_a?(Response) && response.status < 200
  115. # deal with informational responses
  116. 140 if response.status == 100 && @headers.key?("expect")
  117. 119 @informational_status = response.status
  118. 119 return
  119. end
  120. # 103 Early Hints advertises resources in document to browsers.
  121. # not very relevant for an HTTP client, discard.
  122. 21 return if response.status >= 103
  123. end
  124. 7430 @response = response
  125. 7430 emit(:response_started, response)
  126. end
  127. # returnns the URI path of the request +uri+.
  128. 24 def path
  129. 7041 path = uri.path.dup
  130. 7041 path = +"" if path.nil?
  131. 7041 path << "/" if path.empty?
  132. 7041 path << "?#{query}" unless query.empty?
  133. 7041 path
  134. end
  135. # returs the URI authority of the request.
  136. #
  137. # session.build_request("GET", "https://google.com/query").authority #=> "google.com"
  138. # session.build_request("GET", "http://internal:3182/a").authority #=> "internal:3182"
  139. 24 def authority
  140. 7081 @uri.authority
  141. end
  142. # returs the URI origin of the request.
  143. #
  144. # session.build_request("GET", "https://google.com/query").authority #=> "https://google.com"
  145. # session.build_request("GET", "http://internal:3182/a").authority #=> "http://internal:3182"
  146. 24 def origin
  147. 3160 @uri.origin
  148. end
  149. # returs the URI query string of the request (when available).
  150. #
  151. # session.build_request("GET", "https://search.com").query #=> ""
  152. # session.build_request("GET", "https://search.com?q=a").query #=> "q=a"
  153. # session.build_request("GET", "https://search.com", params: { q: "a"}).query #=> "q=a"
  154. # session.build_request("GET", "https://search.com?q=a", params: { foo: "bar"}).query #=> "q=a&foo&bar"
  155. 24 def query
  156. 7814 return @query if defined?(@query)
  157. 6523 query = []
  158. 6523 if (q = @query_params)
  159. 132 query << Transcoder::Form.encode(q)
  160. end
  161. 6523 query << @uri.query if @uri.query
  162. 6523 @query = query.join("&")
  163. end
  164. # consumes and returns the next available chunk of request body that can be sent
  165. 24 def drain_body
  166. 7727 return nil if @body.nil?
  167. 7727 @drainer ||= @body.each
  168. 7727 chunk = @drainer.next.dup
  169. 5241 emit(:body_chunk, chunk)
  170. 5241 chunk
  171. rescue StopIteration
  172. 2476 nil
  173. rescue StandardError => e
  174. 10 @drain_error = e
  175. 10 nil
  176. end
  177. skipped # :nocov:
  178. skipped def inspect
  179. skipped "#<HTTPX::Request:#{object_id} " \
  180. skipped "#{@verb} " \
  181. skipped "#{uri} " \
  182. skipped "@headers=#{@headers} " \
  183. skipped "@body=#{@body}>"
  184. skipped end
  185. skipped # :nocov:
  186. # moves on to the +nextstate+ of the request state machine (when all preconditions are met)
  187. 24 def transition(nextstate)
  188. 28677 case nextstate
  189. when :idle
  190. 606 @body.rewind
  191. 606 @response = nil
  192. 606 @drainer = nil
  193. when :headers
  194. 8882 return unless @state == :idle
  195. when :body
  196. 8868 return unless @state == :headers ||
  197. @state == :expect
  198. 7190 if @headers.key?("expect")
  199. 438 if @informational_status && @informational_status == 100
  200. # check for 100 Continue response, and deallocate the var
  201. # if @informational_status == 100
  202. # @response = nil
  203. # end
  204. else
  205. 326 return if @state == :expect # do not re-set it
  206. 126 nextstate = :expect
  207. end
  208. end
  209. when :trailers
  210. 7176 return unless @state == :body
  211. when :done
  212. 7183 return if @state == :expect
  213. end
  214. 28174 @state = nextstate
  215. 28174 emit(@state, self)
  216. 6772 nil
  217. end
  218. # whether the request supports the 100-continue handshake and already processed the 100 response.
  219. 24 def expects?
  220. 6607 @headers["expect"] == "100-continue" && @informational_status == 100 && !@response
  221. end
  222. end
  223. end
  224. 24 require_relative "request/body"

lib/httpx/request/body.rb

100.0% lines covered

69 relevant lines. 69 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. # Implementation of the HTTP Request body as a delegator which iterates (responds to +each+) payload chunks.
  4. 24 class Request::Body < SimpleDelegator
  5. 24 class << self
  6. 24 def new(_, options, body: nil, **params)
  7. 7981 if body.is_a?(self)
  8. # request derives its options from body
  9. 14 body.options = options.merge(params)
  10. 12 return body
  11. end
  12. 7967 super
  13. end
  14. end
  15. 24 attr_accessor :options
  16. # inits the instance with the request +headers+, +options+ and +params+, which contain the payload definition.
  17. # it wraps the given body with the appropriate encoder on initialization.
  18. #
  19. # ..., json: { foo: "bar" }) #=> json encoder
  20. # ..., form: { foo: "bar" }) #=> form urlencoded encoder
  21. # ..., form: { foo: Pathname.open("path/to/file") }) #=> multipart urlencoded encoder
  22. # ..., form: { foo: File.open("path/to/file") }) #=> multipart urlencoded encoder
  23. # ..., form: { body: "bla") }) #=> raw data encoder
  24. 24 def initialize(headers, options, body: nil, form: nil, json: nil, xml: nil, **params)
  25. 7967 @headers = headers
  26. 7967 @options = options.merge(params)
  27. 7967 @body = if body
  28. 1043 Transcoder::Body.encode(body)
  29. 6923 elsif form
  30. 1302 Transcoder::Form.encode(form)
  31. 5621 elsif json
  32. 63 Transcoder::JSON.encode(json)
  33. 5558 elsif xml
  34. 119 Transcoder::Xml.encode(xml)
  35. end
  36. 7967 if @body
  37. 2527 if @options.compress_request_body && @headers.key?("content-encoding")
  38. 69 @headers.get("content-encoding").each do |encoding|
  39. 69 @body = self.class.initialize_deflater_body(@body, encoding)
  40. end
  41. end
  42. 2527 @headers["content-type"] ||= @body.content_type
  43. 2527 @headers["content-length"] = @body.bytesize unless unbounded_body?
  44. end
  45. 7960 super(@body)
  46. end
  47. # consumes and yields the request payload in chunks.
  48. 24 def each(&block)
  49. 5210 return enum_for(__method__) unless block
  50. 2605 return if @body.nil?
  51. 2542 body = stream(@body)
  52. 2542 if body.respond_to?(:read)
  53. 1087 ::IO.copy_stream(body, ProcIO.new(block))
  54. 1454 elsif body.respond_to?(:each)
  55. 346 body.each(&block)
  56. else
  57. 1109 block[body.to_s]
  58. end
  59. end
  60. # if the +@body+ is rewindable, it rewinnds it.
  61. 24 def rewind
  62. 718 return if empty?
  63. 133 @body.rewind if @body.respond_to?(:rewind)
  64. end
  65. # return +true+ if the +body+ has been fully drained (or does nnot exist).
  66. 24 def empty?
  67. 15546 return true if @body.nil?
  68. 6912 return false if chunked?
  69. 6828 @body.bytesize.zero?
  70. end
  71. # returns the +@body+ payload size in bytes.
  72. 24 def bytesize
  73. 2764 return 0 if @body.nil?
  74. 112 @body.bytesize
  75. end
  76. # sets the body to yield using chunked trannsfer encoding format.
  77. 24 def stream(body)
  78. 2542 return body unless chunked?
  79. 84 Transcoder::Chunker.encode(body.enum_for(:each))
  80. end
  81. # returns whether the body yields infinitely.
  82. 24 def unbounded_body?
  83. 3017 return @unbounded_body if defined?(@unbounded_body)
  84. 2527 @unbounded_body = !@body.nil? && (chunked? || @body.bytesize == Float::INFINITY)
  85. end
  86. # returns whether the chunked transfer encoding header is set.
  87. 24 def chunked?
  88. 16109 @headers["transfer-encoding"] == "chunked"
  89. end
  90. # sets the chunked transfer encoding header.
  91. 24 def chunk!
  92. 28 @headers.add("transfer-encoding", "chunked")
  93. end
  94. skipped # :nocov:
  95. skipped def inspect
  96. skipped "#<HTTPX::Request::Body:#{object_id} " \
  97. skipped "#{unbounded_body? ? "stream" : "@bytesize=#{bytesize}"}>"
  98. skipped end
  99. skipped # :nocov:
  100. 24 class << self
  101. # returns the +body+ wrapped with the correct deflater accordinng to the given +encodisng+.
  102. 24 def initialize_deflater_body(body, encoding)
  103. 62 case encoding
  104. when "gzip"
  105. 34 Transcoder::GZIP.encode(body)
  106. when "deflate"
  107. 14 Transcoder::Deflate.encode(body)
  108. when "identity"
  109. 14 body
  110. else
  111. 7 body
  112. end
  113. end
  114. end
  115. end
  116. # Wrapper yielder which can be used with functions which expect an IO writer.
  117. 24 class ProcIO
  118. 24 def initialize(block)
  119. 1087 @block = block
  120. end
  121. # Implementation the IO write protocol, which yield the given chunk to +@block+.
  122. 24 def write(data)
  123. 2995 @block.call(data.dup)
  124. 2988 data.bytesize
  125. end
  126. end
  127. end

lib/httpx/resolver.rb

100.0% lines covered

79 relevant lines. 79 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "resolv"
  3. 24 require "ipaddr"
  4. 24 module HTTPX
  5. 24 module Resolver
  6. 24 RESOLVE_TIMEOUT = [2, 3].freeze
  7. 24 require "httpx/resolver/resolver"
  8. 24 require "httpx/resolver/system"
  9. 24 require "httpx/resolver/native"
  10. 24 require "httpx/resolver/https"
  11. 24 require "httpx/resolver/multi"
  12. 24 @lookup_mutex = Thread::Mutex.new
  13. 173 @lookups = Hash.new { |h, k| h[k] = [] }
  14. 24 @identifier_mutex = Thread::Mutex.new
  15. 24 @identifier = 1
  16. 24 @system_resolver = Resolv::Hosts.new
  17. 24 module_function
  18. 24 def resolver_for(resolver_type)
  19. 5021 case resolver_type
  20. 5617 when :native then Native
  21. 28 when :system then System
  22. 62 when :https then HTTPS
  23. else
  24. 64 return resolver_type if resolver_type.is_a?(Class) && resolver_type < Resolver
  25. 7 raise Error, "unsupported resolver type (#{resolver_type})"
  26. end
  27. end
  28. 24 def nolookup_resolve(hostname)
  29. 5611 ip_resolve(hostname) || cached_lookup(hostname) || system_resolve(hostname)
  30. end
  31. 24 def ip_resolve(hostname)
  32. 5611 [IPAddr.new(hostname)]
  33. rescue ArgumentError
  34. end
  35. 24 def system_resolve(hostname)
  36. 467 ips = @system_resolver.getaddresses(hostname)
  37. 467 return if ips.empty?
  38. 579 ips.map { |ip| IPAddr.new(ip) }
  39. rescue IOError
  40. end
  41. 24 def cached_lookup(hostname)
  42. 5329 now = Utils.now
  43. 5329 @lookup_mutex.synchronize do
  44. 5329 lookup(hostname, now)
  45. end
  46. end
  47. 24 def cached_lookup_set(hostname, family, entries)
  48. 204 now = Utils.now
  49. 204 entries.each do |entry|
  50. 256 entry["TTL"] += now
  51. end
  52. 204 @lookup_mutex.synchronize do
  53. 175 case family
  54. when Socket::AF_INET6
  55. 35 @lookups[hostname].concat(entries)
  56. when Socket::AF_INET
  57. 169 @lookups[hostname].unshift(*entries)
  58. end
  59. 204 entries.each do |entry|
  60. 256 next unless entry["name"] != hostname
  61. 24 case family
  62. when Socket::AF_INET6
  63. 7 @lookups[entry["name"]] << entry
  64. when Socket::AF_INET
  65. 19 @lookups[entry["name"]].unshift(entry)
  66. end
  67. end
  68. end
  69. end
  70. # do not use directly!
  71. 24 def lookup(hostname, ttl)
  72. 5336 return unless @lookups.key?(hostname)
  73. 4864 entries = @lookups[hostname] = @lookups[hostname].select do |address|
  74. 11631 address["TTL"] > ttl
  75. end
  76. 4864 ips = entries.flat_map do |address|
  77. 11621 if address.key?("alias")
  78. 7 lookup(address["alias"], ttl)
  79. else
  80. 11614 IPAddr.new(address["data"])
  81. end
  82. end.compact
  83. 4864 ips unless ips.empty?
  84. end
  85. 24 def generate_id
  86. 1326 @identifier_mutex.synchronize { @identifier = (@identifier + 1) & 0xFFFF }
  87. end
  88. 24 def encode_dns_query(hostname, type: Resolv::DNS::Resource::IN::A, message_id: generate_id)
  89. 611 Resolv::DNS::Message.new.tap do |query|
  90. 663 query.id = message_id
  91. 663 query.rd = 1
  92. 663 query.add_question(hostname, type)
  93. 103 end.encode
  94. end
  95. 24 def decode_dns_answer(payload)
  96. 51 begin
  97. 608 message = Resolv::DNS::Message.decode(payload)
  98. rescue Resolv::DNS::DecodeError => e
  99. 5 return :decode_error, e
  100. end
  101. # no domain was found
  102. 603 return :no_domain_found if message.rcode == Resolv::DNS::RCode::NXDomain
  103. 241 return :message_truncated if message.tc == 1
  104. 231 return :dns_error, message.rcode if message.rcode != Resolv::DNS::RCode::NoError
  105. 221 addresses = []
  106. 221 message.each_answer do |question, _, value|
  107. 866 case value
  108. when Resolv::DNS::Resource::IN::CNAME
  109. 18 addresses << {
  110. "name" => question.to_s,
  111. "TTL" => value.ttl,
  112. "alias" => value.name.to_s,
  113. }
  114. when Resolv::DNS::Resource::IN::A,
  115. Resolv::DNS::Resource::IN::AAAA
  116. 876 addresses << {
  117. 21 "name" => question.to_s,
  118. "TTL" => value.ttl,
  119. "data" => value.address.to_s,
  120. }
  121. end
  122. end
  123. 221 [:ok, addresses]
  124. end
  125. end
  126. end

lib/httpx/resolver/https.rb

88.0% lines covered

150 relevant lines. 132 lines covered and 18 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "resolv"
  3. 24 require "uri"
  4. 24 require "cgi"
  5. 24 require "forwardable"
  6. 24 require "httpx/base64"
  7. 24 module HTTPX
  8. 24 class Resolver::HTTPS < Resolver::Resolver
  9. 24 extend Forwardable
  10. 24 using URIExtensions
  11. 24 module DNSExtensions
  12. 24 refine Resolv::DNS do
  13. 24 def generate_candidates(name)
  14. 35 @config.generate_candidates(name)
  15. end
  16. end
  17. end
  18. 24 using DNSExtensions
  19. 24 NAMESERVER = "https://1.1.1.1/dns-query"
  20. 2 DEFAULTS = {
  21. 22 uri: NAMESERVER,
  22. use_get: false,
  23. }.freeze
  24. 24 def_delegators :@resolver_connection, :state, :connecting?, :to_io, :call, :close, :terminate
  25. 24 def initialize(_, options)
  26. 40 super
  27. 40 @resolver_options = DEFAULTS.merge(@options.resolver_options)
  28. 40 @queries = {}
  29. 40 @requests = {}
  30. 40 @connections = []
  31. 40 @uri = URI(@resolver_options[:uri])
  32. 40 @uri_addresses = nil
  33. 40 @resolver = Resolv::DNS.new
  34. 40 @resolver.timeouts = @resolver_options.fetch(:timeouts, Resolver::RESOLVE_TIMEOUT)
  35. 40 @resolver.lazy_initialize
  36. end
  37. 24 def <<(connection)
  38. 75 return if @uri.origin == connection.origin.to_s
  39. 40 @uri_addresses ||= HTTPX::Resolver.nolookup_resolve(@uri.host) || @resolver.getaddresses(@uri.host)
  40. 40 if @uri_addresses.empty?
  41. 5 ex = ResolveError.new("Can't resolve DNS server #{@uri.host}")
  42. 5 ex.set_backtrace(caller)
  43. 5 connection.force_reset
  44. 5 throw(:resolve_error, ex)
  45. end
  46. 35 resolve(connection)
  47. end
  48. 24 def closed?
  49. 199 true
  50. end
  51. 24 def empty?
  52. 70 true
  53. end
  54. 24 def resolver_connection
  55. 90 @resolver_connection ||= @pool.find_connection(@uri, @options) || begin
  56. 35 @building_connection = true
  57. 35 connection = @options.connection_class.new(@uri, @options.merge(ssl: { alpn_protocols: %w[h2] }))
  58. 35 @pool.init_connection(connection, @options)
  59. # only explicity emit addresses if connection didn't pre-resolve, i.e. it's not an IP.
  60. 35 catch(:coalesced) do
  61. 35 @building_connection = false
  62. 35 emit_addresses(connection, @family, @uri_addresses) unless connection.addresses
  63. 35 connection
  64. end
  65. end
  66. end
  67. 24 private
  68. 24 def resolve(connection = @connections.first, hostname = nil)
  69. 55 return if @building_connection
  70. 55 return unless connection
  71. 55 hostname ||= @queries.key(connection)
  72. 55 if hostname.nil?
  73. 35 hostname = connection.origin.host
  74. 35 log { "resolver: resolve IDN #{connection.origin.non_ascii_hostname} as #{hostname}" } if connection.origin.non_ascii_hostname
  75. 35 hostname = @resolver.generate_candidates(hostname).each do |name|
  76. 105 @queries[name.to_s] = connection
  77. end.first.to_s
  78. else
  79. 20 @queries[hostname] = connection
  80. end
  81. 55 log { "resolver: query #{FAMILY_TYPES[RECORD_TYPES[@family]]} for #{hostname}" }
  82. begin
  83. 55 request = build_request(hostname)
  84. 55 request.on(:response, &method(:on_response).curry(2)[request])
  85. 55 request.on(:promise, &method(:on_promise))
  86. 55 @requests[request] = hostname
  87. 55 resolver_connection.send(request)
  88. 55 @connections << connection
  89. rescue ResolveError, Resolv::DNS::EncodeError => e
  90. reset_hostname(hostname)
  91. emit_resolve_error(connection, connection.origin.host, e)
  92. end
  93. end
  94. 24 def on_response(request, response)
  95. 55 response.raise_for_status
  96. rescue StandardError => e
  97. 5 hostname = @requests.delete(request)
  98. 5 connection = reset_hostname(hostname)
  99. 5 emit_resolve_error(connection, connection.origin.host, e)
  100. else
  101. # @type var response: HTTPX::Response
  102. 50 parse(request, response)
  103. ensure
  104. 55 @requests.delete(request)
  105. end
  106. 24 def on_promise(_, stream)
  107. log(level: 2) { "#{stream.id}: refusing stream!" }
  108. stream.refuse
  109. end
  110. 24 def parse(request, response)
  111. 50 code, result = decode_response_body(response)
  112. 50 case code
  113. when :ok
  114. 15 parse_addresses(result, request)
  115. when :no_domain_found
  116. # Indicates no such domain was found.
  117. 30 host = @requests.delete(request)
  118. 30 connection = reset_hostname(host, reset_candidates: false)
  119. 30 unless @queries.value?(connection)
  120. 10 emit_resolve_error(connection)
  121. 10 return
  122. end
  123. 20 resolve
  124. when :dns_error
  125. host = @requests.delete(request)
  126. connection = reset_hostname(host)
  127. emit_resolve_error(connection)
  128. when :decode_error
  129. 5 host = @requests.delete(request)
  130. 5 connection = reset_hostname(host)
  131. 5 emit_resolve_error(connection, connection.origin.host, result)
  132. end
  133. end
  134. 24 def parse_addresses(answers, request)
  135. 15 if answers.empty?
  136. # no address found, eliminate candidates
  137. host = @requests.delete(request)
  138. connection = reset_hostname(host)
  139. emit_resolve_error(connection)
  140. return
  141. else
  142. 35 answers = answers.group_by { |answer| answer["name"] }
  143. 15 answers.each do |hostname, addresses|
  144. 20 addresses = addresses.flat_map do |address|
  145. 20 if address.key?("alias")
  146. 5 alias_address = answers[address["alias"]]
  147. 5 if alias_address.nil?
  148. reset_hostname(address["name"])
  149. if catch(:coalesced) { early_resolve(connection, hostname: address["alias"]) }
  150. @connections.delete(connection)
  151. else
  152. resolve(connection, address["alias"])
  153. return # rubocop:disable Lint/NonLocalExitFromIterator
  154. end
  155. else
  156. 5 alias_address
  157. end
  158. else
  159. 15 address
  160. end
  161. end.compact
  162. 20 next if addresses.empty?
  163. 20 hostname.delete_suffix!(".") if hostname.end_with?(".")
  164. 20 connection = reset_hostname(hostname, reset_candidates: false)
  165. 20 next unless connection # probably a retried query for which there's an answer
  166. 15 @connections.delete(connection)
  167. # eliminate other candidates
  168. 45 @queries.delete_if { |_, conn| connection == conn }
  169. 15 Resolver.cached_lookup_set(hostname, @family, addresses) if @resolver_options[:cache]
  170. 45 catch(:coalesced) { emit_addresses(connection, @family, addresses.map { |addr| addr["data"] }) }
  171. end
  172. end
  173. 15 return if @connections.empty?
  174. resolve
  175. end
  176. 24 def build_request(hostname)
  177. 50 uri = @uri.dup
  178. 50 rklass = @options.request_class
  179. 50 payload = Resolver.encode_dns_query(hostname, type: @record_type)
  180. 50 if @resolver_options[:use_get]
  181. 5 params = URI.decode_www_form(uri.query.to_s)
  182. 5 params << ["type", FAMILY_TYPES[@record_type]]
  183. 5 params << ["dns", Base64.urlsafe_encode64(payload, padding: false)]
  184. 5 uri.query = URI.encode_www_form(params)
  185. 5 request = rklass.new("GET", uri, @options)
  186. else
  187. 45 request = rklass.new("POST", uri, @options, body: [payload])
  188. 45 request.headers["content-type"] = "application/dns-message"
  189. end
  190. 50 request.headers["accept"] = "application/dns-message"
  191. 50 request
  192. end
  193. 24 def decode_response_body(response)
  194. 45 case response.headers["content-type"]
  195. when "application/dns-udpwireformat",
  196. "application/dns-message"
  197. 45 Resolver.decode_dns_answer(response.to_s)
  198. else
  199. raise Error, "unsupported DNS mime-type (#{response.headers["content-type"]})"
  200. end
  201. end
  202. 24 def reset_hostname(hostname, reset_candidates: true)
  203. 60 connection = @queries.delete(hostname)
  204. 60 return connection unless connection && reset_candidates
  205. # eliminate other candidates
  206. 30 candidates = @queries.select { |_, conn| connection == conn }.keys
  207. 30 @queries.delete_if { |h, _| candidates.include?(h) }
  208. 10 connection
  209. end
  210. end
  211. end

lib/httpx/resolver/multi.rb

100.0% lines covered

40 relevant lines. 40 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "forwardable"
  3. 24 require "resolv"
  4. 24 module HTTPX
  5. 24 class Resolver::Multi
  6. 24 include Callbacks
  7. 24 using ArrayExtensions::FilterMap
  8. 24 attr_reader :resolvers
  9. 24 def initialize(resolver_type, options)
  10. 647 @options = options
  11. 647 @resolver_options = @options.resolver_options
  12. 647 @resolvers = options.ip_families.map do |ip_family|
  13. 647 resolver = resolver_type.new(ip_family, options)
  14. 647 resolver.on(:resolve, &method(:on_resolver_connection))
  15. 647 resolver.on(:error, &method(:on_resolver_error))
  16. 831 resolver.on(:close) { on_resolver_close(resolver) }
  17. 647 resolver
  18. end
  19. 647 @errors = Hash.new { |hs, k| hs[k] = [] }
  20. end
  21. 24 def closed?
  22. 2231078 @resolvers.all?(&:closed?)
  23. end
  24. 24 def timeout
  25. 2227950 @resolvers.filter_map(&:timeout).min
  26. end
  27. 24 def close
  28. 2733 @resolvers.each(&:close)
  29. end
  30. 24 def connections
  31. 10520 @resolvers.filter_map { |r| r.resolver_connection if r.respond_to?(:resolver_connection) }
  32. end
  33. 24 def early_resolve(connection)
  34. 5715 hostname = connection.origin.host
  35. 5715 addresses = @resolver_options[:cache] && (connection.addresses || HTTPX::Resolver.nolookup_resolve(hostname))
  36. 5715 return unless addresses
  37. 5529 addresses.group_by(&:family).sort { |(f1, _), (f2, _)| f2 <=> f1 }.each do |family, addrs|
  38. # try to match the resolver by family. However, there are cases where that's not possible, as when
  39. # the system does not have IPv6 connectivity, but it does support IPv6 via loopback/link-local.
  40. 11030 resolver = @resolvers.find { |r| r.family == family } || @resolvers.first
  41. 5515 next unless resolver # this should ever happen
  42. # it does not matter which resolver it is, as early-resolve code is shared.
  43. 5515 resolver.emit_addresses(connection, family, addrs, true)
  44. end
  45. end
  46. 24 private
  47. 24 def on_resolver_connection(connection)
  48. 5711 emit(:resolve, connection)
  49. end
  50. 24 def on_resolver_error(connection, error)
  51. 149 emit(:error, connection, error)
  52. end
  53. 24 def on_resolver_close(resolver)
  54. 184 emit(:close, resolver)
  55. end
  56. end
  57. end

lib/httpx/resolver/native.rb

94.44% lines covered

270 relevant lines. 255 lines covered and 15 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "forwardable"
  3. 24 require "resolv"
  4. 24 module HTTPX
  5. 24 class Resolver::Native < Resolver::Resolver
  6. 24 extend Forwardable
  7. 24 using URIExtensions
  8. 2 DEFAULTS = {
  9. 22 nameserver: nil,
  10. **Resolv::DNS::Config.default_config_hash,
  11. packet_size: 512,
  12. timeouts: Resolver::RESOLVE_TIMEOUT,
  13. }.freeze
  14. 24 DNS_PORT = 53
  15. 24 def_delegator :@connections, :empty?
  16. 24 attr_reader :state
  17. 24 def initialize(family, options)
  18. 607 super
  19. 607 @ns_index = 0
  20. 607 @resolver_options = DEFAULTS.merge(@options.resolver_options)
  21. 607 @socket_type = @resolver_options.fetch(:socket_type, :udp)
  22. 607 @nameserver = if (nameserver = @resolver_options[:nameserver])
  23. 602 nameserver = nameserver[family] if nameserver.is_a?(Hash)
  24. 602 Array(nameserver)
  25. end
  26. 607 @ndots = @resolver_options.fetch(:ndots, 1)
  27. 1821 @search = Array(@resolver_options[:search]).map { |srch| srch.scan(/[^.]+/) }
  28. 607 @_timeouts = Array(@resolver_options[:timeouts])
  29. 1858 @timeouts = Hash.new { |timeouts, host| timeouts[host] = @_timeouts.dup }
  30. 607 @connections = []
  31. 607 @queries = {}
  32. 607 @read_buffer = "".b
  33. 607 @write_buffer = Buffer.new(@resolver_options[:packet_size])
  34. 607 @state = :idle
  35. end
  36. 24 def close
  37. 2917 transition(:closed)
  38. end
  39. 24 def closed?
  40. 2231247 @state == :closed
  41. end
  42. 24 def to_io
  43. 1060 @io.to_io
  44. end
  45. 24 def call
  46. 836 case @state
  47. when :open
  48. 920 consume
  49. end
  50. 148 nil
  51. rescue Errno::EHOSTUNREACH => e
  52. 15 @ns_index += 1
  53. 15 nameserver = @nameserver
  54. 15 if nameserver && @ns_index < nameserver.size
  55. 10 log { "resolver: failed resolving on nameserver #{@nameserver[@ns_index - 1]} (#{e.message})" }
  56. 10 transition(:idle)
  57. 10 @timeouts.clear
  58. else
  59. 5 handle_error(e)
  60. end
  61. rescue NativeResolveError => e
  62. 103 handle_error(e)
  63. end
  64. 24 def interests
  65. 1086436 case @state
  66. when :idle
  67. 2788 transition(:open)
  68. when :closed
  69. 196 transition(:idle)
  70. 196 transition(:open)
  71. end
  72. 2213391 calculate_interests
  73. end
  74. 24 def <<(connection)
  75. 304 if @nameserver.nil?
  76. 5 ex = ResolveError.new("No available nameserver")
  77. 5 ex.set_backtrace(caller)
  78. 5 connection.force_reset
  79. 5 throw(:resolve_error, ex)
  80. else
  81. 299 @connections << connection
  82. 299 resolve
  83. end
  84. end
  85. 24 def timeout
  86. 2227950 return if @connections.empty?
  87. 3494 @start_timeout = Utils.now
  88. 3494 hosts = @queries.keys
  89. 3494 @timeouts.values_at(*hosts).reject(&:empty?).map(&:first).min
  90. end
  91. 24 def handle_socket_timeout(interval)
  92. 80 do_retry(interval)
  93. end
  94. 24 private
  95. 24 def calculate_interests
  96. 2215098 return :w unless @write_buffer.empty?
  97. 2213786 return :r unless @queries.empty?
  98. 2193294 nil
  99. end
  100. 24 def consume
  101. 905 dread if calculate_interests == :r
  102. 802 do_retry
  103. 802 dwrite if calculate_interests == :w
  104. end
  105. 24 def do_retry(loop_time = nil)
  106. 882 return if @queries.empty? || !@start_timeout
  107. 669 loop_time ||= Utils.elapsed_time(@start_timeout)
  108. 669 query = @queries.first
  109. 669 return unless query
  110. 669 h, connection = query
  111. 669 host = connection.origin.host
  112. 669 timeout = (@timeouts[host][0] -= loop_time)
  113. 669 return unless timeout <= 0
  114. 60 @timeouts[host].shift
  115. 60 if !@timeouts[host].empty?
  116. 35 log { "resolver: timeout after #{timeout}s, retry(#{@timeouts[host].first}) #{host}..." }
  117. # must downgrade to tcp AND retry on same host as last
  118. 35 downgrade_socket
  119. 35 resolve(connection, h)
  120. 25 elsif @ns_index + 1 < @nameserver.size
  121. # try on the next nameserver
  122. 5 @ns_index += 1
  123. 5 log { "resolver: failed resolving #{host} on nameserver #{@nameserver[@ns_index - 1]} (timeout error)" }
  124. 5 transition(:idle)
  125. 5 @timeouts.clear
  126. 5 resolve(connection, h)
  127. else
  128. 20 @timeouts.delete(host)
  129. 20 reset_hostname(h, reset_candidates: false)
  130. 20 return unless @queries.empty?
  131. 5 @connections.delete(connection)
  132. # This loop_time passed to the exception is bogus. Ideally we would pass the total
  133. # resolve timeout, including from the previous retries.
  134. 5 raise ResolveTimeoutError.new(loop_time, "Timed out while resolving #{connection.origin.host}")
  135. end
  136. end
  137. 24 def dread(wsize = @resolver_options[:packet_size])
  138. 563 loop do
  139. 834 wsize = @large_packet.capacity if @large_packet
  140. 834 siz = @io.read(wsize, @read_buffer)
  141. 834 unless siz
  142. ex = EOFError.new("descriptor closed")
  143. ex.set_backtrace(caller)
  144. raise ex
  145. end
  146. 834 return unless siz.positive?
  147. 573 if @socket_type == :tcp
  148. # packet may be incomplete, need to keep draining from the socket
  149. 25 if @large_packet
  150. # large packet buffer already exists, continue pumping
  151. 10 @large_packet << @read_buffer
  152. 10 next unless @large_packet.full?
  153. 10 parse(@large_packet.to_s)
  154. 10 @large_packet = nil
  155. # downgrade to udp again
  156. 10 downgrade_socket
  157. 10 return
  158. else
  159. 15 size = @read_buffer[0, 2].unpack1("n")
  160. 15 buffer = @read_buffer.byteslice(2..-1)
  161. 15 if size > @read_buffer.bytesize
  162. # only do buffer logic if it's worth it, and the whole packet isn't here already
  163. 10 @large_packet = Buffer.new(size)
  164. 10 @large_packet << buffer
  165. 10 next
  166. else
  167. 5 parse(buffer)
  168. end
  169. end
  170. else # udp
  171. 548 parse(@read_buffer)
  172. end
  173. 450 return if @state == :closed
  174. end
  175. end
  176. 24 def dwrite
  177. 608 loop do
  178. 1216 return if @write_buffer.empty?
  179. 608 siz = @io.write(@write_buffer)
  180. 608 unless siz
  181. ex = EOFError.new("descriptor closed")
  182. ex.set_backtrace(caller)
  183. raise ex
  184. end
  185. 608 return unless siz.positive?
  186. 608 return if @state == :closed
  187. end
  188. end
  189. 24 def parse(buffer)
  190. 563 code, result = Resolver.decode_dns_answer(buffer)
  191. 505 case code
  192. when :ok
  193. 206 parse_addresses(result)
  194. when :no_domain_found
  195. # Indicates no such domain was found.
  196. 332 hostname, connection = @queries.first
  197. 332 reset_hostname(hostname, reset_candidates: false)
  198. 332 unless @queries.value?(connection)
  199. 83 @connections.delete(connection)
  200. 83 raise NativeResolveError.new(connection, connection.origin.host, "name or service not known")
  201. end
  202. 249 resolve
  203. when :message_truncated
  204. # TODO: what to do if it's already tcp??
  205. 10 return if @socket_type == :tcp
  206. 10 @socket_type = :tcp
  207. 10 hostname, _ = @queries.first
  208. 10 reset_hostname(hostname)
  209. 10 transition(:closed)
  210. when :dns_error
  211. 10 hostname, connection = @queries.first
  212. 10 reset_hostname(hostname)
  213. 10 @connections.delete(connection)
  214. 10 ex = NativeResolveError.new(connection, connection.origin.host, "unknown DNS error (error code #{result})")
  215. 10 raise ex
  216. when :decode_error
  217. 5 hostname, connection = @queries.first
  218. 5 reset_hostname(hostname)
  219. 5 @connections.delete(connection)
  220. 5 ex = NativeResolveError.new(connection, connection.origin.host, result.message)
  221. 5 ex.set_backtrace(result.backtrace)
  222. 5 raise ex
  223. end
  224. end
  225. 24 def parse_addresses(addresses)
  226. 206 if addresses.empty?
  227. # no address found, eliminate candidates
  228. 5 hostname, connection = @queries.first
  229. 5 reset_hostname(hostname)
  230. 5 @connections.delete(connection)
  231. 5 raise NativeResolveError.new(connection, connection.origin.host)
  232. else
  233. 201 address = addresses.first
  234. 201 name = address["name"]
  235. 201 connection = @queries.delete(name)
  236. 201 unless connection
  237. orig_name = name
  238. # absolute name
  239. name_labels = Resolv::DNS::Name.create(name).to_a
  240. name = @queries.each_key.first { |hname| name_labels == Resolv::DNS::Name.create(hname).to_a }
  241. # probably a retried query for which there's an answer
  242. unless name
  243. @timeouts.delete(orig_name)
  244. return
  245. end
  246. address["name"] = name
  247. connection = @queries.delete(name)
  248. end
  249. 201 if address.key?("alias") # CNAME
  250. 16 hostname_alias = address["alias"]
  251. # clean up intermediate queries
  252. 16 @timeouts.delete(name) unless connection.origin.host == name
  253. 32 if catch(:coalesced) { early_resolve(connection, hostname: hostname_alias) }
  254. 1 @connections.delete(connection)
  255. else
  256. 15 if @socket_type == :tcp
  257. # must downgrade to udp if tcp
  258. 5 @socket_type = @resolver_options.fetch(:socket_type, :udp)
  259. 5 transition(:idle)
  260. 5 transition(:open)
  261. end
  262. 15 log { "resolver: ALIAS #{hostname_alias} for #{name}" }
  263. 15 resolve(connection, hostname_alias)
  264. 15 return
  265. end
  266. else
  267. 185 reset_hostname(name, connection: connection)
  268. 185 @timeouts.delete(connection.origin.host)
  269. 185 @connections.delete(connection)
  270. 185 Resolver.cached_lookup_set(connection.origin.host, @family, addresses) if @resolver_options[:cache]
  271. 902 catch(:coalesced) { emit_addresses(connection, @family, addresses.map { |addr| addr["data"] }) }
  272. end
  273. end
  274. 186 return emit(:close) if @connections.empty?
  275. 2 resolve
  276. end
  277. 24 def resolve(connection = @connections.first, hostname = nil)
  278. 615 raise Error, "no URI to resolve" unless connection
  279. 615 return unless @write_buffer.empty?
  280. 613 hostname ||= @queries.key(connection)
  281. 613 if hostname.nil?
  282. 309 hostname = connection.origin.host
  283. 309 log { "resolver: resolve IDN #{connection.origin.non_ascii_hostname} as #{hostname}" } if connection.origin.non_ascii_hostname
  284. 309 hostname = generate_candidates(hostname).each do |name|
  285. 1112 @queries[name] = connection
  286. end.first
  287. else
  288. 277 @queries[hostname] = connection
  289. end
  290. 613 log { "resolver: query #{@record_type.name.split("::").last} for #{hostname}" }
  291. 51 begin
  292. 613 @write_buffer << encode_dns_query(hostname)
  293. rescue Resolv::DNS::EncodeError => e
  294. emit_resolve_error(connection, hostname, e)
  295. end
  296. end
  297. 24 def encode_dns_query(hostname)
  298. 613 message_id = Resolver.generate_id
  299. 613 msg = Resolver.encode_dns_query(hostname, type: @record_type, message_id: message_id)
  300. 613 msg[0, 2] = [msg.size, message_id].pack("nn") if @socket_type == :tcp
  301. 613 msg
  302. end
  303. 24 def generate_candidates(name)
  304. 309 return [name] if name.end_with?(".")
  305. 309 candidates = []
  306. 309 name_parts = name.scan(/[^.]+/)
  307. 309 candidates = [name] if @ndots <= name_parts.size - 1
  308. 927 candidates.concat(@search.map { |domain| [*name_parts, *domain].join(".") })
  309. 309 fname = "#{name}."
  310. 309 candidates << fname unless candidates.include?(fname)
  311. 309 candidates
  312. end
  313. 24 def build_socket
  314. 475 ip, port = @nameserver[@ns_index]
  315. 475 port ||= DNS_PORT
  316. 390 case @socket_type
  317. when :udp
  318. 460 log { "resolver: server: udp://#{ip}:#{port}..." }
  319. 460 UDP.new(ip, port, @options)
  320. when :tcp
  321. 15 log { "resolver: server: tcp://#{ip}:#{port}..." }
  322. 15 origin = URI("tcp://#{ip}:#{port}")
  323. 15 TCP.new(origin, [ip], @options)
  324. end
  325. end
  326. 24 def downgrade_socket
  327. 45 return unless @socket_type == :tcp
  328. 5 @socket_type = @resolver_options.fetch(:socket_type, :udp)
  329. 5 transition(:idle)
  330. 5 transition(:open)
  331. end
  332. 24 def transition(nextstate)
  333. 5384 case nextstate
  334. when :idle
  335. 221 if @io
  336. 221 @io.close
  337. 221 @io = nil
  338. end
  339. when :open
  340. 2994 return unless @state == :idle
  341. 2994 @io ||= build_socket
  342. 2994 @io.connect
  343. 2994 return unless @io.connected?
  344. 475 resolve if @queries.empty? && !@connections.empty?
  345. when :closed
  346. 2927 return unless @state == :open
  347. 423 @io.close if @io
  348. 423 @start_timeout = nil
  349. 423 @write_buffer.clear
  350. 423 @read_buffer.clear
  351. end
  352. 1119 @state = nextstate
  353. end
  354. 24 def handle_error(error)
  355. 108 if error.respond_to?(:connection) &&
  356. error.respond_to?(:host)
  357. 103 emit_resolve_error(error.connection, error.host, error)
  358. else
  359. 5 @queries.each do |host, connection|
  360. 20 emit_resolve_error(connection, host, error)
  361. end
  362. end
  363. end
  364. 24 def reset_hostname(hostname, connection: @queries.delete(hostname), reset_candidates: true)
  365. 567 @timeouts.delete(hostname)
  366. 567 @timeouts.delete(hostname)
  367. 567 return unless connection && reset_candidates
  368. # eliminate other candidates
  369. 860 candidates = @queries.select { |_, conn| connection == conn }.keys
  370. 860 @queries.delete_if { |h, _| candidates.include?(h) }
  371. # reset timeouts
  372. 888 @timeouts.delete_if { |h, _| candidates.include?(h) }
  373. end
  374. end
  375. end

lib/httpx/resolver/resolver.rb

90.0% lines covered

60 relevant lines. 54 lines covered and 6 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "resolv"
  3. 24 require "ipaddr"
  4. 24 module HTTPX
  5. 24 class Resolver::Resolver
  6. 24 include Callbacks
  7. 24 include Loggable
  8. 24 using ArrayExtensions::Intersect
  9. 2 RECORD_TYPES = {
  10. 22 Socket::AF_INET6 => Resolv::DNS::Resource::IN::AAAA,
  11. Socket::AF_INET => Resolv::DNS::Resource::IN::A,
  12. }.freeze
  13. 2 FAMILY_TYPES = {
  14. 22 Resolv::DNS::Resource::IN::AAAA => "AAAA",
  15. Resolv::DNS::Resource::IN::A => "A",
  16. }.freeze
  17. 24 class << self
  18. 24 def multi?
  19. 647 true
  20. end
  21. end
  22. 24 attr_reader :family
  23. 24 attr_writer :pool
  24. 24 def initialize(family, options)
  25. 668 @family = family
  26. 668 @record_type = RECORD_TYPES[family]
  27. 668 @options = options
  28. end
  29. 24 def close; end
  30. 24 alias_method :terminate, :close
  31. 24 def closed?
  32. true
  33. end
  34. 24 def empty?
  35. true
  36. end
  37. 24 def emit_addresses(connection, family, addresses, early_resolve = false)
  38. 5761 addresses.map! do |address|
  39. 12839 address.is_a?(IPAddr) ? address : IPAddr.new(address.to_s)
  40. end
  41. # double emission check, but allow early resolution to work
  42. 5761 return if !early_resolve && connection.addresses && !addresses.intersect?(connection.addresses)
  43. 5802 log { "resolver: answer #{FAMILY_TYPES[RECORD_TYPES[family]]} #{connection.origin.host}: #{addresses.inspect}" }
  44. 5761 if @pool && # if triggered by early resolve, pool may not be here yet
  45. !connection.io &&
  46. connection.options.ip_families.size > 1 &&
  47. family == Socket::AF_INET &&
  48. addresses.first.to_s != connection.origin.host.to_s
  49. log { "resolver: A response, applying resolution delay..." }
  50. @pool.after(0.05) do
  51. unless connection.state == :closed ||
  52. # double emission check
  53. (connection.addresses && addresses.intersect?(connection.addresses))
  54. emit_resolved_connection(connection, addresses, early_resolve)
  55. end
  56. end
  57. else
  58. 5761 emit_resolved_connection(connection, addresses, early_resolve)
  59. end
  60. end
  61. 24 private
  62. 24 def emit_resolved_connection(connection, addresses, early_resolve)
  63. begin
  64. 5761 connection.addresses = addresses
  65. 5721 emit(:resolve, connection)
  66. 24 rescue StandardError => e
  67. 40 if early_resolve
  68. 34 connection.force_reset
  69. 34 throw(:resolve_error, e)
  70. else
  71. 6 emit(:error, connection, e)
  72. end
  73. end
  74. end
  75. 24 def early_resolve(connection, hostname: connection.origin.host)
  76. 16 addresses = @resolver_options[:cache] && (connection.addresses || HTTPX::Resolver.nolookup_resolve(hostname))
  77. 16 return unless addresses
  78. 5 addresses = addresses.select { |addr| addr.family == @family }
  79. 1 return if addresses.empty?
  80. 1 emit_addresses(connection, @family, addresses, true)
  81. end
  82. 24 def emit_resolve_error(connection, hostname = connection.origin.host, ex = nil)
  83. 154 emit(:error, connection, resolve_error(hostname, ex))
  84. end
  85. 24 def resolve_error(hostname, ex = nil)
  86. 154 return ex if ex.is_a?(ResolveError) || ex.is_a?(ResolveTimeoutError)
  87. 50 message = ex ? ex.message : "Can't resolve #{hostname}"
  88. 50 error = ResolveError.new(message)
  89. 50 error.set_backtrace(ex ? ex.backtrace : caller)
  90. 50 error
  91. end
  92. end
  93. end

lib/httpx/resolver/system.rb

92.68% lines covered

123 relevant lines. 114 lines covered and 9 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "forwardable"
  3. 24 require "resolv"
  4. 24 module HTTPX
  5. 24 class Resolver::System < Resolver::Resolver
  6. 24 using URIExtensions
  7. 24 extend Forwardable
  8. 24 RESOLV_ERRORS = [Resolv::ResolvError,
  9. Resolv::DNS::Requester::RequestError,
  10. Resolv::DNS::EncodeError,
  11. Resolv::DNS::DecodeError].freeze
  12. 24 DONE = 1
  13. 24 ERROR = 2
  14. 24 class << self
  15. 24 def multi?
  16. 21 false
  17. end
  18. end
  19. 24 attr_reader :state
  20. 24 def_delegator :@connections, :empty?
  21. 24 def initialize(options)
  22. 21 super(nil, options)
  23. 21 @resolver_options = @options.resolver_options
  24. 21 resolv_options = @resolver_options.dup
  25. 21 timeouts = resolv_options.delete(:timeouts) || Resolver::RESOLVE_TIMEOUT
  26. 21 @_timeouts = Array(timeouts)
  27. 42 @timeouts = Hash.new { |tims, host| tims[host] = @_timeouts.dup }
  28. 21 resolv_options.delete(:cache)
  29. 21 @connections = []
  30. 21 @queries = []
  31. 21 @ips = []
  32. 21 @pipe_mutex = Thread::Mutex.new
  33. 21 @state = :idle
  34. end
  35. 24 def resolvers
  36. 42 return enum_for(__method__) unless block_given?
  37. 21 yield self
  38. end
  39. 24 def connections
  40. EMPTY
  41. end
  42. 24 def close
  43. 21 transition(:closed)
  44. end
  45. 24 def closed?
  46. 62 @state == :closed
  47. end
  48. 24 def to_io
  49. 20 @pipe_read.to_io
  50. end
  51. 24 def call
  52. 20 case @state
  53. when :open
  54. 20 consume
  55. end
  56. nil
  57. end
  58. 24 def interests
  59. 20 return if @queries.empty?
  60. 20 :r
  61. end
  62. 24 def timeout
  63. 20 return unless @queries.empty?
  64. _, connection = @queries.first
  65. return unless connection
  66. @timeouts[connection.origin.host].first
  67. end
  68. 24 def <<(connection)
  69. 21 @connections << connection
  70. 21 resolve
  71. end
  72. 24 def handle_socket_timeout(interval)
  73. error = HTTPX::ResolveTimeoutError.new(interval, "timed out while waiting on select")
  74. error.set_backtrace(caller)
  75. on_error(error)
  76. end
  77. 24 private
  78. 24 def transition(nextstate)
  79. 42 case nextstate
  80. when :idle
  81. @timeouts.clear
  82. when :open
  83. 21 return unless @state == :idle
  84. 21 @pipe_read, @pipe_write = ::IO.pipe
  85. when :closed
  86. 21 return unless @state == :open
  87. 21 @pipe_write.close
  88. 21 @pipe_read.close
  89. end
  90. 42 @state = nextstate
  91. end
  92. 24 def consume
  93. 41 return if @connections.empty?
  94. 62 while @pipe_read.ready? && (event = @pipe_read.getbyte)
  95. 21 case event
  96. when DONE
  97. 20 *pair, addrs = @pipe_mutex.synchronize { @ips.pop }
  98. 10 @queries.delete(pair)
  99. 10 family, connection = pair
  100. 20 catch(:coalesced) { emit_addresses(connection, family, addrs) }
  101. when ERROR
  102. 22 *pair, error = @pipe_mutex.synchronize { @ips.pop }
  103. 11 @queries.delete(pair)
  104. 11 family, connection = pair
  105. 11 emit_resolve_error(connection, connection.origin.host, error)
  106. end
  107. 21 @connections.delete(connection) if @queries.empty?
  108. end
  109. 41 return emit(:close, self) if @connections.empty?
  110. 20 resolve
  111. end
  112. 24 def resolve(connection = @connections.first)
  113. 41 raise Error, "no URI to resolve" unless connection
  114. 41 return unless @queries.empty?
  115. 21 hostname = connection.origin.host
  116. 21 scheme = connection.origin.scheme
  117. 21 log { "resolver: resolve IDN #{connection.origin.non_ascii_hostname} as #{hostname}" } if connection.origin.non_ascii_hostname
  118. 21 transition(:open)
  119. 21 connection.options.ip_families.each do |family|
  120. 21 @queries << [family, connection]
  121. end
  122. 21 async_resolve(connection, hostname, scheme)
  123. 21 consume
  124. end
  125. 24 def async_resolve(connection, hostname, scheme)
  126. 21 families = connection.options.ip_families
  127. 21 log { "resolver: query for #{hostname}" }
  128. 21 timeouts = @timeouts[connection.origin.host]
  129. 21 resolve_timeout = timeouts.first
  130. 21 Thread.start do
  131. 21 Thread.current.report_on_exception = false
  132. begin
  133. 21 addrs = if resolve_timeout
  134. 21 Timeout.timeout(resolve_timeout) do
  135. 21 __addrinfo_resolve(hostname, scheme)
  136. end
  137. else
  138. __addrinfo_resolve(hostname, scheme)
  139. end
  140. 10 addrs = addrs.sort_by(&:afamily).group_by(&:afamily)
  141. 10 families.each do |family|
  142. 10 addresses = addrs[family]
  143. 10 next unless addresses
  144. 10 addresses.map!(&:ip_address)
  145. 10 addresses.uniq!
  146. 10 @pipe_mutex.synchronize do
  147. 10 @ips.unshift([family, connection, addresses])
  148. 10 @pipe_write.putc(DONE) unless @pipe_write.closed?
  149. end
  150. end
  151. rescue StandardError => e
  152. 11 if e.is_a?(Timeout::Error)
  153. 1 timeouts.shift
  154. 1 retry unless timeouts.empty?
  155. 1 e = ResolveTimeoutError.new(resolve_timeout, e.message)
  156. 1 e.set_backtrace(e.backtrace)
  157. end
  158. 11 @pipe_mutex.synchronize do
  159. 11 families.each do |family|
  160. 11 @ips.unshift([family, connection, e])
  161. 11 @pipe_write.putc(ERROR) unless @pipe_write.closed?
  162. end
  163. end
  164. end
  165. end
  166. end
  167. 24 def __addrinfo_resolve(host, scheme)
  168. 21 Addrinfo.getaddrinfo(host, scheme, Socket::AF_UNSPEC, Socket::SOCK_STREAM)
  169. end
  170. end
  171. end

lib/httpx/response.rb

100.0% lines covered

105 relevant lines. 105 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "objspace"
  3. 24 require "stringio"
  4. 24 require "tempfile"
  5. 24 require "fileutils"
  6. 24 require "forwardable"
  7. 24 module HTTPX
  8. # Defines a HTTP response is handled internally, with a few properties exposed as attributes.
  9. #
  10. # It delegates the following methods to the corresponding HTTPX::Request:
  11. #
  12. # * HTTPX::Request#uri
  13. # * HTTPX::Request#peer_address
  14. #
  15. # It implements (indirectly, via the +body+) the IO write protocol to internally buffer payloads.
  16. #
  17. # It implements the IO reader protocol in order for users to buffer/stream it, acts as an enumerable
  18. # (of payload chunks).
  19. #
  20. 24 class Response
  21. 24 extend Forwardable
  22. 24 include Callbacks
  23. # the HTTP response status code
  24. 24 attr_reader :status
  25. # an HTTPX::Headers object containing the response HTTP headers.
  26. 24 attr_reader :headers
  27. # a HTTPX::Response::Body object wrapping the response body. The following methods are delegated to it:
  28. #
  29. # * HTTPX::Response::Body#to_s
  30. # * HTTPX::Response::Body#to_str
  31. # * HTTPX::Response::Body#read
  32. # * HTTPX::Response::Body#copy_to
  33. # * HTTPX::Response::Body#close
  34. 24 attr_reader :body
  35. # The HTTP protocol version used to fetch the response.
  36. 24 attr_reader :version
  37. # returns the response body buffered in a string.
  38. 24 def_delegator :@body, :to_s
  39. 24 def_delegator :@body, :to_str
  40. # implements the IO reader +#read+ interface.
  41. 24 def_delegator :@body, :read
  42. # copies the response body to a different location.
  43. 24 def_delegator :@body, :copy_to
  44. # closes the body.
  45. 24 def_delegator :@body, :close
  46. # the corresponding request uri.
  47. 24 def_delegator :@request, :uri
  48. # the IP address of the peer server.
  49. 24 def_delegator :@request, :peer_address
  50. # inits the instance with the corresponding +request+ to this response, an the
  51. # response HTTP +status+, +version+ and HTTPX::Headers instance of +headers+.
  52. 24 def initialize(request, status, version, headers)
  53. 7321 @request = request
  54. 7321 @options = request.options
  55. 7321 @version = version
  56. 7321 @status = Integer(status)
  57. 7321 @headers = @options.headers_class.new(headers)
  58. 7321 @body = @options.response_body_class.new(self, @options)
  59. 7321 @finished = complete?
  60. 7321 @content_type = nil
  61. end
  62. # merges headers defined in +h+ into the response headers.
  63. 24 def merge_headers(h)
  64. 162 @headers = @headers.merge(h)
  65. end
  66. # writes +data+ chunk into the response body.
  67. 24 def <<(data)
  68. 9852 @body.write(data)
  69. end
  70. # returns the HTTPX::ContentType for the response, as per what's declared in the content-type header.
  71. #
  72. # response.content_type #=> #<HTTPX::ContentType:xxx @header_value="text/plain">
  73. # response.content_type.mime_type #=> "text/plain"
  74. 24 def content_type
  75. 7582 @content_type ||= ContentType.new(@headers["content-type"])
  76. end
  77. # returns whether the response has been fully fetched.
  78. 24 def finished?
  79. 3843 @finished
  80. end
  81. # marks the response as finished, freezes the headers.
  82. 24 def finish!
  83. 3749 @finished = true
  84. 3749 @headers.freeze
  85. end
  86. # returns whether the response contains body payload.
  87. 24 def bodyless?
  88. 7321 @request.verb == "HEAD" ||
  89. @status < 200 || # informational response
  90. @status == 204 ||
  91. @status == 205 ||
  92. @status == 304 || begin
  93. 6933 content_length = @headers["content-length"]
  94. 6933 return false if content_length.nil?
  95. 5994 content_length == "0"
  96. end
  97. end
  98. 24 def complete?
  99. 7321 bodyless? || (@request.verb == "CONNECT" && @status == 200)
  100. end
  101. skipped # :nocov:
  102. skipped def inspect
  103. skipped "#<Response:#{object_id} " \
  104. skipped "HTTP/#{version} " \
  105. skipped "@status=#{@status} " \
  106. skipped "@headers=#{@headers} " \
  107. skipped "@body=#{@body.bytesize}>"
  108. skipped end
  109. skipped # :nocov:
  110. # returns an instance of HTTPX::HTTPError if the response has a 4xx or 5xx
  111. # status code, or nothing.
  112. #
  113. # ok_response.error #=> nil
  114. # not_found_response.error #=> HTTPX::HTTPError instance, status 404
  115. 24 def error
  116. 451 return if @status < 400
  117. 47 HTTPError.new(self)
  118. end
  119. # it raises the exception returned by +error+, or itself otherwise.
  120. #
  121. # ok_response.raise_for_status #=> ok_response
  122. # not_found_response.raise_for_status #=> raises HTTPX::HTTPError exception
  123. 24 def raise_for_status
  124. 416 return self unless (err = error)
  125. 33 raise err
  126. end
  127. # decodes the response payload into a ruby object **if** the payload is valid json.
  128. #
  129. # response.json #≈> { "foo" => "bar" } for "{\"foo\":\"bar\"}" payload
  130. # response.json(symbolize_names: true) #≈> { foo: "bar" } for "{\"foo\":\"bar\"}" payload
  131. 24 def json(*args)
  132. 65 decode(Transcoder::JSON, *args)
  133. end
  134. # decodes the response payload into a ruby object **if** the payload is valid
  135. # "application/x-www-urlencoded" or "multipart/form-data".
  136. 24 def form
  137. 56 decode(Transcoder::Form)
  138. end
  139. # decodes the response payload into a Nokogiri::XML::Node object **if** the payload is valid
  140. # "application/xml" (requires the "nokogiri" gem).
  141. 24 def xml
  142. 7 decode(Transcoder::Xml)
  143. end
  144. 24 private
  145. # decodes the response payload using the given +transcoder+, which implements the decoding logic.
  146. #
  147. # +transcoder+ must implement the internal transcoder API, i.e. respond to <tt>decode(HTTPX::Response response)</tt>,
  148. # which returns a decoder which responds to <tt>call(HTTPX::Response response, **kwargs)</tt>
  149. 24 def decode(transcoder, *args)
  150. # TODO: check if content-type is a valid format, i.e. "application/json" for json parsing
  151. 128 decoder = transcoder.decode(self)
  152. 114 raise Error, "no decoder available for \"#{transcoder}\"" unless decoder
  153. 114 @body.rewind
  154. 114 decoder.call(self, *args)
  155. end
  156. end
  157. # Helper class which decodes the HTTP "content-type" header.
  158. 24 class ContentType
  159. 24 MIME_TYPE_RE = %r{^([^/]+/[^;]+)(?:$|;)}.freeze
  160. 24 CHARSET_RE = /;\s*charset=([^;]+)/i.freeze
  161. 24 def initialize(header_value)
  162. 7548 @header_value = header_value
  163. end
  164. # returns the mime type declared in the header.
  165. #
  166. # ContentType.new("application/json; charset=utf-8").mime_type #=> "application/json"
  167. 24 def mime_type
  168. 128 return @mime_type if defined?(@mime_type)
  169. 94 m = @header_value.to_s[MIME_TYPE_RE, 1]
  170. 94 m && @mime_type = m.strip.downcase
  171. end
  172. # returns the charset declared in the header.
  173. #
  174. # ContentType.new("application/json; charset=utf-8").charset #=> "utf-8"
  175. # ContentType.new("text/plain").charset #=> nil
  176. 24 def charset
  177. 7454 return @charset if defined?(@charset)
  178. 7454 m = @header_value.to_s[CHARSET_RE, 1]
  179. 7454 m && @charset = m.strip.delete('"')
  180. end
  181. end
  182. # Wraps an error which has happened while processing an HTTP Request. It has partial
  183. # public API parity with HTTPX::Response, so users should rely on it to infer whether
  184. # the returned response is one or the other.
  185. #
  186. # response = HTTPX.get("https://some-domain/path") #=> response is HTTPX::Response or HTTPX::ErrorResponse
  187. # response.raise_for_status #=> raises if it wraps an error
  188. 24 class ErrorResponse
  189. 24 include Loggable
  190. 24 extend Forwardable
  191. # the corresponding HTTPX::Request instance.
  192. 24 attr_reader :request
  193. # the HTTPX::Response instance, when there is one (i.e. error happens fetching the response).
  194. 24 attr_reader :response
  195. # the wrapped exception.
  196. 24 attr_reader :error
  197. # the request uri
  198. 24 def_delegator :@request, :uri
  199. # the IP address of the peer server.
  200. 24 def_delegator :@request, :peer_address
  201. 24 def initialize(request, error)
  202. 936 @request = request
  203. 936 @response = request.response if request.response.is_a?(Response)
  204. 936 @error = error
  205. 936 @options = request.options
  206. 936 log_exception(@error)
  207. end
  208. # returns the exception full message.
  209. 24 def to_s
  210. 8 @error.full_message(highlight: false)
  211. end
  212. # closes the error resources.
  213. 24 def close
  214. 7 @response.close if @response && @response.respond_to?(:close)
  215. end
  216. # always true for error responses.
  217. 24 def finished?
  218. 7 true
  219. end
  220. # raises the wrapped exception.
  221. 24 def raise_for_status
  222. 66 raise @error
  223. end
  224. # buffers lost chunks to error response
  225. 24 def <<(data)
  226. 7 @response << data
  227. end
  228. end
  229. end
  230. 24 require_relative "response/body"
  231. 24 require_relative "response/buffer"
  232. 24 require_relative "pmatch_extensions" if RUBY_VERSION >= "2.7.0"

lib/httpx/response/body.rb

100.0% lines covered

115 relevant lines. 115 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. # Implementation of the HTTP Response body as a buffer which implements the IO writer protocol
  4. # (for buffering the response payload), the IO reader protocol (for consuming the response payload),
  5. # and can be iterated over (via #each, which yields the payload in chunks).
  6. 24 class Response::Body
  7. # the payload encoding (i.e. "utf-8", "ASCII-8BIT")
  8. 24 attr_reader :encoding
  9. # Array of encodings contained in the response "content-encoding" header.
  10. 24 attr_reader :encodings
  11. # initialized with the corresponding HTTPX::Response +response+ and HTTPX::Options +options+.
  12. 24 def initialize(response, options)
  13. 7454 @response = response
  14. 7454 @headers = response.headers
  15. 7454 @options = options
  16. 7454 @window_size = options.window_size
  17. 7454 @encodings = []
  18. 7454 @length = 0
  19. 7454 @buffer = nil
  20. 7454 @reader = nil
  21. 7454 @state = :idle
  22. # initialize response encoding
  23. 7454 @encoding = if (enc = response.content_type.charset)
  24. 161 begin
  25. 1267 Encoding.find(enc)
  26. rescue ArgumentError
  27. 28 Encoding::BINARY
  28. end
  29. else
  30. 6187 Encoding::BINARY
  31. end
  32. 7454 initialize_inflaters
  33. end
  34. 24 def initialize_dup(other)
  35. 28 super
  36. 28 @buffer = other.instance_variable_get(:@buffer).dup
  37. end
  38. 24 def closed?
  39. 259 @state == :closed
  40. end
  41. # write the response payload +chunk+ into the buffer. Inflates the chunk when required
  42. # and supported.
  43. 24 def write(chunk)
  44. 9716 return if @state == :closed
  45. 9716 return 0 if chunk.empty?
  46. 9362 chunk = decode_chunk(chunk)
  47. 9362 size = chunk.bytesize
  48. 8179 @length += size
  49. 9362 transition(:open)
  50. 9362 @buffer.write(chunk)
  51. 9362 @response.emit(:chunk_received, chunk)
  52. 9348 size
  53. end
  54. # reads a chunk from the payload (implementation of the IO reader protocol).
  55. 24 def read(*args)
  56. 147 return unless @buffer
  57. 147 unless @reader
  58. 94 rewind
  59. 94 @reader = @buffer
  60. end
  61. 147 @reader.read(*args)
  62. end
  63. # size of the decoded response payload. May differ from "content-length" header if
  64. # response was encoded over-the-wire.
  65. 24 def bytesize
  66. 151 @length
  67. end
  68. # yields the payload in chunks.
  69. 24 def each
  70. 56 return enum_for(__method__) unless block_given?
  71. 5 begin
  72. 42 if @buffer
  73. 42 rewind
  74. 108 while (chunk = @buffer.read(@window_size))
  75. 42 yield(chunk.force_encoding(@encoding))
  76. end
  77. end
  78. ensure
  79. 42 close
  80. end
  81. end
  82. # returns the declared filename in the "contennt-disposition" header, when present.
  83. 24 def filename
  84. 42 return unless @headers.key?("content-disposition")
  85. 35 Utils.get_filename(@headers["content-disposition"])
  86. end
  87. # returns the full response payload as a string.
  88. 24 def to_s
  89. 3765 return "".b unless @buffer
  90. 3497 @buffer.to_s
  91. end
  92. 24 alias_method :to_str, :to_s
  93. # whether the payload is empty.
  94. 24 def empty?
  95. 28 @length.zero?
  96. end
  97. # copies the payload to +dest+.
  98. #
  99. # body.copy_to("path/to/file")
  100. # body.copy_to(Pathname.new("path/to/file"))
  101. # body.copy_to(File.new("path/to/file"))
  102. 24 def copy_to(dest)
  103. 42 return unless @buffer
  104. 42 rewind
  105. 42 if dest.respond_to?(:path) && @buffer.respond_to?(:path)
  106. 7 FileUtils.mv(@buffer.path, dest.path)
  107. else
  108. 35 ::IO.copy_stream(@buffer, dest)
  109. end
  110. end
  111. # closes/cleans the buffer, resets everything
  112. 24 def close
  113. 491 if @buffer
  114. 351 @buffer.close
  115. 351 @buffer = nil
  116. end
  117. 491 @length = 0
  118. 491 transition(:closed)
  119. end
  120. 24 def ==(other)
  121. 103 object_id == other.object_id || begin
  122. 103 if other.respond_to?(:read)
  123. 70 _with_same_buffer_pos { FileUtils.compare_stream(@buffer, other) }
  124. else
  125. 68 to_s == other.to_s
  126. end
  127. end
  128. end
  129. skipped # :nocov:
  130. skipped def inspect
  131. skipped "#<HTTPX::Response::Body:#{object_id} " \
  132. skipped "@state=#{@state} " \
  133. skipped "@length=#{@length}>"
  134. skipped end
  135. skipped # :nocov:
  136. # rewinds the response payload buffer.
  137. 24 def rewind
  138. 327 return unless @buffer
  139. # in case there's some reading going on
  140. 327 @reader = nil
  141. 327 @buffer.rewind
  142. end
  143. 24 private
  144. # prepares inflaters for the advertised encodings in "content-encoding" header.
  145. 24 def initialize_inflaters
  146. 7454 @inflaters = nil
  147. 7454 return unless @headers.key?("content-encoding")
  148. 149 return unless @options.decompress_response_body
  149. 135 @inflaters = @headers.get("content-encoding").filter_map do |encoding|
  150. 135 next if encoding == "identity"
  151. 135 inflater = self.class.initialize_inflater_by_encoding(encoding, @response)
  152. # do not uncompress if there is no decoder available. In fact, we can't reliably
  153. # continue decompressing beyond that, so ignore.
  154. 135 break unless inflater
  155. 135 @encodings << encoding
  156. 135 inflater
  157. end
  158. end
  159. # passes the +chunk+ through all inflaters to decode it.
  160. 24 def decode_chunk(chunk)
  161. 35 @inflaters.reverse_each do |inflater|
  162. 371 chunk = inflater.call(chunk)
  163. 9489 end if @inflaters
  164. 9490 chunk
  165. end
  166. # tries transitioning the body STM to the +nextstate+.
  167. 24 def transition(nextstate)
  168. 8611 case nextstate
  169. when :open
  170. 9362 return unless @state == :idle
  171. 5713 @buffer = Response::Buffer.new(
  172. threshold_size: @options.body_threshold_size,
  173. bytesize: @length,
  174. encoding: @encoding
  175. )
  176. when :closed
  177. 491 return if @state == :closed
  178. end
  179. 6204 @state = nextstate
  180. end
  181. 24 def _with_same_buffer_pos # :nodoc:
  182. 35 return yield unless @buffer && @buffer.respond_to?(:pos)
  183. # @type ivar @buffer: StringIO | Tempfile
  184. 35 current_pos = @buffer.pos
  185. 35 @buffer.rewind
  186. 4 begin
  187. 35 yield
  188. ensure
  189. 35 @buffer.pos = current_pos
  190. end
  191. end
  192. 24 class << self
  193. 24 def initialize_inflater_by_encoding(encoding, response, **kwargs) # :nodoc:
  194. 120 case encoding
  195. when "gzip"
  196. 121 Transcoder::GZIP.decode(response, **kwargs)
  197. when "deflate"
  198. 14 Transcoder::Deflate.decode(response, **kwargs)
  199. end
  200. end
  201. end
  202. end
  203. end

lib/httpx/response/buffer.rb

96.0% lines covered

50 relevant lines. 48 lines covered and 2 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "delegate"
  3. 24 require "stringio"
  4. 24 require "tempfile"
  5. 24 module HTTPX
  6. # wraps and delegates to an internal buffer, which can be a StringIO or a Tempfile.
  7. 24 class Response::Buffer < SimpleDelegator
  8. # initializes buffer with the +threshold_size+ over which the payload gets buffer to a tempfile,
  9. # the initial +bytesize+, and the +encoding+.
  10. 24 def initialize(threshold_size:, bytesize: 0, encoding: Encoding::BINARY)
  11. 5771 @threshold_size = threshold_size
  12. 5771 @bytesize = bytesize
  13. 5771 @encoding = encoding
  14. 5771 @buffer = StringIO.new("".b)
  15. 5771 super(@buffer)
  16. end
  17. 24 def initialize_dup(other)
  18. 28 super
  19. 28 @buffer = other.instance_variable_get(:@buffer).dup
  20. end
  21. # size in bytes of the buffered content.
  22. 24 def size
  23. 222 @bytesize
  24. end
  25. # writes the +chunk+ into the buffer.
  26. 24 def write(chunk)
  27. 8275 @bytesize += chunk.bytesize
  28. 9466 try_upgrade_buffer
  29. 9466 @buffer.write(chunk)
  30. end
  31. # returns the buffered content as a string.
  32. 24 def to_s
  33. 3027 case @buffer
  34. when StringIO
  35. 451 begin
  36. 3427 @buffer.string.force_encoding(@encoding)
  37. rescue ArgumentError
  38. @buffer.string
  39. end
  40. when Tempfile
  41. 70 rewind
  42. 140 content = _with_same_buffer_pos { @buffer.read }
  43. 9 begin
  44. 70 content.force_encoding(@encoding)
  45. rescue ArgumentError # ex: unknown encoding name - utf
  46. content
  47. end
  48. end
  49. end
  50. # closes the buffer.
  51. 24 def close
  52. 351 @buffer.close
  53. 351 @buffer.unlink if @buffer.respond_to?(:unlink)
  54. end
  55. 24 private
  56. # initializes the buffer into a StringIO, or turns it into a Tempfile when the threshold
  57. # has been reached.
  58. 24 def try_upgrade_buffer
  59. 9466 return unless @bytesize > @threshold_size
  60. 353 return if @buffer.is_a?(Tempfile)
  61. 115 aux = @buffer
  62. 115 @buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
  63. 115 if aux
  64. 115 aux.rewind
  65. 115 ::IO.copy_stream(aux, @buffer)
  66. 115 aux.close
  67. end
  68. 115 __setobj__(@buffer)
  69. end
  70. 24 def _with_same_buffer_pos # :nodoc:
  71. 70 current_pos = @buffer.pos
  72. 70 @buffer.rewind
  73. 9 begin
  74. 70 yield
  75. ensure
  76. 70 @buffer.pos = current_pos
  77. end
  78. end
  79. end
  80. end

lib/httpx/selector.rb

86.76% lines covered

68 relevant lines. 59 lines covered and 9 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "io/wait"
  3. 24 class HTTPX::Selector
  4. 24 READABLE = %i[rw r].freeze
  5. 24 WRITABLE = %i[rw w].freeze
  6. 24 private_constant :READABLE
  7. 24 private_constant :WRITABLE
  8. 24 def initialize
  9. 548 @selectables = []
  10. end
  11. # deregisters +io+ from selectables.
  12. 24 def deregister(io)
  13. 12683 @selectables.delete(io)
  14. end
  15. # register +io+.
  16. 24 def register(io)
  17. 7131 return if @selectables.include?(io)
  18. 6907 @selectables << io
  19. end
  20. 24 private
  21. 24 def select_many(interval, &block)
  22. 2026 selectables, r, w = nil
  23. # first, we group IOs based on interest type. On call to #interests however,
  24. # things might already happen, and new IOs might be registered, so we might
  25. # have to start all over again. We do this until we group all selectables
  26. 231 begin
  27. 2026 loop do
  28. 231 begin
  29. 2026 r = nil
  30. 2026 w = nil
  31. 2026 selectables = @selectables
  32. 2026 @selectables = []
  33. 2026 selectables.delete_if do |io|
  34. 7612 interests = io.interests
  35. 7612 (r ||= []) << io if READABLE.include?(interests)
  36. 7612 (w ||= []) << io if WRITABLE.include?(interests)
  37. 7612 io.state == :closed
  38. end
  39. 2026 if @selectables.empty?
  40. 2026 @selectables = selectables
  41. # do not run event loop if there's nothing to wait on.
  42. # this might happen if connect failed and connection was unregistered.
  43. 2026 return if (!r || r.empty?) && (!w || w.empty?) && !selectables.empty?
  44. 2003 break
  45. else
  46. @selectables.concat(selectables)
  47. end
  48. rescue StandardError
  49. @selectables = selectables if selectables
  50. raise
  51. end
  52. end
  53. # TODO: what to do if there are no selectables?
  54. 2003 readers, writers = IO.select(r, w, nil, interval)
  55. 2003 if readers.nil? && writers.nil? && interval
  56. 188 [*r, *w].each { |io| io.handle_socket_timeout(interval) }
  57. 145 return
  58. end
  59. rescue IOError, SystemCallError
  60. @selectables.reject!(&:closed?)
  61. retry
  62. end
  63. 1858 if writers
  64. 162 readers.each do |io|
  65. 992 yield io
  66. # so that we don't yield 2 times
  67. 991 writers.delete(io)
  68. 1857 end if readers
  69. 1857 writers.each(&block)
  70. else
  71. readers.each(&block) if readers
  72. end
  73. end
  74. 24 def select_one(interval)
  75. 2227227 io = @selectables.first
  76. 2227227 return unless io
  77. 2227227 interests = io.interests
  78. 2227227 result = case interests
  79. 9394 when :r then io.to_io.wait_readable(interval)
  80. 7109 when :w then io.to_io.wait_writable(interval)
  81. when :rw then io.to_io.wait(interval, :read_write)
  82. 2210724 when nil then return
  83. end
  84. 16503 unless result || interval.nil?
  85. 427 io.handle_socket_timeout(interval)
  86. 422 return
  87. end
  88. # raise HTTPX::TimeoutError.new(interval, "timed out while waiting on select")
  89. 16076 yield io
  90. rescue IOError, SystemCallError
  91. @selectables.reject!(&:closed?)
  92. raise unless @selectables.empty?
  93. end
  94. 24 def select(interval, &block)
  95. # do not cause an infinite loop here.
  96. #
  97. # this may happen if timeout calculation actually triggered an error which causes
  98. # the connections to be reaped (such as the total timeout error) before #select
  99. # gets called.
  100. 2229253 return if interval.nil? && @selectables.empty?
  101. 2229253 return select_one(interval, &block) if @selectables.size == 1
  102. 2026 select_many(interval, &block)
  103. end
  104. 24 public :select
  105. end

lib/httpx/session.rb

94.94% lines covered

178 relevant lines. 169 lines covered and 9 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 EMPTY_HASH = {}.freeze
  4. # Class implementing the APIs being used publicly.
  5. #
  6. # HTTPX.get(..) #=> delegating to an internal HTTPX::Session object.
  7. # HTTPX.plugin(..).get(..) #=> creating an intermediate HTTPX::Session with plugin, then sending the GET request
  8. 24 class Session
  9. 24 include Loggable
  10. 24 include Chainable
  11. # initializes the session with a set of +options+, which will be shared by all
  12. # requests sent from it.
  13. #
  14. # When pass a block, it'll yield itself to it, then closes after the block is evaluated.
  15. 24 def initialize(options = EMPTY_HASH, &blk)
  16. 8618 @options = self.class.default_options.merge(options)
  17. 8618 @responses = {}
  18. 8618 @persistent = @options.persistent
  19. 8618 wrap(&blk) if blk
  20. end
  21. # Yields itself the block, then closes it after the block is evaluated.
  22. #
  23. # session.wrap do |http|
  24. # http.get("https://wikipedia.com")
  25. # end # wikipedia connection closes here
  26. 24 def wrap
  27. 425 prev_persistent = @persistent
  28. 425 @persistent = true
  29. 425 pool.wrap do
  30. 46 begin
  31. 425 yield self
  32. ensure
  33. 425 @persistent = prev_persistent
  34. 425 close unless @persistent
  35. end
  36. end
  37. end
  38. # closes all the active connections from the session
  39. 24 def close(*args)
  40. 5598 pool.close(*args)
  41. end
  42. # performs one, or multple requests; it accepts:
  43. #
  44. # 1. one or multiple HTTPX::Request objects;
  45. # 2. an HTTP verb, then a sequence of URIs or URI/options tuples;
  46. # 3. one or multiple HTTP verb / uri / (optional) options tuples;
  47. #
  48. # when present, the set of +options+ kwargs is applied to all of the
  49. # sent requests.
  50. #
  51. # respectively returns a single HTTPX::Response response, or all of them in an Array, in the same order.
  52. #
  53. # resp1 = session.request(req1)
  54. # resp1, resp2 = session.request(req1, req2)
  55. # resp1 = session.request("GET", "https://server.org/a")
  56. # resp1, resp2 = session.request("GET", ["https://server.org/a", "https://server.org/b"])
  57. # resp1, resp2 = session.request(["GET", "https://server.org/a"], ["GET", "https://server.org/b"])
  58. # resp1 = session.request("POST", "https://server.org/a", form: { "foo" => "bar" })
  59. # resp1, resp2 = session.request(["POST", "https://server.org/a", form: { "foo" => "bar" }], ["GET", "https://server.org/b"])
  60. # resp1, resp2 = session.request("GET", ["https://server.org/a", "https://server.org/b"], headers: { "x-api-token" => "TOKEN" })
  61. #
  62. 24 def request(*args, **params)
  63. 5837 raise ArgumentError, "must perform at least one request" if args.empty?
  64. 5837 requests = args.first.is_a?(Request) ? args : build_requests(*args, params)
  65. 5816 responses = send_requests(*requests)
  66. 5692 return responses.first if responses.size == 1
  67. 167 responses
  68. end
  69. # returns a HTTP::Request instance built from the HTTP +verb+, the request +uri+, and
  70. # the optional set of request-specific +options+. This request **must** be sent through
  71. # the same session it was built from.
  72. #
  73. # req = session.build_request("GET", "https://server.com")
  74. # resp = session.request(req)
  75. 24 def build_request(verb, uri, params = EMPTY_HASH, options = @options)
  76. 7052 rklass = options.request_class
  77. 7052 request = rklass.new(verb, uri, options, params)
  78. 7031 request.persistent = @persistent
  79. 7031 set_request_callbacks(request)
  80. 7031 request
  81. end
  82. 24 private
  83. # returns the HTTPX::Pool object which manages the networking required to
  84. # perform requests.
  85. 24 def pool
  86. 2240687 Thread.current[:httpx_connection_pool] ||= Pool.new
  87. end
  88. # callback executed when a response for a given request has been received.
  89. 24 def on_response(request, response)
  90. 6449 @responses[request] = response
  91. end
  92. # callback executed when an HTTP/2 promise frame has been received.
  93. 24 def on_promise(_, stream)
  94. 7 log(level: 2) { "#{stream.id}: refusing stream!" }
  95. 7 stream.refuse
  96. end
  97. # returns the corresponding HTTP::Response to the given +request+ if it has been received.
  98. 24 def fetch_response(request, _, _)
  99. 2235453 @responses.delete(request)
  100. end
  101. # returns the HTTPX::Connection through which the +request+ should be sent through.
  102. 24 def find_connection(request, connections, options)
  103. 7046 uri = request.uri
  104. 7046 connection = pool.find_connection(uri, options) || init_connection(uri, options)
  105. 6988 unless connections.nil? || connections.include?(connection)
  106. 5618 connections << connection
  107. 5618 set_connection_callbacks(connection, connections, options)
  108. end
  109. 6988 connection
  110. end
  111. # sends the +request+ to the corresponding HTTPX::Connection
  112. 24 def send_request(request, connections, options = request.options)
  113. 7367 error = catch(:resolve_error) do
  114. 7367 connection = find_connection(request, connections, options)
  115. 7288 connection.send(request)
  116. end
  117. 7341 return unless error.is_a?(Error)
  118. 58 request.emit(:response, ErrorResponse.new(request, error))
  119. end
  120. # sets the callbacks on the +connection+ required to process certain specific
  121. # connection lifecycle events which deal with request rerouting.
  122. 24 def set_connection_callbacks(connection, connections, options, cloned: false)
  123. 5952 connection.only(:misdirected) do |misdirected_request|
  124. 7 other_connection = connection.create_idle(ssl: { alpn_protocols: %w[http/1.1] })
  125. 7 other_connection.merge(connection)
  126. 7 catch(:coalesced) do
  127. 7 pool.init_connection(other_connection, options)
  128. end
  129. 7 set_connection_callbacks(other_connection, connections, options)
  130. 7 connections << other_connection
  131. 7 misdirected_request.transition(:idle)
  132. 7 other_connection.send(misdirected_request)
  133. end
  134. 5952 connection.only(:altsvc) do |alt_origin, origin, alt_params|
  135. 7 other_connection = build_altsvc_connection(connection, connections, alt_origin, origin, alt_params, options)
  136. 7 connections << other_connection if other_connection
  137. end
  138. 5200 connection.only(:cloned) do |cloned_conn|
  139. set_connection_callbacks(cloned_conn, connections, options, cloned: true)
  140. connections << cloned_conn
  141. 5951 end unless cloned
  142. end
  143. # returns an HTTPX::Connection for the negotiated Alternative Service (or none).
  144. 24 def build_altsvc_connection(existing_connection, connections, alt_origin, origin, alt_params, options)
  145. # do not allow security downgrades on altsvc negotiation
  146. 7 return if existing_connection.origin.scheme == "https" && alt_origin.scheme != "https"
  147. 7 altsvc = AltSvc.cached_altsvc_set(origin, alt_params.merge("origin" => alt_origin))
  148. # altsvc already exists, somehow it wasn't advertised, probably noop
  149. 7 return unless altsvc
  150. 7 alt_options = options.merge(ssl: options.ssl.merge(hostname: URI(origin).host))
  151. 7 connection = pool.find_connection(alt_origin, alt_options) || init_connection(alt_origin, alt_options)
  152. # advertised altsvc is the same origin being used, ignore
  153. 7 return if connection == existing_connection
  154. 7 connection.extend(AltSvc::ConnectionMixin) unless connection.is_a?(AltSvc::ConnectionMixin)
  155. 7 set_connection_callbacks(connection, connections, alt_options)
  156. 7 log(level: 1) { "#{origin} alt-svc: #{alt_origin}" }
  157. 7 connection.merge(existing_connection)
  158. 7 existing_connection.terminate
  159. 7 connection
  160. rescue UnsupportedSchemeError
  161. altsvc["noop"] = true
  162. nil
  163. end
  164. # returns a set of HTTPX::Request objects built from the given +args+ and +options+.
  165. 24 def build_requests(*args, params)
  166. 5404 requests = if args.size == 1
  167. 68 reqs = args.first
  168. # TODO: find a way to make requests share same options object
  169. 68 reqs.map do |verb, uri, ps = EMPTY_HASH|
  170. 136 request_params = params
  171. 136 request_params = request_params.merge(ps) unless ps.empty?
  172. 136 build_request(verb, uri, request_params)
  173. end
  174. else
  175. 5336 verb, uris = args
  176. 5336 if uris.respond_to?(:each)
  177. # TODO: find a way to make requests share same options object
  178. 5126 uris.enum_for(:each).map do |uri, ps = EMPTY_HASH|
  179. 5850 request_params = params
  180. 5850 request_params = request_params.merge(ps) unless ps.empty?
  181. 5850 build_request(verb, uri, request_params)
  182. end
  183. else
  184. 210 [build_request(verb, uris, params)]
  185. end
  186. end
  187. 5383 raise ArgumentError, "wrong number of URIs (given 0, expect 1..+1)" if requests.empty?
  188. 5383 requests
  189. end
  190. 24 def set_request_callbacks(request)
  191. 7031 request.on(:response, &method(:on_response).curry(2)[request])
  192. 7031 request.on(:promise, &method(:on_promise))
  193. end
  194. 24 def init_connection(uri, options)
  195. 5894 connection = options.connection_class.new(uri, options)
  196. 5880 catch(:coalesced) do
  197. 5880 pool.init_connection(connection, options)
  198. 5831 connection
  199. end
  200. end
  201. 24 def deactivate_connection(request, connections, options)
  202. 109 conn = connections.find do |c|
  203. 109 c.match?(request.uri, options)
  204. end
  205. 109 pool.deactivate(conn) if conn
  206. end
  207. # sends an array of HTTPX::Request +requests+, returns the respective array of HTTPX::Response objects.
  208. 24 def send_requests(*requests)
  209. 5902 connections = _send_requests(requests)
  210. 5876 receive_requests(requests, connections)
  211. end
  212. # sends an array of HTTPX::Request objects
  213. 24 def _send_requests(requests)
  214. 5902 connections = []
  215. 5902 requests.each do |request|
  216. 6681 send_request(request, connections)
  217. end
  218. 5876 connections
  219. end
  220. # returns the array of HTTPX::Response objects corresponding to the array of HTTPX::Request +requests+.
  221. 24 def receive_requests(requests, connections)
  222. # @type var responses: Array[response]
  223. 5876 responses = []
  224. 741 begin
  225. # guarantee ordered responses
  226. 5876 loop do
  227. 6662 request = requests.first
  228. 6662 return responses unless request
  229. 3363603 catch(:coalesced) { pool.next_tick } until (response = fetch_response(request, connections, request.options))
  230. 6564 request.emit(:complete, response)
  231. 6564 responses << response
  232. 6564 requests.shift
  233. 6564 break if requests.empty?
  234. 786 next unless pool.empty?
  235. # in some cases, the pool of connections might have been drained because there was some
  236. # handshake error, and the error responses have already been emitted, but there was no
  237. # opportunity to traverse the requests, hence we're returning only a fraction of the errors
  238. # we were supposed to. This effectively fetches the existing responses and return them.
  239. while (request = requests.shift)
  240. response = fetch_response(request, connections, request.options)
  241. request.emit(:complete, response) if response
  242. responses << response
  243. end
  244. break
  245. end
  246. 5778 responses
  247. ensure
  248. 5876 if @persistent
  249. 869 pool.deactivate(*connections)
  250. else
  251. 5007 close(connections)
  252. end
  253. end
  254. end
  255. 24 @default_options = Options.new
  256. 24 @default_options.freeze
  257. 24 @plugins = []
  258. 24 class << self
  259. 24 attr_reader :default_options
  260. 24 def inherited(klass)
  261. 4243 super
  262. 4243 klass.instance_variable_set(:@default_options, @default_options)
  263. 4243 klass.instance_variable_set(:@plugins, @plugins.dup)
  264. 4243 klass.instance_variable_set(:@callbacks, @callbacks.dup)
  265. end
  266. # returns a new HTTPX::Session instance, with the plugin pointed by +pl+ loaded.
  267. #
  268. # session_with_retries = session.plugin(:retries)
  269. # session_with_custom = session.plugin(CustomPlugin)
  270. #
  271. 24 def plugin(pl, options = nil, &block)
  272. # raise Error, "Cannot add a plugin to a frozen config" if frozen?
  273. 5781 pl = Plugins.load_plugin(pl) if pl.is_a?(Symbol)
  274. 5781 if !@plugins.include?(pl)
  275. 5588 @plugins << pl
  276. 5588 pl.load_dependencies(self, &block) if pl.respond_to?(:load_dependencies)
  277. 5588 @default_options = @default_options.dup
  278. 5588 include(pl::InstanceMethods) if defined?(pl::InstanceMethods)
  279. 5588 extend(pl::ClassMethods) if defined?(pl::ClassMethods)
  280. 5588 opts = @default_options
  281. 5588 opts.extend_with_plugin_classes(pl)
  282. 5588 if defined?(pl::OptionsMethods)
  283. 2204 (pl::OptionsMethods.instance_methods - Object.instance_methods).each do |meth|
  284. 6414 opts.options_class.method_added(meth)
  285. end
  286. 2204 @default_options = opts.options_class.new(opts)
  287. end
  288. 5588 @default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
  289. 5588 @default_options = @default_options.merge(options) if options
  290. 5588 pl.configure(self, &block) if pl.respond_to?(:configure)
  291. 5588 @default_options.freeze
  292. 192 elsif options
  293. # this can happen when two plugins are loaded, an one of them calls the other under the hood,
  294. # albeit changing some default.
  295. 14 @default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
  296. 14 @default_options = @default_options.merge(options) if options
  297. 14 @default_options.freeze
  298. end
  299. 5781 self
  300. end
  301. end
  302. end
  303. # session may be overridden by certain adapters.
  304. 24 S = Session
  305. end

lib/httpx/session_extensions.rb

100.0% lines covered

14 relevant lines. 14 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 unless ENV.keys.grep(/\Ahttps?_proxy\z/i).empty?
  4. 1 proxy_session = plugin(:proxy)
  5. 1 remove_const(:Session)
  6. 1 const_set(:Session, proxy_session.class)
  7. # redefine the default options static var, which needs to
  8. # refresh options_class
  9. 1 options = proxy_session.class.default_options.to_hash
  10. 1 original_verbosity = $VERBOSE
  11. 1 $VERBOSE = nil
  12. 1 const_set(:Options, proxy_session.class.default_options.options_class)
  13. 1 options[:options_class] = Class.new(options[:options_class])
  14. 1 options.freeze
  15. 1 Options.send(:const_set, :DEFAULT_OPTIONS, options)
  16. 1 Session.instance_variable_set(:@default_options, Options.new(options))
  17. 1 $VERBOSE = original_verbosity
  18. end
  19. skipped # :nocov:
  20. skipped if Session.default_options.debug_level > 2
  21. skipped proxy_session = plugin(:internal_telemetry)
  22. skipped remove_const(:Session)
  23. skipped const_set(:Session, proxy_session.class)
  24. skipped end
  25. skipped # :nocov:
  26. end

lib/httpx/timers.rb

100.0% lines covered

57 relevant lines. 57 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 class Timers
  4. 24 def initialize
  5. 548 @intervals = []
  6. end
  7. 24 def after(interval_in_secs, cb = nil, &blk)
  8. 34587 return unless interval_in_secs
  9. 34587 callback = cb || blk
  10. # I'm assuming here that most requests will have the same
  11. # request timeout, as in most cases they share common set of
  12. # options. A user setting different request timeouts for 100s of
  13. # requests will already have a hard time dealing with that.
  14. 63196 unless (interval = @intervals.find { |t| t.interval == interval_in_secs })
  15. 7120 interval = Interval.new(interval_in_secs)
  16. 13949 interval.on_empty { @intervals.delete(interval) }
  17. 7120 @intervals << interval
  18. 7120 @intervals.sort!
  19. end
  20. 34587 interval << callback
  21. 34587 @next_interval_at = nil
  22. 34587 interval
  23. end
  24. 24 def wait_interval
  25. 2229253 return if @intervals.empty?
  26. 2215117 @next_interval_at = Utils.now
  27. 2215117 @intervals.first.interval
  28. end
  29. 24 def fire(error = nil)
  30. 2229143 raise error if error && error.timeout != @intervals.first
  31. 2229138 return if @intervals.empty? || !@next_interval_at
  32. 2210032 elapsed_time = Utils.elapsed_time(@next_interval_at)
  33. 4420076 @intervals = @intervals.drop_while { |interval| interval.elapse(elapsed_time) <= 0 }
  34. 2210032 @next_interval_at = nil if @intervals.empty?
  35. end
  36. 24 class Interval
  37. 24 include Comparable
  38. 24 attr_reader :interval
  39. 24 def initialize(interval)
  40. 7120 @interval = interval
  41. 7120 @callbacks = []
  42. 7120 @on_empty = nil
  43. end
  44. 24 def on_empty(&blk)
  45. 7120 @on_empty = blk
  46. end
  47. 24 def <=>(other)
  48. 653 @interval <=> other.interval
  49. end
  50. 24 def ==(other)
  51. 2141 return @interval == other if other.is_a?(Numeric)
  52. 2141 @interval == other.to_f # rubocop:disable Lint/FloatComparison
  53. end
  54. 24 def to_f
  55. 2141 Float(@interval)
  56. end
  57. 24 def <<(callback)
  58. 34587 @callbacks << callback
  59. end
  60. 24 def delete(callback)
  61. 51064 @callbacks.delete(callback)
  62. 51064 @on_empty.call if @callbacks.empty?
  63. end
  64. 24 def no_callbacks?
  65. 51064 @callbacks.empty?
  66. end
  67. 24 def elapsed?
  68. 1087 @interval <= 0
  69. end
  70. 24 def elapse(elapsed)
  71. 1083138 @interval -= elapsed
  72. 2210044 if @interval <= 0
  73. 481 cb = @callbacks.dup
  74. 481 cb.each(&:call)
  75. end
  76. 2210044 @interval
  77. end
  78. end
  79. 24 private_constant :Interval
  80. end
  81. end

lib/httpx/transcoder.rb

100.0% lines covered

53 relevant lines. 53 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 module Transcoder
  4. 24 module_function
  5. 24 def normalize_keys(key, value, cond = nil, &block)
  6. 2957 if cond && cond.call(value)
  7. 931 block.call(key.to_s, value)
  8. 2025 elsif value.respond_to?(:to_ary)
  9. 397 if value.empty?
  10. 112 block.call("#{key}[]")
  11. else
  12. 285 value.to_ary.each do |element|
  13. 458 normalize_keys("#{key}[]", element, cond, &block)
  14. end
  15. end
  16. 1628 elsif value.respond_to?(:to_hash)
  17. 448 value.to_hash.each do |child_key, child_value|
  18. 448 normalize_keys("#{key}[#{child_key}]", child_value, cond, &block)
  19. end
  20. else
  21. 1181 block.call(key.to_s, value)
  22. end
  23. end
  24. # based on https://github.com/rack/rack/blob/d15dd728440710cfc35ed155d66a98dc2c07ae42/lib/rack/query_parser.rb#L82
  25. 24 def normalize_query(params, name, v, depth)
  26. 161 raise Error, "params depth surpasses what's supported" if depth <= 0
  27. 161 name =~ /\A[\[\]]*([^\[\]]+)\]*/
  28. 161 k = Regexp.last_match(1) || ""
  29. 161 after = Regexp.last_match ? Regexp.last_match.post_match : ""
  30. 161 if k.empty?
  31. 14 return Array(v) if !v.empty? && name == "[]"
  32. 6 return
  33. end
  34. 126 case after
  35. when ""
  36. 42 params[k] = v
  37. when "["
  38. 6 params[name] = v
  39. when "[]"
  40. 14 params[k] ||= []
  41. 14 raise Error, "expected Array (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Array)
  42. 14 params[k] << v
  43. when /^\[\]\[([^\[\]]+)\]$/, /^\[\](.+)$/
  44. 28 child_key = Regexp.last_match(1)
  45. 28 params[k] ||= []
  46. 28 raise Error, "expected Array (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Array)
  47. 28 if params[k].last.is_a?(Hash) && !params_hash_has_key?(params[k].last, child_key)
  48. 7 normalize_query(params[k].last, child_key, v, depth - 1)
  49. else
  50. 21 params[k] << normalize_query({}, child_key, v, depth - 1)
  51. end
  52. else
  53. 49 params[k] ||= {}
  54. 49 raise Error, "expected Hash (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Hash)
  55. 42 params[k] = normalize_query(params[k], after, v, depth - 1)
  56. end
  57. 147 params
  58. end
  59. 24 def params_hash_has_key?(hash, key)
  60. 14 return false if key.include?("[]")
  61. 14 key.split(/[\[\]]+/).inject(hash) do |h, part|
  62. 14 next h if part == ""
  63. 14 return false unless h.is_a?(Hash) && h.key?(part)
  64. 7 h[part]
  65. end
  66. 7 true
  67. end
  68. end
  69. end
  70. 24 require "httpx/transcoder/body"
  71. 24 require "httpx/transcoder/form"
  72. 24 require "httpx/transcoder/json"
  73. 24 require "httpx/transcoder/xml"
  74. 24 require "httpx/transcoder/chunker"
  75. 24 require "httpx/transcoder/deflate"
  76. 24 require "httpx/transcoder/gzip"

lib/httpx/transcoder/body.rb

100.0% lines covered

33 relevant lines. 33 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "forwardable"
  3. 24 module HTTPX::Transcoder
  4. 24 module Body
  5. 24 class Error < HTTPX::Error; end
  6. 24 module_function
  7. 24 class Encoder
  8. 24 extend Forwardable
  9. 24 def_delegator :@raw, :to_s
  10. 24 def_delegator :@raw, :==
  11. 24 def initialize(body)
  12. 1043 @raw = body
  13. end
  14. 24 def bytesize
  15. 4017 if @raw.respond_to?(:bytesize)
  16. 2152 @raw.bytesize
  17. 1864 elsif @raw.respond_to?(:to_ary)
  18. 778 @raw.sum(&:bytesize)
  19. 1086 elsif @raw.respond_to?(:size)
  20. 604 @raw.size || Float::INFINITY
  21. 482 elsif @raw.respond_to?(:length)
  22. 224 @raw.length || Float::INFINITY
  23. 258 elsif @raw.respond_to?(:each)
  24. 252 Float::INFINITY
  25. else
  26. 7 raise Error, "cannot determine size of body: #{@raw.inspect}"
  27. end
  28. end
  29. 24 def content_type
  30. 1001 "application/octet-stream"
  31. end
  32. 24 private
  33. 24 def respond_to_missing?(meth, *args)
  34. 4497 @raw.respond_to?(meth, *args) || super
  35. end
  36. 24 def method_missing(meth, *args, &block)
  37. 893 return super unless @raw.respond_to?(meth)
  38. 893 @raw.__send__(meth, *args, &block)
  39. end
  40. end
  41. 24 def encode(body)
  42. 1043 Encoder.new(body)
  43. end
  44. end
  45. end

lib/httpx/transcoder/chunker.rb

100.0% lines covered

66 relevant lines. 66 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "forwardable"
  3. 24 module HTTPX::Transcoder
  4. 24 module Chunker
  5. 24 class Error < HTTPX::Error; end
  6. 24 CRLF = "\r\n".b
  7. 24 class Encoder
  8. 24 extend Forwardable
  9. 24 def initialize(body)
  10. 84 @raw = body
  11. end
  12. 24 def each
  13. 84 return enum_for(__method__) unless block_given?
  14. 84 @raw.each do |chunk|
  15. 392 yield "#{chunk.bytesize.to_s(16)}#{CRLF}#{chunk}#{CRLF}"
  16. end
  17. 84 yield "0#{CRLF}"
  18. end
  19. 24 def respond_to_missing?(meth, *args)
  20. 132 @raw.respond_to?(meth, *args) || super
  21. end
  22. end
  23. 24 class Decoder
  24. 24 extend Forwardable
  25. 24 def_delegator :@buffer, :empty?
  26. 24 def_delegator :@buffer, :<<
  27. 24 def_delegator :@buffer, :clear
  28. 24 def initialize(buffer, trailers = false)
  29. 100 @buffer = buffer
  30. 100 @chunk_buffer = "".b
  31. 100 @finished = false
  32. 100 @state = :length
  33. 100 @trailers = trailers
  34. end
  35. 24 def to_s
  36. 93 @buffer
  37. end
  38. 24 def each
  39. 170 loop do
  40. 894 case @state
  41. when :length
  42. 298 index = @buffer.index(CRLF)
  43. 298 return unless index && index.positive?
  44. # Read hex-length
  45. 298 hexlen = @buffer.byteslice(0, index)
  46. 298 @buffer = @buffer.byteslice(index..-1) || "".b
  47. 298 hexlen[/\h/] || raise(Error, "wrong chunk size line: #{hexlen}")
  48. 298 @chunk_length = hexlen.hex
  49. # check if is last chunk
  50. 298 @finished = @chunk_length.zero?
  51. 298 nextstate(:crlf)
  52. when :crlf
  53. 496 crlf_size = @finished && !@trailers ? 4 : 2
  54. # consume CRLF
  55. 496 return if @buffer.bytesize < crlf_size
  56. 496 raise Error, "wrong chunked encoding format" unless @buffer.start_with?(CRLF * (crlf_size / 2))
  57. 496 @buffer = @buffer.byteslice(crlf_size..-1)
  58. 496 if @chunk_length.nil?
  59. 198 nextstate(:length)
  60. else
  61. 298 return if @finished
  62. 205 nextstate(:data)
  63. end
  64. when :data
  65. 247 chunk = @buffer.byteslice(0, @chunk_length)
  66. 247 @buffer = @buffer.byteslice(@chunk_length..-1) || "".b
  67. 247 @chunk_buffer << chunk
  68. 212 @chunk_length -= chunk.bytesize
  69. 247 if @chunk_length.zero?
  70. 205 yield @chunk_buffer unless @chunk_buffer.empty?
  71. 198 @chunk_buffer.clear
  72. 198 @chunk_length = nil
  73. 198 nextstate(:crlf)
  74. end
  75. end
  76. 941 break if @buffer.empty?
  77. end
  78. end
  79. 24 def finished?
  80. 163 @finished
  81. end
  82. 24 private
  83. 24 def nextstate(state)
  84. 899 @state = state
  85. end
  86. end
  87. 24 module_function
  88. 24 def encode(chunks)
  89. 84 Encoder.new(chunks)
  90. end
  91. end
  92. end

lib/httpx/transcoder/deflate.rb

100.0% lines covered

20 relevant lines. 20 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "zlib"
  3. 24 require_relative "utils/deflater"
  4. 24 module HTTPX
  5. 24 module Transcoder
  6. 24 module Deflate
  7. 24 class Deflater < Transcoder::Deflater
  8. 24 def deflate(chunk)
  9. 42 @deflater ||= Zlib::Deflate.new
  10. 42 if chunk.nil?
  11. 28 unless @deflater.closed?
  12. 14 last = @deflater.finish
  13. 14 @deflater.close
  14. 14 last.empty? ? nil : last
  15. end
  16. else
  17. 14 @deflater.deflate(chunk)
  18. end
  19. end
  20. end
  21. 24 module_function
  22. 24 def encode(body)
  23. 14 Deflater.new(body)
  24. end
  25. 24 def decode(response, bytesize: nil)
  26. 14 bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
  27. 14 GZIP::Inflater.new(bytesize)
  28. end
  29. end
  30. end
  31. end

lib/httpx/transcoder/form.rb

100.0% lines covered

42 relevant lines. 42 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "forwardable"
  3. 24 require "uri"
  4. 24 require_relative "multipart"
  5. 24 module HTTPX
  6. 24 module Transcoder
  7. 24 module Form
  8. 24 module_function
  9. 24 PARAM_DEPTH_LIMIT = 32
  10. 24 class Encoder
  11. 24 extend Forwardable
  12. 24 def_delegator :@raw, :to_s
  13. 24 def_delegator :@raw, :to_str
  14. 24 def_delegator :@raw, :bytesize
  15. 24 def_delegator :@raw, :==
  16. 24 def initialize(form)
  17. 602 @raw = form.each_with_object("".b) do |(key, val), buf|
  18. 1008 HTTPX::Transcoder.normalize_keys(key, val) do |k, v|
  19. 1181 buf << "&" unless buf.empty?
  20. 1181 buf << URI.encode_www_form_component(k)
  21. 1181 buf << "=#{URI.encode_www_form_component(v.to_s)}" unless v.nil?
  22. end
  23. end
  24. end
  25. 24 def content_type
  26. 470 "application/x-www-form-urlencoded"
  27. end
  28. end
  29. 24 module Decoder
  30. 24 module_function
  31. 24 def call(response, *)
  32. 35 URI.decode_www_form(response.to_s).each_with_object({}) do |(field, value), params|
  33. 84 HTTPX::Transcoder.normalize_query(params, field, value, PARAM_DEPTH_LIMIT)
  34. end
  35. end
  36. end
  37. 24 def encode(form)
  38. 1434 if multipart?(form)
  39. 832 Multipart::Encoder.new(form)
  40. else
  41. 602 Encoder.new(form)
  42. end
  43. end
  44. 24 def decode(response)
  45. 56 content_type = response.content_type.mime_type
  46. 48 case content_type
  47. when "application/x-www-form-urlencoded"
  48. 35 Decoder
  49. when "multipart/form-data"
  50. 14 Multipart::Decoder.new(response)
  51. else
  52. 7 raise Error, "invalid form mime type (#{content_type})"
  53. end
  54. end
  55. 24 def multipart?(data)
  56. 1434 data.any? do |_, v|
  57. 1896 Multipart::MULTIPART_VALUE_COND.call(v) ||
  58. 1456 (v.respond_to?(:to_ary) && v.to_ary.any?(&Multipart::MULTIPART_VALUE_COND)) ||
  59. 1792 (v.respond_to?(:to_hash) && v.to_hash.any? { |_, e| Multipart::MULTIPART_VALUE_COND.call(e) })
  60. end
  61. end
  62. end
  63. end
  64. end

lib/httpx/transcoder/gzip.rb

100.0% lines covered

43 relevant lines. 43 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "forwardable"
  3. 24 require "uri"
  4. 24 require "stringio"
  5. 24 require "zlib"
  6. 24 module HTTPX
  7. 24 module Transcoder
  8. 24 module GZIP
  9. 24 class Deflater < Transcoder::Deflater
  10. 24 def initialize(body)
  11. 34 @compressed_chunk = "".b
  12. 34 super
  13. end
  14. 24 def deflate(chunk)
  15. 68 @deflater ||= Zlib::GzipWriter.new(self)
  16. 68 if chunk.nil?
  17. 34 unless @deflater.closed?
  18. 34 @deflater.flush
  19. 34 @deflater.close
  20. 34 compressed_chunk
  21. end
  22. else
  23. 34 @deflater.write(chunk)
  24. 34 compressed_chunk
  25. end
  26. end
  27. 24 private
  28. 24 def write(chunk)
  29. 102 @compressed_chunk << chunk
  30. end
  31. 24 def compressed_chunk
  32. 68 @compressed_chunk.dup
  33. ensure
  34. 68 @compressed_chunk.clear
  35. end
  36. end
  37. 24 class Inflater
  38. 24 def initialize(bytesize)
  39. 135 @inflater = Zlib::Inflate.new(Zlib::MAX_WBITS + 32)
  40. 135 @bytesize = bytesize
  41. end
  42. 24 def call(chunk)
  43. 371 buffer = @inflater.inflate(chunk)
  44. 336 @bytesize -= chunk.bytesize
  45. 371 if @bytesize <= 0
  46. 80 buffer << @inflater.finish
  47. 80 @inflater.close
  48. end
  49. 371 buffer
  50. end
  51. end
  52. 24 module_function
  53. 24 def encode(body)
  54. 34 Deflater.new(body)
  55. end
  56. 24 def decode(response, bytesize: nil)
  57. 121 bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
  58. 121 Inflater.new(bytesize)
  59. end
  60. end
  61. end
  62. end

lib/httpx/transcoder/json.rb

100.0% lines covered

33 relevant lines. 33 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "forwardable"
  3. 24 module HTTPX::Transcoder
  4. 24 module JSON
  5. 24 module_function
  6. 24 JSON_REGEX = %r{\bapplication/(?:vnd\.api\+|hal\+)?json\b}i.freeze
  7. 24 class Encoder
  8. 24 extend Forwardable
  9. 24 def_delegator :@raw, :to_s
  10. 24 def_delegator :@raw, :bytesize
  11. 24 def_delegator :@raw, :==
  12. 24 def initialize(json)
  13. 63 @raw = JSON.json_dump(json)
  14. 63 @charset = @raw.encoding.name.downcase
  15. end
  16. 24 def content_type
  17. 63 "application/json; charset=#{@charset}"
  18. end
  19. end
  20. 24 def encode(json)
  21. 63 Encoder.new(json)
  22. end
  23. 24 def decode(response)
  24. 65 content_type = response.content_type.mime_type
  25. 65 raise HTTPX::Error, "invalid json mime type (#{content_type})" unless JSON_REGEX.match?(content_type)
  26. 58 method(:json_load)
  27. end
  28. # rubocop:disable Style/SingleLineMethods
  29. 24 if defined?(MultiJson)
  30. 4 def json_load(*args); MultiJson.load(*args); end
  31. 1 def json_dump(*args); MultiJson.dump(*args); end
  32. 22 elsif defined?(Oj)
  33. 4 def json_load(response, *args); Oj.load(response.to_s, *args); end
  34. 1 def json_dump(*args); Oj.dump(*args); end
  35. 21 elsif defined?(Yajl)
  36. 4 def json_load(response, *args); Yajl::Parser.new(*args).parse(response.to_s); end
  37. 1 def json_dump(*args); Yajl::Encoder.encode(*args); end
  38. else
  39. 21 require "json"
  40. 63 def json_load(*args); ::JSON.parse(*args); end
  41. 75 def json_dump(*args); ::JSON.dump(*args); end
  42. end
  43. # rubocop:enable Style/SingleLineMethods
  44. end
  45. end

lib/httpx/transcoder/multipart.rb

100.0% lines covered

10 relevant lines. 10 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require_relative "multipart/encoder"
  3. 24 require_relative "multipart/decoder"
  4. 24 require_relative "multipart/part"
  5. 24 require_relative "multipart/mime_type_detector"
  6. 24 module HTTPX::Transcoder
  7. 24 module Multipart
  8. 24 MULTIPART_VALUE_COND = lambda do |value|
  9. 4237 value.respond_to?(:read) ||
  10. 3038 (value.respond_to?(:to_hash) &&
  11. value.key?(:body) &&
  12. 564 (value.key?(:filename) || value.key?(:content_type)))
  13. end
  14. end
  15. end

lib/httpx/transcoder/multipart/decoder.rb

93.98% lines covered

83 relevant lines. 78 lines covered and 5 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "tempfile"
  3. 24 require "delegate"
  4. 24 module HTTPX
  5. 24 module Transcoder
  6. 24 module Multipart
  7. 24 class FilePart < SimpleDelegator
  8. 24 attr_reader :original_filename, :content_type
  9. 24 def initialize(filename, content_type)
  10. 28 @original_filename = filename
  11. 28 @content_type = content_type
  12. 28 @file = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
  13. 28 super(@file)
  14. end
  15. end
  16. 24 class Decoder
  17. 24 include HTTPX::Utils
  18. 24 CRLF = "\r\n"
  19. 24 BOUNDARY_RE = /;\s*boundary=([^;]+)/i.freeze
  20. 24 MULTIPART_CONTENT_TYPE = /Content-Type: (.*)#{CRLF}/ni.freeze
  21. 24 MULTIPART_CONTENT_DISPOSITION = /Content-Disposition:.*;\s*name=(#{VALUE})/ni.freeze
  22. 24 MULTIPART_CONTENT_ID = /Content-ID:\s*([^#{CRLF}]*)/ni.freeze
  23. 24 WINDOW_SIZE = 2 << 14
  24. 24 def initialize(response)
  25. 2 @boundary = begin
  26. 14 m = response.headers["content-type"].to_s[BOUNDARY_RE, 1]
  27. 14 raise Error, "no boundary declared in content-type header" unless m
  28. 14 m.strip
  29. end
  30. 14 @buffer = "".b
  31. 14 @parts = {}
  32. 14 @intermediate_boundary = "--#{@boundary}"
  33. 14 @state = :idle
  34. end
  35. 24 def call(response, *)
  36. 14 response.body.each do |chunk|
  37. 14 @buffer << chunk
  38. 14 parse
  39. end
  40. 14 raise Error, "invalid or unsupported multipart format" unless @buffer.empty?
  41. 14 @parts
  42. end
  43. 24 private
  44. 24 def parse
  45. 12 case @state
  46. when :idle
  47. 14 raise Error, "payload does not start with boundary" unless @buffer.start_with?("#{@intermediate_boundary}#{CRLF}")
  48. 14 @buffer = @buffer.byteslice(@intermediate_boundary.bytesize + 2..-1)
  49. 14 @state = :part_header
  50. when :part_header
  51. 42 idx = @buffer.index("#{CRLF}#{CRLF}")
  52. # raise Error, "couldn't parse part headers" unless idx
  53. 42 return unless idx
  54. 42 head = @buffer.byteslice(0..idx + 4 - 1)
  55. 42 @buffer = @buffer.byteslice(head.bytesize..-1)
  56. 42 content_type = head[MULTIPART_CONTENT_TYPE, 1]
  57. 72 if (name = head[MULTIPART_CONTENT_DISPOSITION, 1])
  58. 42 name = /\A"(.*)"\Z/ =~ name ? Regexp.last_match(1) : name.dup
  59. 42 name.gsub!(/\\(.)/, "\\1")
  60. 12 name
  61. else
  62. name = head[MULTIPART_CONTENT_ID, 1]
  63. end
  64. 42 filename = HTTPX::Utils.get_filename(head)
  65. 42 name = filename || +"#{content_type || "text/plain"}[]" if name.nil? || name.empty?
  66. 42 @current = name
  67. 36 @parts[name] = if filename
  68. 28 FilePart.new(filename, content_type)
  69. else
  70. 14 "".b
  71. end
  72. 42 @state = :part_body
  73. when :part_body
  74. 42 part = @parts[@current]
  75. 42 body_separator = if part.is_a?(FilePart)
  76. 24 "#{CRLF}#{CRLF}"
  77. else
  78. 14 CRLF
  79. end
  80. 42 idx = @buffer.index(body_separator)
  81. 42 if idx
  82. 42 payload = @buffer.byteslice(0..idx - 1)
  83. 42 @buffer = @buffer.byteslice(idx + body_separator.bytesize..-1)
  84. 42 part << payload
  85. 42 part.rewind if part.respond_to?(:rewind)
  86. 42 @state = :parse_boundary
  87. else
  88. part << @buffer
  89. @buffer.clear
  90. end
  91. when :parse_boundary
  92. 42 raise Error, "payload does not start with boundary" unless @buffer.start_with?(@intermediate_boundary)
  93. 42 @buffer = @buffer.byteslice(@intermediate_boundary.bytesize..-1)
  94. 42 if @buffer == "--"
  95. 14 @buffer.clear
  96. 14 @state = :done
  97. 14 return
  98. 27 elsif @buffer.start_with?(CRLF)
  99. 28 @buffer = @buffer.byteslice(2..-1)
  100. 28 @state = :part_header
  101. else
  102. return
  103. end
  104. when :done
  105. raise Error, "parsing should have been over by now"
  106. 20 end until @buffer.empty?
  107. end
  108. end
  109. end
  110. end
  111. end

lib/httpx/transcoder/multipart/encoder.rb

100.0% lines covered

69 relevant lines. 69 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 module Transcoder::Multipart
  4. 24 class Encoder
  5. 24 attr_reader :bytesize
  6. 24 def initialize(form)
  7. 832 @boundary = ("-" * 21) << SecureRandom.hex(21)
  8. 832 @part_index = 0
  9. 832 @buffer = "".b
  10. 832 @form = form
  11. 832 @parts = to_parts(form)
  12. end
  13. 24 def content_type
  14. 832 "multipart/form-data; boundary=#{@boundary}"
  15. end
  16. 24 def to_s
  17. 15 read
  18. ensure
  19. 15 rewind
  20. end
  21. 24 def read(length = nil, outbuf = nil)
  22. 3355 data = String(outbuf).clear.force_encoding(Encoding::BINARY) if outbuf
  23. 3355 data ||= "".b
  24. 3355 read_chunks(data, length)
  25. 3355 data unless length && data.empty?
  26. end
  27. 24 def rewind
  28. 43 form = @form.each_with_object([]) do |(key, val), aux|
  29. 43 if val.respond_to?(:path) && val.respond_to?(:reopen) && val.respond_to?(:closed?) && val.closed?
  30. 43 val = val.reopen(val.path, File::RDONLY)
  31. end
  32. 43 val.rewind if val.respond_to?(:rewind)
  33. 43 aux << [key, val]
  34. end
  35. 43 @form = form
  36. 43 @parts = to_parts(form)
  37. 43 @part_index = 0
  38. end
  39. 24 private
  40. 24 def to_parts(form)
  41. 875 @bytesize = 0
  42. 875 params = form.each_with_object([]) do |(key, val), aux|
  43. 1043 Transcoder.normalize_keys(key, val, MULTIPART_VALUE_COND) do |k, v|
  44. 1043 next if v.nil?
  45. 1043 value, content_type, filename = Part.call(v)
  46. 1043 header = header_part(k, content_type, filename)
  47. 899 @bytesize += header.size
  48. 1043 aux << header
  49. 899 @bytesize += value.size
  50. 1043 aux << value
  51. 1043 delimiter = StringIO.new("\r\n")
  52. 899 @bytesize += delimiter.size
  53. 1043 aux << delimiter
  54. end
  55. end
  56. 875 final_delimiter = StringIO.new("--#{@boundary}--\r\n")
  57. 755 @bytesize += final_delimiter.size
  58. 875 params << final_delimiter
  59. 875 params
  60. end
  61. 24 def header_part(key, content_type, filename)
  62. 1043 header = "--#{@boundary}\r\n".b
  63. 1043 header << "Content-Disposition: form-data; name=#{key.inspect}".b
  64. 1043 header << "; filename=#{filename.inspect}" if filename
  65. 1043 header << "\r\nContent-Type: #{content_type}\r\n\r\n"
  66. 1043 StringIO.new(header)
  67. end
  68. 24 def read_chunks(buffer, length = nil)
  69. 4455 while @part_index < @parts.size
  70. 9535 chunk = read_from_part(length)
  71. 9535 next unless chunk
  72. 5571 buffer << chunk.force_encoding(Encoding::BINARY)
  73. 5571 next unless length
  74. 4776 length -= chunk.bytesize
  75. 5516 break if length.zero?
  76. end
  77. end
  78. # if there's a current part to read from, tries to read a chunk.
  79. 24 def read_from_part(max_length = nil)
  80. 9535 part = @parts[@part_index]
  81. 9535 chunk = part.read(max_length, @buffer)
  82. 9535 return chunk if chunk && !chunk.empty?
  83. 3964 part.close if part.respond_to?(:close)
  84. 3412 @part_index += 1
  85. 1104 nil
  86. end
  87. end
  88. end
  89. end

lib/httpx/transcoder/multipart/mime_type_detector.rb

92.11% lines covered

38 relevant lines. 35 lines covered and 3 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 module Transcoder::Multipart
  4. 24 module MimeTypeDetector
  5. 24 module_function
  6. 24 DEFAULT_MIMETYPE = "application/octet-stream"
  7. # inspired by https://github.com/shrinerb/shrine/blob/master/lib/shrine/plugins/determine_mime_type.rb
  8. 24 if defined?(FileMagic)
  9. 1 MAGIC_NUMBER = 256 * 1024
  10. 1 def call(file, _)
  11. 1 return nil if file.eof? # FileMagic returns "application/x-empty" for empty files
  12. 1 mime = FileMagic.open(FileMagic::MAGIC_MIME_TYPE) do |filemagic|
  13. 1 filemagic.buffer(file.read(MAGIC_NUMBER))
  14. end
  15. 1 file.rewind
  16. 1 mime
  17. end
  18. 22 elsif defined?(Marcel)
  19. 1 def call(file, filename)
  20. 1 return nil if file.eof? # marcel returns "application/octet-stream" for empty files
  21. 1 Marcel::MimeType.for(file, name: filename)
  22. end
  23. 21 elsif defined?(MimeMagic)
  24. 1 def call(file, _)
  25. 1 mime = MimeMagic.by_magic(file)
  26. 1 mime.type if mime
  27. end
  28. 20 elsif system("which file", out: File::NULL)
  29. 21 require "open3"
  30. 21 def call(file, _)
  31. 591 return if file.eof? # file command returns "application/x-empty" for empty files
  32. 553 Open3.popen3(*%w[file --mime-type --brief -]) do |stdin, stdout, stderr, thread|
  33. 75 begin
  34. 553 ::IO.copy_stream(file, stdin.binmode)
  35. rescue Errno::EPIPE
  36. end
  37. 553 file.rewind
  38. 553 stdin.close
  39. 553 status = thread.value
  40. # call to file command failed
  41. 553 if status.nil? || !status.success?
  42. $stderr.print(stderr.read)
  43. else
  44. 553 output = stdout.read.strip
  45. 553 if output.include?("cannot open")
  46. $stderr.print(output)
  47. else
  48. 553 output
  49. end
  50. end
  51. end
  52. end
  53. else
  54. def call(_, _); end
  55. end
  56. end
  57. end
  58. end

lib/httpx/transcoder/multipart/part.rb

100.0% lines covered

18 relevant lines. 18 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 module Transcoder::Multipart
  4. 24 module Part
  5. 24 module_function
  6. 24 def call(value)
  7. # take out specialized objects of the way
  8. 1043 if value.respond_to?(:filename) && value.respond_to?(:content_type) && value.respond_to?(:read)
  9. 96 return value, value.content_type, value.filename
  10. end
  11. 931 content_type = filename = nil
  12. 931 if value.is_a?(Hash)
  13. 282 content_type = value[:content_type]
  14. 282 filename = value[:filename]
  15. 282 value = value[:body]
  16. end
  17. 931 value = value.open(File::RDONLY) if Object.const_defined?(:Pathname) && value.is_a?(Pathname)
  18. 931 if value.respond_to?(:path) && value.respond_to?(:read)
  19. # either a File, a Tempfile, or something else which has to quack like a file
  20. 595 filename ||= File.basename(value.path)
  21. 595 content_type ||= MimeTypeDetector.call(value, filename) || "application/octet-stream"
  22. 595 [value, content_type, filename]
  23. else
  24. 336 [StringIO.new(value.to_s), content_type || "text/plain", filename]
  25. end
  26. end
  27. end
  28. end
  29. end

lib/httpx/transcoder/utils/body_reader.rb

96.0% lines covered

25 relevant lines. 24 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "stringio"
  3. 24 module HTTPX
  4. 24 module Transcoder
  5. 24 class BodyReader
  6. 24 def initialize(body)
  7. 163 @body = if body.respond_to?(:read)
  8. 10 body.rewind if body.respond_to?(:rewind)
  9. 10 body
  10. 152 elsif body.respond_to?(:each)
  11. 30 body.enum_for(:each)
  12. else
  13. 123 StringIO.new(body.to_s)
  14. end
  15. end
  16. 24 def bytesize
  17. 335 return @body.bytesize if @body.respond_to?(:bytesize)
  18. 305 Float::INFINITY
  19. end
  20. 24 def read(length = nil, outbuf = nil)
  21. 350 return @body.read(length, outbuf) if @body.respond_to?(:read)
  22. begin
  23. 70 chunk = @body.next
  24. 40 if outbuf
  25. 40 outbuf.clear.force_encoding(Encoding::BINARY)
  26. 40 outbuf << chunk
  27. else
  28. outbuf = chunk
  29. end
  30. 40 outbuf unless length && outbuf.empty?
  31. 24 rescue StopIteration
  32. end
  33. end
  34. 24 def close
  35. 34 @body.close if @body.respond_to?(:close)
  36. end
  37. end
  38. end
  39. end

lib/httpx/transcoder/utils/deflater.rb

100.0% lines covered

36 relevant lines. 36 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "forwardable"
  3. 24 require_relative "body_reader"
  4. 24 module HTTPX
  5. 24 module Transcoder
  6. 24 class Deflater
  7. 24 extend Forwardable
  8. 24 attr_reader :content_type
  9. 24 def initialize(body)
  10. 58 @content_type = body.content_type
  11. 58 @body = BodyReader.new(body)
  12. 58 @closed = false
  13. end
  14. 24 def bytesize
  15. 222 buffer_deflate!
  16. 222 @buffer.size
  17. end
  18. 24 def read(length = nil, outbuf = nil)
  19. 280 return @buffer.read(length, outbuf) if @buffer
  20. 164 return if @closed
  21. 130 chunk = @body.read(length)
  22. 130 compressed_chunk = deflate(chunk)
  23. 130 return unless compressed_chunk
  24. 106 if outbuf
  25. 98 outbuf.clear.force_encoding(Encoding::BINARY)
  26. 98 outbuf << compressed_chunk
  27. else
  28. 8 compressed_chunk
  29. end
  30. end
  31. 24 def close
  32. 34 return if @closed
  33. 34 @buffer.close if @buffer
  34. 34 @body.close
  35. 34 @closed = true
  36. end
  37. 24 private
  38. # rubocop:disable Naming/MemoizedInstanceVariableName
  39. 24 def buffer_deflate!
  40. 222 return @buffer if defined?(@buffer)
  41. 58 buffer = Response::Buffer.new(
  42. threshold_size: Options::MAX_BODY_THRESHOLD_SIZE
  43. )
  44. 58 ::IO.copy_stream(self, buffer)
  45. 58 buffer.rewind
  46. 58 @buffer = buffer
  47. end
  48. # rubocop:enable Naming/MemoizedInstanceVariableName
  49. end
  50. end
  51. end

lib/httpx/transcoder/xml.rb

92.31% lines covered

26 relevant lines. 24 lines covered and 2 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 require "delegate"
  3. 24 require "forwardable"
  4. 24 require "uri"
  5. 24 module HTTPX::Transcoder
  6. 24 module Xml
  7. 24 module_function
  8. 24 MIME_TYPES = %r{\b(application|text)/(.+\+)?xml\b}.freeze
  9. 24 class Encoder
  10. 24 def initialize(xml)
  11. 119 @raw = xml
  12. end
  13. 24 def content_type
  14. 119 charset = @raw.respond_to?(:encoding) ? @raw.encoding.to_s.downcase : "utf-8"
  15. 119 "application/xml; charset=#{charset}"
  16. end
  17. 24 def bytesize
  18. 357 @raw.to_s.bytesize
  19. end
  20. 24 def to_s
  21. 112 @raw.to_s
  22. end
  23. end
  24. 24 def encode(xml)
  25. 119 Encoder.new(xml)
  26. end
  27. begin
  28. 24 require "nokogiri"
  29. 24 def decode(response)
  30. 7 content_type = response.content_type.mime_type
  31. 7 raise HTTPX::Error, "invalid form mime type (#{content_type})" unless MIME_TYPES.match?(content_type)
  32. 7 Nokogiri::XML.method(:parse)
  33. end
  34. rescue LoadError
  35. def decode(_response)
  36. raise HTTPX::Error, "\"nokogiri\" is required in order to decode XML"
  37. end
  38. end
  39. end
  40. end

lib/httpx/utils.rb

100.0% lines covered

39 relevant lines. 39 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 24 module HTTPX
  3. 24 module Utils
  4. 24 using URIExtensions
  5. 24 TOKEN = %r{[^\s()<>,;:\\"/\[\]?=]+}.freeze
  6. 24 VALUE = /"(?:\\"|[^"])*"|#{TOKEN}/.freeze
  7. 24 FILENAME_REGEX = /\s*filename=(#{VALUE})/.freeze
  8. 24 FILENAME_EXTENSION_REGEX = /\s*filename\*=(#{VALUE})/.freeze
  9. 24 module_function
  10. 24 def now
  11. 2236729 Process.clock_gettime(Process::CLOCK_MONOTONIC)
  12. end
  13. 24 def elapsed_time(monotonic_timestamp)
  14. 2211018 Process.clock_gettime(Process::CLOCK_MONOTONIC) - monotonic_timestamp
  15. end
  16. # The value of this field can be either an HTTP-date or a number of
  17. # seconds to delay after the response is received.
  18. 24 def parse_retry_after(retry_after)
  19. # first: bet on it being an integer
  20. 53 Integer(retry_after)
  21. rescue ArgumentError
  22. # Then it's a datetime
  23. 14 time = Time.httpdate(retry_after)
  24. 14 time - Time.now
  25. end
  26. 24 def get_filename(header, _prefix_regex = nil)
  27. 77 filename = nil
  28. 66 case header
  29. when FILENAME_REGEX
  30. 49 filename = Regexp.last_match(1)
  31. 49 filename = Regexp.last_match(1) if filename =~ /^"(.*)"$/
  32. when FILENAME_EXTENSION_REGEX
  33. 14 filename = Regexp.last_match(1)
  34. 14 encoding, _, filename = filename.split("'", 3)
  35. end
  36. 77 return unless filename
  37. 119 filename = URI::DEFAULT_PARSER.unescape(filename) if filename.scan(/%.?.?/).all? { |s| /%[0-9a-fA-F]{2}/.match?(s) }
  38. 63 filename.scrub!
  39. 63 filename = filename.gsub(/\\(.)/, '\1') unless /\\[^\\"]/.match?(filename)
  40. 63 filename.force_encoding ::Encoding.find(encoding) if encoding
  41. 63 filename
  42. end
  43. 24 URIParser = URI::RFC2396_Parser.new
  44. 24 def to_uri(uri)
  45. 20119 return URI(uri) unless uri.is_a?(String) && !uri.ascii_only?
  46. 29 uri = URI(URIParser.escape(uri))
  47. 29 non_ascii_hostname = URIParser.unescape(uri.host)
  48. 29 non_ascii_hostname.force_encoding(Encoding::UTF_8)
  49. 29 idna_hostname = Punycode.encode_hostname(non_ascii_hostname)
  50. 29 uri.host = idna_hostname
  51. 28 uri.non_ascii_hostname = non_ascii_hostname
  52. 28 uri
  53. end
  54. end
  55. end