loading
Generated 2025-10-14T00:15:26+00:00

All Files ( 96.31% covered at 79209.09 hits/line )

107 files in total.
7951 relevant lines, 7658 lines covered and 293 lines missed. ( 96.31% )
File % covered Lines Relevant Lines Lines covered Lines missed Avg. Hits / Line
lib/httpx.rb 100.00 % 66 39 39 0 898.44
lib/httpx/adapters/datadog.rb 86.98 % 359 169 147 22 43.56
lib/httpx/adapters/faraday.rb 98.76 % 303 161 159 2 123.12
lib/httpx/adapters/sentry.rb 100.00 % 121 62 62 0 81.81
lib/httpx/adapters/webmock.rb 100.00 % 175 93 93 0 96.04
lib/httpx/altsvc.rb 96.39 % 163 83 80 3 233.87
lib/httpx/buffer.rb 100.00 % 61 27 27 0 4590.37
lib/httpx/callbacks.rb 100.00 % 35 19 19 0 158012.16
lib/httpx/chainable.rb 95.45 % 106 44 42 2 1038.80
lib/httpx/connection.rb 94.81 % 954 482 457 25 130971.55
lib/httpx/connection/http1.rb 89.59 % 399 221 198 23 3631.60
lib/httpx/connection/http2.rb 95.56 % 468 270 258 12 225405.89
lib/httpx/domain_name.rb 95.56 % 145 45 43 2 217.22
lib/httpx/errors.rb 97.67 % 111 43 42 1 78.40
lib/httpx/extensions.rb 67.86 % 59 28 19 9 428.57
lib/httpx/headers.rb 100.00 % 176 71 71 0 17056.55
lib/httpx/io.rb 100.00 % 11 5 5 0 26.00
lib/httpx/io/ssl.rb 97.50 % 163 80 78 2 2469.81
lib/httpx/io/tcp.rb 92.19 % 239 128 118 10 6922.93
lib/httpx/io/udp.rb 100.00 % 62 35 35 0 355.43
lib/httpx/io/unix.rb 97.14 % 71 35 34 1 18.80
lib/httpx/loggable.rb 100.00 % 66 25 25 0 390487.00
lib/httpx/options.rb 97.96 % 483 196 192 4 24572.29
lib/httpx/parser/http1.rb 100.00 % 186 109 109 0 7249.19
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 84.70
lib/httpx/plugins/auth/digest.rb 100.00 % 102 57 57 0 118.79
lib/httpx/plugins/auth/ntlm.rb 100.00 % 35 19 19 0 2.95
lib/httpx/plugins/auth/socks5.rb 100.00 % 22 11 11 0 21.00
lib/httpx/plugins/aws_sdk_authentication.rb 100.00 % 111 44 44 0 11.45
lib/httpx/plugins/aws_sigv4.rb 100.00 % 239 107 107 0 99.85
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 10.80
lib/httpx/plugins/callbacks.rb 91.53 % 127 59 54 5 112.37
lib/httpx/plugins/circuit_breaker.rb 100.00 % 147 65 65 0 67.11
lib/httpx/plugins/circuit_breaker/circuit.rb 100.00 % 100 47 47 0 52.53
lib/httpx/plugins/circuit_breaker/circuit_store.rb 100.00 % 53 23 23 0 86.43
lib/httpx/plugins/content_digest.rb 100.00 % 204 101 101 0 69.89
lib/httpx/plugins/cookies.rb 100.00 % 107 52 52 0 107.31
lib/httpx/plugins/cookies/cookie.rb 100.00 % 174 76 76 0 282.78
lib/httpx/plugins/cookies/jar.rb 100.00 % 95 46 46 0 228.13
lib/httpx/plugins/cookies/set_cookie_parser.rb 100.00 % 143 72 72 0 136.51
lib/httpx/plugins/digest_auth.rb 100.00 % 67 30 30 0 84.70
lib/httpx/plugins/expect.rb 100.00 % 120 57 57 0 77.30
lib/httpx/plugins/fiber_concurrency.rb 88.04 % 195 92 81 11 654.70
lib/httpx/plugins/follow_redirects.rb 100.00 % 233 109 109 0 160569.64
lib/httpx/plugins/grpc.rb 100.00 % 282 134 134 0 116.96
lib/httpx/plugins/grpc/call.rb 90.91 % 63 33 30 3 40.18
lib/httpx/plugins/grpc/grpc_encoding.rb 97.87 % 90 47 46 1 76.85
lib/httpx/plugins/grpc/message.rb 95.83 % 55 24 23 1 39.50
lib/httpx/plugins/h2c.rb 95.24 % 127 63 60 3 15.73
lib/httpx/plugins/ntlm_auth.rb 100.00 % 62 31 31 0 3.94
lib/httpx/plugins/oauth.rb 100.00 % 183 90 90 0 95.08
lib/httpx/plugins/persistent.rb 100.00 % 82 31 31 0 405.90
lib/httpx/plugins/proxy.rb 94.71 % 349 170 161 9 305.63
lib/httpx/plugins/proxy/http.rb 100.00 % 184 104 104 0 192.32
lib/httpx/plugins/proxy/socks4.rb 97.47 % 135 79 77 2 167.84
lib/httpx/plugins/proxy/socks5.rb 99.12 % 194 113 112 1 274.84
lib/httpx/plugins/proxy/ssh.rb 92.45 % 94 53 49 4 8.15
lib/httpx/plugins/push_promise.rb 100.00 % 81 41 41 0 9.22
lib/httpx/plugins/query.rb 100.00 % 35 14 14 0 9.43
lib/httpx/plugins/rate_limiter.rb 100.00 % 55 18 18 0 36.56
lib/httpx/plugins/response_cache.rb 100.00 % 336 144 144 0 167.33
lib/httpx/plugins/response_cache/file_store.rb 100.00 % 140 72 72 0 147.96
lib/httpx/plugins/response_cache/store.rb 100.00 % 33 16 16 0 137.81
lib/httpx/plugins/retries.rb 96.91 % 230 97 94 3 156658.03
lib/httpx/plugins/ssrf_filter.rb 100.00 % 145 61 61 0 109.57
lib/httpx/plugins/stream.rb 97.78 % 183 90 88 2 104.93
lib/httpx/plugins/stream_bidi.rb 99.28 % 315 138 137 1 80.10
lib/httpx/plugins/upgrade.rb 100.00 % 86 38 38 0 42.66
lib/httpx/plugins/upgrade/h2.rb 89.66 % 64 29 26 3 32.72
lib/httpx/plugins/webdav.rb 100.00 % 86 39 39 0 20.31
lib/httpx/plugins/xml.rb 100.00 % 76 34 34 0 74.32
lib/httpx/pmatch_extensions.rb 100.00 % 33 17 17 0 26.12
lib/httpx/pool.rb 100.00 % 190 90 90 0 4423.07
lib/httpx/punycode.rb 100.00 % 22 9 9 0 17.78
lib/httpx/request.rb 100.00 % 318 133 133 0 6431.17
lib/httpx/request/body.rb 100.00 % 158 68 68 0 2883.81
lib/httpx/resolver.rb 98.94 % 189 94 93 1 1440.96
lib/httpx/resolver/entry.rb 100.00 % 30 16 16 0 3404.69
lib/httpx/resolver/https.rb 86.11 % 256 144 124 20 34.42
lib/httpx/resolver/multi.rb 89.09 % 102 55 49 6 3532.64
lib/httpx/resolver/native.rb 91.40 % 547 314 287 27 1085.62
lib/httpx/resolver/resolver.rb 93.98 % 173 83 78 5 1676.45
lib/httpx/resolver/system.rb 79.14 % 255 139 110 29 17.74
lib/httpx/response.rb 100.00 % 304 114 114 0 1792.15
lib/httpx/response/body.rb 100.00 % 242 108 108 0 2795.55
lib/httpx/response/buffer.rb 96.67 % 115 60 58 2 1573.27
lib/httpx/selector.rb 95.45 % 282 132 126 6 1693213.20
lib/httpx/session.rb 94.33 % 612 300 283 17 89071.38
lib/httpx/session_extensions.rb 100.00 % 30 15 15 0 6.07
lib/httpx/timers.rb 93.94 % 133 66 62 4 2733353.94
lib/httpx/transcoder.rb 100.00 % 91 52 52 0 262.44
lib/httpx/transcoder/body.rb 100.00 % 43 26 26 0 857.77
lib/httpx/transcoder/chunker.rb 100.00 % 115 66 66 0 189.67
lib/httpx/transcoder/deflate.rb 100.00 % 42 21 21 0 27.43
lib/httpx/transcoder/form.rb 100.00 % 68 35 35 0 220.23
lib/httpx/transcoder/gzip.rb 100.00 % 71 40 40 0 107.00
lib/httpx/transcoder/json.rb 100.00 % 71 33 33 0 42.88
lib/httpx/transcoder/multipart.rb 100.00 % 31 18 18 0 844.94
lib/httpx/transcoder/multipart/decoder.rb 93.90 % 141 82 77 5 26.65
lib/httpx/transcoder/multipart/encoder.rb 100.00 % 120 70 70 0 1818.54
lib/httpx/transcoder/multipart/mime_type_detector.rb 92.11 % 78 38 35 3 172.03
lib/httpx/transcoder/multipart/part.rb 100.00 % 35 18 18 0 480.00
lib/httpx/transcoder/utils/body_reader.rb 95.83 % 45 24 23 1 102.08
lib/httpx/transcoder/utils/deflater.rb 100.00 % 74 36 36 0 93.97
lib/httpx/utils.rb 100.00 % 75 39 39 0 440196.85

lib/httpx.rb

100.0% lines covered

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

lib/httpx/adapters/datadog.rb

86.98% lines covered

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

lib/httpx/adapters/faraday.rb

98.76% lines covered

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

lib/httpx/adapters/webmock.rb

100.0% lines covered

93 relevant lines. 93 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 8 module WebMock
  3. 8 module HttpLibAdapters
  4. 8 require "net/http/status"
  5. 8 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. 8 module Plugin
  12. 8 class << self
  13. 8 def build_webmock_request_signature(request)
  14. 188 uri = WebMock::Util::URI.heuristic_parse(request.uri)
  15. 188 uri.query = request.query
  16. 188 uri.path = uri.normalized_path.gsub("[^:]//", "/")
  17. 188 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. 8 def build_webmock_response(_request, response)
  25. 6 webmock_response = WebMock::Response.new
  26. 6 webmock_response.status = [response.status, HTTP_REASONS[response.status]]
  27. 6 webmock_response.body = response.body.to_s
  28. 6 webmock_response.headers = response.headers.to_h
  29. 6 webmock_response
  30. end
  31. 8 def build_from_webmock_response(request, webmock_response)
  32. 158 return build_error_response(request, HTTPX::TimeoutError.new(1, "Timed out")) if webmock_response.should_timeout
  33. 140 return build_error_response(request, webmock_response.exception) if webmock_response.exception
  34. 133 request.options.response_class.new(request,
  35. webmock_response.status[0],
  36. "2.0",
  37. webmock_response.headers).tap do |res|
  38. 133 res.mocked = true
  39. end
  40. end
  41. 8 def build_error_response(request, exception)
  42. 25 HTTPX::ErrorResponse.new(request, exception)
  43. end
  44. end
  45. 8 module InstanceMethods
  46. 8 private
  47. 8 def do_init_connection(connection, selector)
  48. 170 super
  49. 170 connection.once(:unmock_connection) do
  50. 24 next unless connection.current_session == self
  51. 24 unless connection.addresses?
  52. # reset Happy Eyeballs, fail early
  53. 24 connection.sibling = nil
  54. 24 deselect_connection(connection, selector)
  55. end
  56. 24 resolve_connection(connection, selector)
  57. end
  58. end
  59. end
  60. 8 module ResponseMethods
  61. 8 attr_accessor :mocked
  62. 8 def initialize(*)
  63. 157 super
  64. 157 @mocked = false
  65. end
  66. end
  67. 8 module ResponseBodyMethods
  68. 8 def decode_chunk(chunk)
  69. 96 return chunk if @response.mocked
  70. 42 super
  71. end
  72. end
  73. 8 module ConnectionMethods
  74. 8 def initialize(*)
  75. 170 super
  76. 170 @mocked = true
  77. end
  78. 8 def open?
  79. 194 return true if @mocked
  80. 24 super
  81. end
  82. 8 def interests
  83. 278 return if @mocked
  84. 246 super
  85. end
  86. 8 def terminate
  87. 145 force_reset
  88. end
  89. 8 def send(request)
  90. 188 request_signature = Plugin.build_webmock_request_signature(request)
  91. 188 WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
  92. 188 if (mock_response = WebMock::StubRegistry.instance.response_for_request(request_signature))
  93. 158 response = Plugin.build_from_webmock_response(request, mock_response)
  94. 158 WebMock::CallbackRegistry.invoke_callbacks({ lib: :httpx }, request_signature, mock_response)
  95. 158 log { "mocking #{request.uri} with #{mock_response.inspect}" }
  96. 158 request.transition(:headers)
  97. 158 request.transition(:body)
  98. 158 request.transition(:trailers)
  99. 158 request.transition(:done)
  100. 158 response.finish!
  101. 158 request.response = response
  102. 158 request.emit(:response, response)
  103. 158 request_signature.headers = request.headers.to_h
  104. 158 response << mock_response.body.dup unless response.is_a?(HTTPX::ErrorResponse)
  105. 30 elsif WebMock.net_connect_allowed?(request_signature.uri)
  106. 24 if WebMock::CallbackRegistry.any_callbacks?
  107. 6 request.on(:response) do |resp|
  108. 6 unless resp.is_a?(HTTPX::ErrorResponse)
  109. 6 webmock_response = Plugin.build_webmock_response(request, resp)
  110. 6 WebMock::CallbackRegistry.invoke_callbacks(
  111. { lib: :httpx, real_request: true }, request_signature,
  112. webmock_response
  113. )
  114. end
  115. end
  116. end
  117. 24 @mocked = false
  118. 24 emit(:unmock_connection, self)
  119. 24 super
  120. else
  121. 6 raise WebMock::NetConnectNotAllowedError, request_signature
  122. end
  123. end
  124. end
  125. end
  126. 8 class HttpxAdapter < HttpLibAdapter
  127. 8 adapter_for :httpx
  128. 8 class << self
  129. 8 def enable!
  130. 370 @original_session ||= HTTPX::Session
  131. 370 webmock_session = HTTPX.plugin(Plugin)
  132. 370 HTTPX.send(:remove_const, :Session)
  133. 370 HTTPX.send(:const_set, :Session, webmock_session.class)
  134. end
  135. 8 def disable!
  136. 370 return unless @original_session
  137. 362 HTTPX.send(:remove_const, :Session)
  138. 362 HTTPX.send(:const_set, :Session, @original_session)
  139. end
  140. end
  141. end
  142. end
  143. 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. 26 require "strscan"
  3. 26 module HTTPX
  4. 26 module AltSvc
  5. # makes connections able to accept requests destined to primary service.
  6. 26 module ConnectionMixin
  7. 26 using URIExtensions
  8. 26 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. 26 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. 26 private
  17. # checks if this is connection is an alternative service of
  18. # +uri+
  19. 26 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. 26 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. 26 def altsvc_match?(uri, other_uri)
  33. 14 other_uri = URI(other_uri)
  34. 14 uri.origin == other_uri.origin || begin
  35. 7 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. 26 @altsvc_mutex = Thread::Mutex.new
  47. 47 @altsvcs = Hash.new { |h, k| h[k] = [] }
  48. 26 module_function
  49. 26 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. 26 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. 26 def lookup(origin, ttl)
  65. 35 return [] unless @altsvcs.key?(origin)
  66. 28 @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. 26 def emit(request, response)
  72. 7335 return unless response.respond_to?(:headers)
  73. # Alt-Svc
  74. 7298 return unless response.headers.key?("alt-svc")
  75. 114 origin = request.origin
  76. 114 host = request.uri.host
  77. 114 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. 114 if altsvc == "clear"
  84. 7 @altsvc_mutex.synchronize do
  85. 7 @altsvcs[origin].clear
  86. end
  87. 7 return
  88. end
  89. 107 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. 26 def parse(altsvc)
  95. 205 return enum_for(__method__, altsvc) unless block_given?
  96. 156 scanner = StringScanner.new(altsvc)
  97. 156 until scanner.eos?
  98. 156 alt_service = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
  99. 156 alt_params = []
  100. 156 loop do
  101. 177 alt_param = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
  102. 177 alt_params << alt_param.strip if alt_param
  103. 177 scanner.skip(/;/)
  104. 177 break if scanner.eos? || scanner.scan(/ *, */)
  105. end
  106. 312 alt_params = Hash[alt_params.map { |field| field.split("=", 2) }]
  107. 156 alt_proto, alt_authority = alt_service.split("=", 2)
  108. 156 alt_origin = parse_altsvc_origin(alt_proto, alt_authority)
  109. 156 return unless alt_origin
  110. 42 yield(alt_origin, alt_params.merge("proto" => alt_proto))
  111. end
  112. end
  113. 26 def parse_altsvc_scheme(alt_proto)
  114. 177 case alt_proto
  115. when "h2c"
  116. 7 "http"
  117. when "h2"
  118. 49 "https"
  119. end
  120. end
  121. 26 def parse_altsvc_origin(alt_proto, alt_origin)
  122. 156 alt_scheme = parse_altsvc_scheme(alt_proto)
  123. 156 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

27 relevant lines. 27 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "forwardable"
  3. 26 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. 26 class Buffer
  13. 26 extend Forwardable
  14. 26 def_delegator :@buffer, :to_s
  15. 26 def_delegator :@buffer, :to_str
  16. 26 def_delegator :@buffer, :empty?
  17. 26 def_delegator :@buffer, :bytesize
  18. 26 def_delegator :@buffer, :clear
  19. 26 def_delegator :@buffer, :replace
  20. 26 attr_reader :limit
  21. 26 if RUBY_VERSION >= "3.4.0"
  22. 15 def initialize(limit)
  23. 3046 @buffer = String.new("", encoding: Encoding::BINARY, capacity: limit)
  24. 3046 @limit = limit
  25. end
  26. 15 def <<(chunk)
  27. 12970 @buffer.append_as_bytes(chunk)
  28. end
  29. else
  30. 11 def initialize(limit)
  31. 16919 @buffer = "".b
  32. 16919 @limit = limit
  33. end
  34. 11 def_delegator :@buffer, :<<
  35. end
  36. 26 def full?
  37. 52707 @buffer.bytesize >= @limit
  38. end
  39. 26 def capacity
  40. 12 @limit - @buffer.bytesize
  41. end
  42. 26 def shift!(fin)
  43. 17879 @buffer = @buffer.byteslice(fin..-1) || "".b
  44. end
  45. end
  46. end

lib/httpx/callbacks.rb

100.0% lines covered

19 relevant lines. 19 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 module HTTPX
  3. 26 module Callbacks
  4. 26 def on(type, &action)
  5. 332698 callbacks(type) << action
  6. 332698 action
  7. end
  8. 26 def once(type, &block)
  9. 185425 on(type) do |*args, &callback|
  10. 95425 block.call(*args, &callback)
  11. 95369 :delete
  12. end
  13. end
  14. 26 def emit(type, *args)
  15. 119331 log { "emit #{type.inspect} callbacks" } if respond_to?(:log)
  16. 253122 callbacks(type).delete_if { |pr| :delete == pr.call(*args) } # rubocop:disable Style/YodaCondition
  17. end
  18. 26 def callbacks_for?(type)
  19. 3063 @callbacks && @callbacks.key?(type) && @callbacks[type].any?
  20. end
  21. 26 protected
  22. 26 def callbacks(type = nil)
  23. 454747 return @callbacks unless type
  24. 675475 @callbacks ||= Hash.new { |h, k| h[k] = [] }
  25. 454670 @callbacks[type]
  26. end
  27. end
  28. 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. 26 module HTTPX
  3. # Session mixin, implements most of the APIs that the users call.
  4. # delegates to a default session when extended.
  5. 26 module Chainable
  6. 26 %w[head get post put delete trace options connect patch].each do |meth|
  7. 225 class_eval(<<-MOD, __FILE__, __LINE__ + 1)
  8. def #{meth}(*uri, **options) # def get(*uri, **options)
  9. 9 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. 26 def request(*args, **options)
  15. 2459 branch(default_options).request(*args, **options)
  16. end
  17. 26 def accept(type)
  18. 14 with(headers: { "accept" => String(type) })
  19. end
  20. # delegates to the default session (see HTTPX::Session#wrap).
  21. 26 def wrap(&blk)
  22. 78 branch(default_options).wrap(&blk)
  23. end
  24. # returns a new instance loaded with the +pl+ plugin and +options+.
  25. 26 def plugin(pl, options = nil, &blk)
  26. 4823 klass = is_a?(S) ? self.class : Session
  27. 4823 klass = Class.new(klass)
  28. 4823 klass.instance_variable_set(:@default_options, klass.default_options.merge(default_options))
  29. 4823 klass.plugin(pl, options, &blk).new
  30. end
  31. # returns a new instance loaded with +options+.
  32. 26 def with(options, &blk)
  33. 2547 branch(default_options.merge(options), &blk)
  34. end
  35. 26 private
  36. # returns default instance of HTTPX::Options.
  37. 26 def default_options
  38. 9956 @options || Session.default_options
  39. end
  40. # returns a default instance of HTTPX::Session.
  41. 26 def branch(options, &blk)
  42. 5070 return self.class.new(options, &blk) if is_a?(S)
  43. 2932 Session.new(options, &blk)
  44. end
  45. 26 def method_missing(meth, *args, **options, &blk)
  46. 652 case meth
  47. when /\Awith_(.+)/
  48. 644 option = Regexp.last_match(1)
  49. 644 return super unless option
  50. 644 with(option.to_sym => args.first || options)
  51. when /\Aon_(.+)/
  52. 8 callback = Regexp.last_match(1)
  53. 5 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. 2 ].include?(callback)
  59. 8 warn "DEPRECATION WARNING: calling `.#{meth}` on plain HTTPX sessions is deprecated. " \
  60. "Use `HTTPX.plugin(:callbacks).#{meth}` instead."
  61. 8 plugin(:callbacks).__send__(meth, *args, **options, &blk)
  62. else
  63. super
  64. end
  65. end
  66. 26 def respond_to_missing?(meth, *)
  67. 49 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. 10 %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. 3 ].include?(callback) || super
  79. else
  80. super
  81. end
  82. end
  83. end
  84. 26 extend Chainable
  85. end

lib/httpx/connection.rb

94.81% lines covered

482 relevant lines. 457 lines covered and 25 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "resolv"
  3. 26 require "forwardable"
  4. 26 require "httpx/io"
  5. 26 require "httpx/buffer"
  6. 26 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. 26 class Connection
  29. 26 extend Forwardable
  30. 26 include Loggable
  31. 26 include Callbacks
  32. 26 using URIExtensions
  33. 26 def_delegator :@io, :closed?
  34. 26 def_delegator :@write_buffer, :empty?
  35. 26 attr_reader :type, :io, :origin, :origins, :state, :pending, :options, :ssl_session, :sibling
  36. 26 attr_writer :current_selector
  37. 26 attr_accessor :current_session, :family
  38. 26 protected :ssl_session, :sibling
  39. 26 def initialize(uri, options)
  40. 832 @current_session = @current_selector =
  41. @parser = @sibling = @coalesced_connection =
  42. @family = @io = @ssl_session = @timeout =
  43. 5929 @connected_at = @response_received_at = nil
  44. 6761 @exhausted = @cloned = @main_sibling = false
  45. 6761 @options = Options.new(options)
  46. 6761 @type = initialize_type(uri, @options)
  47. 6761 @origins = [uri.origin]
  48. 6761 @origin = Utils.to_uri(uri.origin)
  49. 6761 @window_size = @options.window_size
  50. 6761 @read_buffer = Buffer.new(@options.buffer_size)
  51. 6761 @write_buffer = Buffer.new(@options.buffer_size)
  52. 6761 @pending = []
  53. 6761 @inflight = 0
  54. 6761 @keep_alive_timeout = @options.timeout[:keep_alive_timeout]
  55. 6761 on(:error, &method(:on_error))
  56. 6761 if @options.io
  57. # if there's an already open IO, get its
  58. # peer address, and force-initiate the parser
  59. 59 transition(:already_open)
  60. 59 @io = build_socket
  61. 59 parser
  62. else
  63. 6702 transition(:idle)
  64. end
  65. 6761 on(:close) do
  66. 6875 next if @exhausted # it'll reset
  67. # may be called after ":close" above, so after the connection has been checked back in.
  68. # next unless @current_session
  69. 6868 next unless @current_session
  70. 6868 @current_session.deselect_connection(self, @current_selector, @cloned)
  71. end
  72. 6761 on(:terminate) do
  73. 2561 next if @exhausted # it'll reset
  74. 2554 current_session = @current_session
  75. 2554 current_selector = @current_selector
  76. # may be called after ":close" above, so after the connection has been checked back in.
  77. 2554 next unless current_session && current_selector
  78. 14 current_session.deselect_connection(self, current_selector)
  79. end
  80. 6761 on(:altsvc) do |alt_origin, origin, alt_params|
  81. 7 build_altsvc_connection(alt_origin, origin, alt_params)
  82. end
  83. 6761 self.addresses = @options.addresses if @options.addresses
  84. end
  85. 26 def peer
  86. 13740 @origin
  87. end
  88. # this is a semi-private method, to be used by the resolver
  89. # to initiate the io object.
  90. 26 def addresses=(addrs)
  91. 6569 if @io
  92. 263 @io.add_addresses(addrs)
  93. else
  94. 6306 @io = build_socket(addrs)
  95. end
  96. end
  97. 26 def addresses
  98. 13147 @io && @io.addresses
  99. end
  100. 26 def addresses?
  101. 7295 @io && @io.addresses?
  102. end
  103. 26 def match?(uri, options)
  104. 1999 return false if !used? && (@state == :closing || @state == :closed)
  105. 156 (
  106. 1738 @origins.include?(uri.origin) &&
  107. # if there is more than one origin to match, it means that this connection
  108. # was the result of coalescing. To prevent blind trust in the case where the
  109. # origin came from an ORIGIN frame, we're going to verify the hostname with the
  110. # SSL certificate
  111. 1785 (@origins.size == 1 || @origin == uri.origin || (@io.is_a?(SSL) && @io.verify_hostname(uri.host)))
  112. ) && @options == options
  113. end
  114. 26 def mergeable?(connection)
  115. 362 return false if @state == :closing || @state == :closed || !@io
  116. 102 return false unless connection.addresses
  117. (
  118. 102 (open? && @origin == connection.origin) ||
  119. 102 !(@io.addresses & (connection.addresses || [])).empty?
  120. ) && @options == connection.options
  121. end
  122. # coalesces +self+ into +connection+.
  123. 26 def coalesce!(connection)
  124. 13 @coalesced_connection = connection
  125. 13 close_sibling
  126. 13 connection.merge(self)
  127. end
  128. # coalescable connections need to be mergeable!
  129. # but internally, #mergeable? is called before #coalescable?
  130. 26 def coalescable?(connection)
  131. 33 if @io.protocol == "h2" &&
  132. @origin.scheme == "https" &&
  133. connection.origin.scheme == "https" &&
  134. @io.can_verify_peer?
  135. 13 @io.verify_hostname(connection.origin.host)
  136. else
  137. 20 @origin == connection.origin
  138. end
  139. end
  140. 26 def create_idle(options = {})
  141. self.class.new(@origin, @options.merge(options))
  142. end
  143. 26 def merge(connection)
  144. 42 @origins |= connection.instance_variable_get(:@origins)
  145. 42 if @ssl_session.nil? && connection.ssl_session
  146. 12 @ssl_session = connection.ssl_session
  147. @io.session_new_cb do |sess|
  148. 18 @ssl_session = sess
  149. 12 end if @io
  150. end
  151. 42 connection.purge_pending do |req|
  152. 15 send(req)
  153. end
  154. end
  155. 26 def purge_pending(&block)
  156. 42 pendings = []
  157. 42 if @parser
  158. 21 @inflight -= @parser.pending.size
  159. 21 pendings << @parser.pending
  160. end
  161. 42 pendings << @pending
  162. 42 pendings.each do |pending|
  163. 63 pending.reject!(&block)
  164. end
  165. end
  166. 26 def io_connected?
  167. 8 return @coalesced_connection.io_connected? if @coalesced_connection
  168. 8 @io && @io.state == :connected
  169. end
  170. 26 def connecting?
  171. 8703931 @state == :idle
  172. end
  173. 26 def inflight?
  174. 2670 @parser && (
  175. # parser may be dealing with other requests (possibly started from a different fiber)
  176. 2194 !@parser.empty? ||
  177. # connection may be doing connection termination handshake
  178. !@write_buffer.empty?
  179. )
  180. end
  181. 26 def interests
  182. # connecting
  183. 8682237 if connecting?
  184. 10717 connect
  185. 10717 return @io.interests if connecting?
  186. end
  187. 8672057 return @parser.interests if @parser
  188. 16 nil
  189. rescue StandardError => e
  190. emit(:error, e)
  191. nil
  192. end
  193. 26 def to_io
  194. 24339 @io.to_io
  195. end
  196. 26 def call
  197. 23450 case @state
  198. when :idle
  199. 9968 connect
  200. # when opening the tcp or ssl socket fails
  201. 9954 return if @state == :closed
  202. 9931 consume
  203. when :closed
  204. return
  205. when :closing
  206. consume
  207. transition(:closed)
  208. when :open
  209. 13163 consume
  210. end
  211. 7603 nil
  212. rescue StandardError => e
  213. 16 @write_buffer.clear
  214. 16 emit(:error, e)
  215. 16 raise e
  216. end
  217. 26 def close
  218. 2510 transition(:active) if @state == :inactive
  219. 2510 @parser.close if @parser
  220. end
  221. 26 def terminate
  222. 2510 case @state
  223. when :idle
  224. purge_after_closed
  225. emit(:terminate)
  226. when :closed
  227. 7 @connected_at = nil
  228. end
  229. 2510 close
  230. end
  231. # bypasses the state machine to force closing of connections still connecting.
  232. # **only** used for Happy Eyeballs v2.
  233. 26 def force_reset(cloned = false)
  234. 283 @state = :closing
  235. 283 @cloned = cloned
  236. 283 transition(:closed)
  237. end
  238. 26 def reset
  239. 6789 return if @state == :closing || @state == :closed
  240. 6749 transition(:closing)
  241. 6749 transition(:closed)
  242. end
  243. 26 def send(request)
  244. 8252 return @coalesced_connection.send(request) if @coalesced_connection
  245. 8246 if @parser && !@write_buffer.full?
  246. 401 if @response_received_at && @keep_alive_timeout &&
  247. Utils.elapsed_time(@response_received_at) > @keep_alive_timeout
  248. # when pushing a request into an existing connection, we have to check whether there
  249. # is the possibility that the connection might have extended the keep alive timeout.
  250. # for such cases, we want to ping for availability before deciding to shovel requests.
  251. 18 log(level: 3) { "keep alive timeout expired, pinging connection..." }
  252. 18 @pending << request
  253. 18 transition(:active) if @state == :inactive
  254. 18 parser.ping
  255. 18 request.ping!
  256. 18 return
  257. end
  258. 383 send_request_to_parser(request)
  259. else
  260. 7845 @pending << request
  261. end
  262. end
  263. 26 def timeout
  264. 8573529 return if @state == :closed || @state == :inactive
  265. 8573529 return @timeout if @timeout
  266. 8558348 return @options.timeout[:connect_timeout] if @state == :idle
  267. 8558348 @options.timeout[:operation_timeout]
  268. end
  269. 26 def idling
  270. 759 purge_after_closed
  271. 759 @write_buffer.clear
  272. 759 transition(:idle)
  273. 759 @parser = nil if @parser
  274. end
  275. 26 def used?
  276. 2191 @connected_at
  277. end
  278. 26 def deactivate
  279. 401 transition(:inactive)
  280. end
  281. 26 def open?
  282. 6617 @state == :open || @state == :inactive
  283. end
  284. 26 def handle_socket_timeout(interval)
  285. 40 error = OperationTimeoutError.new(interval, "timed out while waiting on select")
  286. 40 error.set_backtrace(caller)
  287. 40 on_error(error)
  288. end
  289. 26 def sibling=(connection)
  290. 40 @sibling = connection
  291. 40 return unless connection
  292. 16 @main_sibling = connection.sibling.nil?
  293. 16 return unless @main_sibling
  294. 8 connection.sibling = self
  295. end
  296. 26 def handle_connect_error(error)
  297. 271 return handle_error(error) unless @sibling && @sibling.connecting?
  298. 7 @sibling.merge(self)
  299. 7 force_reset(true)
  300. end
  301. 26 def disconnect
  302. 7003 return unless @current_session && @current_selector
  303. 6875 emit(:close)
  304. 6861 @current_session = @current_selector = nil
  305. end
  306. skipped # :nocov:
  307. skipped def inspect
  308. skipped "#<#{self.class}:#{object_id} " \
  309. skipped "@origin=#{@origin} " \
  310. skipped "@state=#{@state} " \
  311. skipped "@pending=#{@pending.size} " \
  312. skipped "@io=#{@io}>"
  313. skipped end
  314. skipped # :nocov:
  315. 26 private
  316. 26 def connect
  317. 19733 transition(:open)
  318. end
  319. 26 def consume
  320. 26108 return unless @io
  321. 26108 catch(:called) do
  322. 26108 epiped = false
  323. 26108 loop do
  324. # connection may have
  325. 39349 return if @state == :idle
  326. 36078 parser.consume
  327. # we exit if there's no more requests to process
  328. #
  329. # this condition takes into account:
  330. #
  331. # * the number of inflight requests
  332. # * the number of pending requests
  333. # * whether the write buffer has bytes (i.e. for close handshake)
  334. 36064 if @pending.empty? && @inflight.zero? && @write_buffer.empty?
  335. 2574 log(level: 3) { "NO MORE REQUESTS..." }
  336. 2560 return
  337. end
  338. 33504 @timeout = @current_timeout
  339. 33504 read_drained = false
  340. 33504 write_drained = nil
  341. #
  342. # tight read loop.
  343. #
  344. # read as much of the socket as possible.
  345. #
  346. # this tight loop reads all the data it can from the socket and pipes it to
  347. # its parser.
  348. #
  349. 5325 loop do
  350. 51355 siz = @io.read(@window_size, @read_buffer)
  351. 51509 log(level: 3, color: :cyan) { "IO READ: #{siz} bytes... (wsize: #{@window_size}, rbuffer: #{@read_buffer.bytesize})" }
  352. 51353 unless siz
  353. 14 @write_buffer.clear
  354. 14 ex = EOFError.new("descriptor closed")
  355. 14 ex.set_backtrace(caller)
  356. 14 on_error(ex)
  357. 14 return
  358. end
  359. # socket has been drained. mark and exit the read loop.
  360. 51339 if siz.zero?
  361. 12696 read_drained = @read_buffer.empty?
  362. 12696 epiped = false
  363. 12696 break
  364. end
  365. 38643 parser << @read_buffer.to_s
  366. # continue reading if possible.
  367. 34618 break if interests == :w && !epiped
  368. # exit the read loop if connection is preparing to be closed
  369. 30241 break if @state == :closing || @state == :closed
  370. # exit #consume altogether if all outstanding requests have been dealt with
  371. 30197 return if @pending.empty? && @inflight.zero?
  372. 33504 end unless ((ints = interests).nil? || ints == :w || @state == :closing) && !epiped
  373. #
  374. # tight write loop.
  375. #
  376. # flush as many bytes as the sockets allow.
  377. #
  378. 3539 loop do
  379. # buffer has been drainned, mark and exit the write loop.
  380. 19822 if @write_buffer.empty?
  381. # we only mark as drained on the first loop
  382. 2664 write_drained = write_drained.nil? && @inflight.positive?
  383. 2664 break
  384. end
  385. 2135 begin
  386. 17158 siz = @io.write(@write_buffer)
  387. rescue Errno::EPIPE
  388. # this can happen if we still have bytes in the buffer to send to the server, but
  389. # the server wants to respond immediately with some message, or an error. An example is
  390. # when one's uploading a big file to an unintended endpoint, and the server stops the
  391. # consumption, and responds immediately with an authorization of even method not allowed error.
  392. # at this point, we have to let the connection switch to read-mode.
  393. 6 log(level: 2) { "pipe broken, could not flush buffer..." }
  394. 6 epiped = true
  395. 6 read_drained = false
  396. 6 break
  397. end
  398. 17235 log(level: 3, color: :cyan) { "IO WRITE: #{siz} bytes..." }
  399. 17151 unless siz
  400. @write_buffer.clear
  401. ex = EOFError.new("descriptor closed")
  402. ex.set_backtrace(caller)
  403. on_error(ex)
  404. return
  405. end
  406. # socket closed for writing. mark and exit the write loop.
  407. 17151 if siz.zero?
  408. 14 write_drained = !@write_buffer.empty?
  409. 14 break
  410. end
  411. # exit write loop if marked to consume from peer, or is closing.
  412. 17137 break if interests == :r || @state == :closing || @state == :closed
  413. 2863 write_drained = false
  414. 26605 end unless (ints = interests) == :r
  415. 26604 send_pending if @state == :open
  416. # return if socket is drained
  417. 26604 next unless (ints != :r || read_drained) && (ints != :w || write_drained)
  418. # gotta go back to the event loop. It happens when:
  419. #
  420. # * the socket is drained of bytes or it's not the interest of the conn to read;
  421. # * theres nothing more to write, or it's not in the interest of the conn to write;
  422. 13430 log(level: 3) { "(#{ints}): WAITING FOR EVENTS..." }
  423. 13363 return
  424. end
  425. end
  426. end
  427. 26 def send_pending
  428. 74086 while !@write_buffer.full? && (request = @pending.shift)
  429. 18069 send_request_to_parser(request)
  430. end
  431. end
  432. 26 def parser
  433. 101000 @parser ||= build_parser
  434. end
  435. 26 def send_request_to_parser(request)
  436. 18452 @inflight += 1
  437. 18452 request.peer_address = @io.ip && @io.ip.address
  438. 18452 set_request_timeouts(request)
  439. 18452 parser.send(request)
  440. 18452 return unless @state == :inactive
  441. 14 transition(:active)
  442. # mark request as ping, as this inactive connection may have been
  443. # closed by the server, and we don't want that to influence retry
  444. # bookkeeping.
  445. 14 request.ping!
  446. end
  447. 26 def build_parser(protocol = @io.protocol)
  448. 6792 parser = parser_type(protocol).new(@write_buffer, @options)
  449. 6792 set_parser_callbacks(parser)
  450. 6792 parser
  451. end
  452. 26 def set_parser_callbacks(parser)
  453. 6889 parser.on(:response) do |request, response|
  454. 7328 AltSvc.emit(request, response) do |alt_origin, origin, alt_params|
  455. 7 emit(:altsvc, alt_origin, origin, alt_params)
  456. end
  457. 7328 @response_received_at = Utils.now
  458. 7328 @inflight -= 1
  459. 7328 response.finish!
  460. 7328 request.emit(:response, response)
  461. end
  462. 6889 parser.on(:altsvc) do |alt_origin, origin, alt_params|
  463. emit(:altsvc, alt_origin, origin, alt_params)
  464. end
  465. 6889 parser.on(:pong, &method(:send_pending))
  466. 6889 parser.on(:promise) do |request, stream|
  467. 21 request.emit(:promise, parser, stream)
  468. end
  469. 6889 parser.on(:exhausted) do
  470. 7 @exhausted = true
  471. 7 current_session = @current_session
  472. 7 current_selector = @current_selector
  473. begin
  474. 7 parser.close
  475. 7 @pending.concat(parser.pending)
  476. ensure
  477. 7 @current_session = current_session
  478. 7 @current_selector = current_selector
  479. end
  480. 7 case @state
  481. when :closed
  482. 7 idling
  483. 7 @exhausted = false
  484. when :closing
  485. once(:closed) do
  486. idling
  487. @exhausted = false
  488. end
  489. end
  490. end
  491. 6889 parser.on(:origin) do |origin|
  492. @origins |= [origin]
  493. end
  494. 6889 parser.on(:close) do |force|
  495. 2561 if force
  496. 2561 reset
  497. 2554 emit(:terminate)
  498. end
  499. end
  500. 6889 parser.on(:close_handshake) do
  501. 7 consume
  502. end
  503. 6889 parser.on(:reset) do
  504. 3677 @pending.concat(parser.pending) unless parser.empty?
  505. 3677 current_session = @current_session
  506. 3677 current_selector = @current_selector
  507. 3677 reset
  508. 3670 unless @pending.empty?
  509. 184 idling
  510. 184 @current_session = current_session
  511. 184 @current_selector = current_selector
  512. end
  513. end
  514. 6889 parser.on(:current_timeout) do
  515. 2926 @current_timeout = @timeout = parser.timeout
  516. end
  517. 6889 parser.on(:timeout) do |tout|
  518. 2496 @timeout = tout
  519. end
  520. 6889 parser.on(:error) do |request, error|
  521. 67 case error
  522. when :http_1_1_required
  523. 14 current_session = @current_session
  524. 14 current_selector = @current_selector
  525. 14 parser.close
  526. 14 other_connection = current_session.find_connection(@origin, current_selector,
  527. @options.merge(ssl: { alpn_protocols: %w[http/1.1] }))
  528. 14 other_connection.merge(self)
  529. 14 request.transition(:idle)
  530. 14 other_connection.send(request)
  531. 14 next
  532. when OperationTimeoutError
  533. # request level timeouts should take precedence
  534. next unless request.active_timeouts.empty?
  535. end
  536. 53 @inflight -= 1
  537. 53 response = ErrorResponse.new(request, error)
  538. 53 request.response = response
  539. 53 request.emit(:response, response)
  540. end
  541. end
  542. 26 def transition(nextstate)
  543. 42957 handle_transition(nextstate)
  544. rescue Errno::ECONNABORTED,
  545. Errno::ECONNREFUSED,
  546. Errno::ECONNRESET,
  547. Errno::EADDRNOTAVAIL,
  548. Errno::EHOSTUNREACH,
  549. Errno::EINVAL,
  550. Errno::ENETUNREACH,
  551. Errno::EPIPE,
  552. Errno::ENOENT,
  553. SocketError,
  554. IOError => e
  555. # connect errors, exit gracefully
  556. 80 error = ConnectionError.new(e.message)
  557. 80 error.set_backtrace(e.backtrace)
  558. 80 handle_connect_error(error) if connecting?
  559. 80 @state = :closed
  560. 80 purge_after_closed
  561. 80 disconnect
  562. rescue TLSError, ::HTTP2::Error::ProtocolError, ::HTTP2::Error::HandshakeError => e
  563. # connect errors, exit gracefully
  564. 21 handle_error(e)
  565. 21 handle_connect_error(e) if connecting?
  566. 21 @state = :closed
  567. 21 purge_after_closed
  568. 21 disconnect
  569. end
  570. 26 def handle_transition(nextstate)
  571. 42502 case nextstate
  572. when :idle
  573. 7474 @timeout = @current_timeout = @options.timeout[:connect_timeout]
  574. 7474 @connected_at = @response_received_at = nil
  575. when :open
  576. 20046 return if @state == :closed
  577. 20046 @io.connect
  578. 19945 close_sibling if @io.state == :connected
  579. 19945 return unless @io.connected?
  580. 6816 @connected_at = Utils.now
  581. 6816 send_pending
  582. 6816 @timeout = @current_timeout = parser.timeout
  583. 6816 emit(:open)
  584. when :inactive
  585. 401 return unless @state == :open
  586. # do not deactivate connection in use
  587. 357 return if @inflight.positive? || @parser.waiting_for_ping?
  588. when :closing
  589. 6756 return unless @state == :idle || @state == :open
  590. 6756 unless @write_buffer.empty?
  591. # preset state before handshake, as error callbacks
  592. # may take it back here.
  593. 2502 @state = nextstate
  594. # handshakes, try sending
  595. 2502 consume
  596. 2502 @write_buffer.clear
  597. 2502 return
  598. end
  599. when :closed
  600. 7039 return unless @state == :closing
  601. 7039 return unless @write_buffer.empty?
  602. 7017 purge_after_closed
  603. 7017 disconnect if @pending.empty?
  604. when :already_open
  605. 59 nextstate = :open
  606. # the first check for given io readiness must still use a timeout.
  607. # connect is the reasonable choice in such a case.
  608. 59 @timeout = @options.timeout[:connect_timeout]
  609. 59 send_pending
  610. when :active
  611. 188 return unless @state == :inactive
  612. 188 nextstate = :open
  613. # activate
  614. 188 @current_session.select_connection(self, @current_selector)
  615. end
  616. 26898 log(level: 3) { "#{@state} -> #{nextstate}" }
  617. 26676 @state = nextstate
  618. end
  619. 26 def close_sibling
  620. 9292 return unless @sibling
  621. 8 if @sibling.io_connected?
  622. reset
  623. # TODO: transition connection to closed
  624. end
  625. 8 unless @sibling.state == :closed
  626. 1 merge(@sibling) unless @main_sibling
  627. 1 @sibling.force_reset(true)
  628. end
  629. 8 @sibling = nil
  630. end
  631. 26 def purge_after_closed
  632. 7883 @io.close if @io
  633. 7883 @read_buffer.clear
  634. 7883 @timeout = nil
  635. end
  636. 26 def initialize_type(uri, options)
  637. 6432 options.transport || begin
  638. 6408 case uri.scheme
  639. when "http"
  640. 3667 "tcp"
  641. when "https"
  642. 2741 "ssl"
  643. else
  644. raise UnsupportedSchemeError, "#{uri}: #{uri.scheme}: unsupported URI scheme"
  645. end
  646. end
  647. end
  648. # returns an HTTPX::Connection for the negotiated Alternative Service (or none).
  649. 26 def build_altsvc_connection(alt_origin, origin, alt_params)
  650. # do not allow security downgrades on altsvc negotiation
  651. 7 return if @origin.scheme == "https" && alt_origin.scheme != "https"
  652. 7 altsvc = AltSvc.cached_altsvc_set(origin, alt_params.merge("origin" => alt_origin))
  653. # altsvc already exists, somehow it wasn't advertised, probably noop
  654. 7 return unless altsvc
  655. 7 alt_options = @options.merge(ssl: @options.ssl.merge(hostname: URI(origin).host))
  656. 7 connection = @current_session.find_connection(alt_origin, @current_selector, alt_options)
  657. # advertised altsvc is the same origin being used, ignore
  658. 7 return if connection == self
  659. 7 connection.extend(AltSvc::ConnectionMixin) unless connection.is_a?(AltSvc::ConnectionMixin)
  660. 7 log(level: 1) { "#{origin} alt-svc: #{alt_origin}" }
  661. 7 connection.merge(self)
  662. 7 terminate
  663. rescue UnsupportedSchemeError
  664. altsvc["noop"] = true
  665. nil
  666. end
  667. 26 def build_socket(addrs = nil)
  668. 6365 case @type
  669. when "tcp"
  670. 3699 TCP.new(peer, addrs, @options)
  671. when "ssl"
  672. 2642 SSL.new(peer, addrs, @options) do |sock|
  673. 2622 sock.ssl_session = @ssl_session
  674. 2622 sock.session_new_cb do |sess|
  675. 4509 @ssl_session = sess
  676. 4509 sock.ssl_session = sess
  677. end
  678. end
  679. when "unix"
  680. 24 path = Array(addrs).first
  681. 24 path = String(path) if path
  682. 24 UNIX.new(peer, path, @options)
  683. else
  684. raise Error, "unsupported transport (#{@type})"
  685. end
  686. end
  687. 26 def on_error(error, request = nil)
  688. 542 if error.is_a?(OperationTimeoutError)
  689. # inactive connections do not contribute to the select loop, therefore
  690. # they should not fail due to such errors.
  691. 40 return if @state == :inactive
  692. 40 if @timeout
  693. 40 @timeout -= error.timeout
  694. 40 return unless @timeout <= 0
  695. end
  696. 28 error = error.to_connection_error if connecting?
  697. end
  698. 530 handle_error(error, request)
  699. 530 reset
  700. end
  701. 26 def handle_error(error, request = nil)
  702. 815 parser.handle_error(error, request) if @parser && parser.respond_to?(:handle_error)
  703. 1883 while (req = @pending.shift)
  704. 397 next if request && req == request
  705. 397 response = ErrorResponse.new(req, error)
  706. 397 req.response = response
  707. 383 req.emit(:response, response)
  708. end
  709. 801 return unless request
  710. 360 @inflight -= 1
  711. 360 response = ErrorResponse.new(request, error)
  712. 360 request.response = response
  713. 360 request.emit(:response, response)
  714. end
  715. 26 def set_request_timeouts(request)
  716. 18452 set_request_write_timeout(request)
  717. 18452 set_request_read_timeout(request)
  718. 18452 set_request_request_timeout(request)
  719. end
  720. 26 def set_request_read_timeout(request)
  721. 18452 read_timeout = request.read_timeout
  722. 18452 return if read_timeout.nil? || read_timeout.infinite?
  723. 18160 set_request_timeout(:read_timeout, request, read_timeout, :done, :response) do
  724. 14 read_timeout_callback(request, read_timeout)
  725. end
  726. end
  727. 26 def set_request_write_timeout(request)
  728. 18452 write_timeout = request.write_timeout
  729. 18452 return if write_timeout.nil? || write_timeout.infinite?
  730. 18452 set_request_timeout(:write_timeout, request, write_timeout, :headers, %i[done response]) do
  731. 14 write_timeout_callback(request, write_timeout)
  732. end
  733. end
  734. 26 def set_request_request_timeout(request)
  735. 18203 request_timeout = request.request_timeout
  736. 18203 return if request_timeout.nil? || request_timeout.infinite?
  737. 481 set_request_timeout(:request_timeout, request, request_timeout, :headers, :complete) do
  738. 333 read_timeout_callback(request, request_timeout, RequestTimeoutError)
  739. end
  740. end
  741. 26 def write_timeout_callback(request, write_timeout)
  742. 14 return if request.state == :done
  743. 14 @write_buffer.clear
  744. 14 error = WriteTimeoutError.new(request, nil, write_timeout)
  745. 14 on_error(error, request)
  746. end
  747. 26 def read_timeout_callback(request, read_timeout, error_type = ReadTimeoutError)
  748. 347 response = request.response
  749. 347 return if response && response.finished?
  750. 346 @write_buffer.clear
  751. 346 error = error_type.new(request, request.response, read_timeout)
  752. 346 on_error(error, request)
  753. end
  754. 26 def set_request_timeout(label, request, timeout, start_event, finish_events, &callback)
  755. 37163 request.set_timeout_callback(start_event) do
  756. 36988 timer = @current_selector.after(timeout, callback)
  757. 36988 request.active_timeouts << label
  758. 36988 Array(finish_events).each do |event|
  759. # clean up request timeouts if the connection errors out
  760. 55433 request.set_timeout_callback(event) do
  761. 54930 timer.cancel
  762. 54930 request.active_timeouts.delete(label)
  763. end
  764. end
  765. end
  766. end
  767. 26 def parser_type(protocol)
  768. 6918 case protocol
  769. 2920 when "h2" then @options.http2_class
  770. 3998 when "http/1.1" then @options.http1_class
  771. else
  772. raise Error, "unsupported protocol (##{protocol})"
  773. end
  774. end
  775. end
  776. end

lib/httpx/connection/http1.rb

89.59% lines covered

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

lib/httpx/connection/http2.rb

95.56% lines covered

270 relevant lines. 258 lines covered and 12 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "securerandom"
  3. 26 require "http/2"
  4. 26 module HTTPX
  5. 26 class Connection::HTTP2
  6. 26 include Callbacks
  7. 26 include Loggable
  8. 26 MAX_CONCURRENT_REQUESTS = ::HTTP2::DEFAULT_MAX_CONCURRENT_STREAMS
  9. 26 class Error < Error
  10. 26 def initialize(id, error)
  11. 54 super("stream #{id} closed with error: #{error}")
  12. end
  13. end
  14. 26 class PingError < Error
  15. 26 def initialize
  16. super(0, :ping_error)
  17. end
  18. end
  19. 26 class GoawayError < Error
  20. 26 def initialize(code = :no_error)
  21. 30 super(0, code)
  22. end
  23. end
  24. 26 attr_reader :streams, :pending
  25. 26 def initialize(buffer, options)
  26. 2961 @options = options
  27. 2961 @settings = @options.http2_settings
  28. 2961 @pending = []
  29. 2961 @streams = {}
  30. 2961 @drains = {}
  31. 2961 @pings = []
  32. 2961 @buffer = buffer
  33. 2961 @handshake_completed = false
  34. 2961 @wait_for_handshake = @settings.key?(:wait_for_handshake) ? @settings.delete(:wait_for_handshake) : true
  35. 2961 @max_concurrent_requests = @options.max_concurrent_requests || MAX_CONCURRENT_REQUESTS
  36. 2961 @max_requests = @options.max_requests
  37. 2961 init_connection
  38. end
  39. 26 def timeout
  40. 5846 return @options.timeout[:operation_timeout] if @handshake_completed
  41. 2920 @options.timeout[:settings_timeout]
  42. end
  43. 26 def interests
  44. 8631499 if @connection.state == :closed
  45. 7639 return unless @handshake_completed
  46. 7592 return if @buffer.empty?
  47. 4992 return :w
  48. end
  49. 8623860 unless @connection.state == :connected && @handshake_completed
  50. 17983 return @buffer.empty? ? :r : :rw
  51. end
  52. 8605877 unless @connection.send_buffer.empty?
  53. 20 return :rw unless @buffer.empty?
  54. # waiting for WINDOW_UPDATE frames
  55. 4 return :r
  56. end
  57. 8605857 return :w if !@pending.empty? && can_buffer_more_requests?
  58. 8605857 return :w unless @drains.empty?
  59. 8602301 if @buffer.empty?
  60. 8593950 return if @streams.empty? && @pings.empty?
  61. 42532 :r
  62. else
  63. 8351 :w
  64. end
  65. end
  66. 26 def close
  67. 2503 unless @connection.state == :closed
  68. 2496 @connection.goaway
  69. 2496 emit(:timeout, @options.timeout[:close_handshake_timeout])
  70. end
  71. 2503 emit(:close, true)
  72. end
  73. 26 def empty?
  74. 2497 @connection.state == :closed || @streams.empty?
  75. end
  76. 26 def exhausted?
  77. 2963 !@max_requests.positive?
  78. end
  79. 26 def <<(data)
  80. 31818 @connection << data
  81. end
  82. 26 def send(request, head = false)
  83. 6460 unless can_buffer_more_requests?
  84. 3127 head ? @pending.unshift(request) : @pending << request
  85. 3127 return false
  86. end
  87. 3333 unless (stream = @streams[request])
  88. 3333 stream = @connection.new_stream
  89. 3333 handle_stream(stream, request)
  90. 3333 @streams[request] = stream
  91. 3333 @max_requests -= 1
  92. end
  93. 3333 handle(request, stream)
  94. 3319 true
  95. rescue ::HTTP2::Error::StreamLimitExceeded
  96. @pending.unshift(request)
  97. false
  98. end
  99. 26 def consume
  100. 20095 @streams.each do |request, stream|
  101. 9158 next unless request.can_buffer?
  102. 1033 handle(request, stream)
  103. end
  104. end
  105. 26 def handle_error(ex, request = nil)
  106. 242 if ex.is_a?(OperationTimeoutError) && !@handshake_completed && @connection.state != :closed
  107. 7 @connection.goaway(:settings_timeout, "closing due to settings timeout")
  108. 7 emit(:close_handshake)
  109. 7 settings_ex = SettingsTimeoutError.new(ex.timeout, ex.message)
  110. 7 settings_ex.set_backtrace(ex.backtrace)
  111. 7 ex = settings_ex
  112. end
  113. 242 @streams.each_key do |req|
  114. 197 next if request && request == req
  115. 15 emit(:error, req, ex)
  116. end
  117. 490 while (req = @pending.shift)
  118. 38 next if request && request == req
  119. 38 emit(:error, req, ex)
  120. end
  121. end
  122. 26 def ping
  123. 18 ping = SecureRandom.gen_random(8)
  124. 18 @connection.ping(ping.dup)
  125. ensure
  126. 18 @pings << ping
  127. end
  128. 26 def waiting_for_ping?
  129. 341 @pings.any?
  130. end
  131. 26 private
  132. 26 def can_buffer_more_requests?
  133. 7175 (@handshake_completed || !@wait_for_handshake) &&
  134. @streams.size < @max_concurrent_requests &&
  135. @streams.size < @max_requests
  136. end
  137. 26 def send_pending
  138. 8059 while (request = @pending.shift)
  139. 3015 break unless send(request, true)
  140. end
  141. end
  142. 26 def handle(request, stream)
  143. 4492 catch(:buffer_full) do
  144. 4492 request.transition(:headers)
  145. 4485 join_headers(stream, request) if request.state == :headers
  146. 4485 request.transition(:body)
  147. 4485 join_body(stream, request) if request.state == :body
  148. 3471 request.transition(:trailers)
  149. 3471 join_trailers(stream, request) if request.state == :trailers && !request.body.empty?
  150. 3471 request.transition(:done)
  151. end
  152. end
  153. 26 def init_connection
  154. 2961 @connection = ::HTTP2::Client.new(@settings)
  155. 2961 @connection.on(:frame, &method(:on_frame))
  156. 2961 @connection.on(:frame_sent, &method(:on_frame_sent))
  157. 2961 @connection.on(:frame_received, &method(:on_frame_received))
  158. 2961 @connection.on(:origin, &method(:on_origin))
  159. 2961 @connection.on(:promise, &method(:on_promise))
  160. 2961 @connection.on(:altsvc) { |frame| on_altsvc(frame[:origin], frame) }
  161. 2961 @connection.on(:settings_ack, &method(:on_settings))
  162. 2961 @connection.on(:ack, &method(:on_pong))
  163. 2961 @connection.on(:goaway, &method(:on_close))
  164. #
  165. # Some servers initiate HTTP/2 negotiation right away, some don't.
  166. # As such, we have to check the socket buffer. If there is something
  167. # to read, the server initiated the negotiation. If not, we have to
  168. # initiate it.
  169. #
  170. 2961 @connection.send_connection_preface
  171. end
  172. 26 alias_method :reset, :init_connection
  173. 26 public :reset
  174. 26 def handle_stream(stream, request)
  175. 3347 request.on(:refuse, &method(:on_stream_refuse).curry(3)[stream, request])
  176. 3347 stream.on(:close, &method(:on_stream_close).curry(3)[stream, request])
  177. 3347 stream.on(:half_close) do
  178. 3316 log(level: 2) { "#{stream.id}: waiting for response..." }
  179. end
  180. 3347 stream.on(:altsvc, &method(:on_altsvc).curry(2)[request.origin])
  181. 3347 stream.on(:headers, &method(:on_stream_headers).curry(3)[stream, request])
  182. 3347 stream.on(:data, &method(:on_stream_data).curry(3)[stream, request])
  183. end
  184. 26 def set_protocol_headers(request)
  185. {
  186. 3325 ":scheme" => request.scheme,
  187. ":method" => request.verb,
  188. ":path" => request.path,
  189. ":authority" => request.authority,
  190. }
  191. end
  192. 26 def join_headers(stream, request)
  193. 3326 extra_headers = set_protocol_headers(request)
  194. 3326 if request.headers.key?("host")
  195. 7 log { "forbidden \"host\" header found (#{log_redact_headers(request.headers["host"])}), will use it as authority..." }
  196. 7 extra_headers[":authority"] = request.headers["host"]
  197. end
  198. 3326 log(level: 1, color: :yellow) do
  199. 126 "\n#{request.headers.merge(extra_headers).each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{log_redact_headers(v)}" }.join("\n")}"
  200. end
  201. 3326 stream.headers(request.headers.each(extra_headers), end_stream: request.body.empty?)
  202. end
  203. 26 def join_trailers(stream, request)
  204. 1393 unless request.trailers?
  205. 1386 stream.data("", end_stream: true) if request.callbacks_for?(:trailers)
  206. 1386 return
  207. end
  208. 7 log(level: 1, color: :yellow) do
  209. 14 request.trailers.each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{log_redact_headers(v)}" }.join("\n")
  210. end
  211. 7 stream.headers(request.trailers.each, end_stream: true)
  212. end
  213. 26 def join_body(stream, request)
  214. 4327 return if request.body.empty?
  215. 2408 chunk = @drains.delete(request) || request.drain_body
  216. 2408 while chunk
  217. 2593 next_chunk = request.drain_body
  218. 2593 send_chunk(request, stream, chunk, next_chunk)
  219. 2509 if next_chunk && (@buffer.full? || request.body.unbounded_body?)
  220. 930 @drains[request] = next_chunk
  221. 930 throw(:buffer_full)
  222. end
  223. 1579 chunk = next_chunk
  224. end
  225. 1394 return unless (error = request.drain_error)
  226. 24 on_stream_refuse(stream, request, error)
  227. end
  228. 26 def send_chunk(request, stream, chunk, next_chunk)
  229. 2614 log(level: 1, color: :green) { "#{stream.id}: -> DATA: #{chunk.bytesize} bytes..." }
  230. 2614 log(level: 2, color: :green) { "#{stream.id}: -> #{log_redact_body(chunk.inspect)}" }
  231. 2593 stream.data(chunk, end_stream: end_stream?(request, next_chunk))
  232. end
  233. 26 def end_stream?(request, next_chunk)
  234. 2509 !(next_chunk || request.trailers? || request.callbacks_for?(:trailers))
  235. end
  236. ######
  237. # HTTP/2 Callbacks
  238. ######
  239. 26 def on_stream_headers(stream, request, h)
  240. 3292 response = request.response
  241. 3292 if response.is_a?(Response) && response.version == "2.0"
  242. 114 on_stream_trailers(stream, response, h)
  243. 114 return
  244. end
  245. 3178 log(color: :yellow) do
  246. 126 h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{log_redact_headers(v)}" }.join("\n")
  247. end
  248. 3178 _, status = h.shift
  249. 3178 headers = request.options.headers_class.new(h)
  250. 3178 response = request.options.response_class.new(request, status, "2.0", headers)
  251. 3178 request.response = response
  252. 3171 @streams[request] = stream
  253. 3171 handle(request, stream) if request.expects?
  254. end
  255. 26 def on_stream_trailers(stream, response, h)
  256. 114 log(color: :yellow) do
  257. h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{log_redact_headers(v)}" }.join("\n")
  258. end
  259. 114 response.merge_headers(h)
  260. end
  261. 26 def on_stream_data(stream, request, data)
  262. 6054 log(level: 1, color: :green) { "#{stream.id}: <- DATA: #{data.bytesize} bytes..." }
  263. 6054 log(level: 2, color: :green) { "#{stream.id}: <- #{log_redact_body(data.inspect)}" }
  264. 6035 request.response << data
  265. end
  266. 26 def on_stream_refuse(stream, request, error)
  267. 24 on_stream_close(stream, request, error)
  268. 24 stream.close
  269. end
  270. 26 def on_stream_close(stream, request, error)
  271. 3122 return if error == :stream_closed && !@streams.key?(request)
  272. 3112 log(level: 2) { "#{stream.id}: closing stream" }
  273. 3098 teardown(request)
  274. 3098 if error
  275. 24 case error
  276. when :http_1_1_required
  277. emit(:error, request, error)
  278. else
  279. 24 ex = Error.new(stream.id, error)
  280. 24 ex.set_backtrace(caller)
  281. 24 response = ErrorResponse.new(request, ex)
  282. 24 request.response = response
  283. 24 emit(:response, request, response)
  284. end
  285. else
  286. 3074 response = request.response
  287. 3074 if response && response.is_a?(Response) && response.status == 421
  288. 7 emit(:error, request, :http_1_1_required)
  289. else
  290. 3067 emit(:response, request, response)
  291. end
  292. end
  293. 3091 send(@pending.shift) unless @pending.empty?
  294. 3091 return unless @streams.empty? && exhausted?
  295. 7 if @pending.empty?
  296. close
  297. else
  298. 7 emit(:exhausted)
  299. end
  300. end
  301. 26 def on_frame(bytes)
  302. 18461 @buffer << bytes
  303. end
  304. 26 def on_settings(*)
  305. 2926 @handshake_completed = true
  306. 2926 emit(:current_timeout)
  307. 2926 @max_concurrent_requests = [@max_concurrent_requests, @connection.remote_settings[:settings_max_concurrent_streams]].min
  308. 2926 send_pending
  309. end
  310. 26 def on_close(_last_frame, error, _payload)
  311. 37 is_connection_closed = @connection.state == :closed
  312. 37 if error
  313. 37 @buffer.clear if is_connection_closed
  314. 37 case error
  315. when :http_1_1_required
  316. 19 while (request = @pending.shift)
  317. 7 emit(:error, request, error)
  318. end
  319. else
  320. 30 ex = GoawayError.new(error)
  321. 30 @pending.unshift(*@streams.keys)
  322. 30 teardown
  323. end
  324. 37 if ex
  325. 30 ex.set_backtrace(caller)
  326. 30 handle_error(ex)
  327. end
  328. end
  329. 37 return unless is_connection_closed && @streams.empty?
  330. 37 emit(:close, is_connection_closed)
  331. end
  332. 26 def on_frame_sent(frame)
  333. 15575 log(level: 2) { "#{frame[:stream]}: frame was sent!" }
  334. 15491 log(level: 2, color: :blue) do
  335. payload =
  336. 83 case frame[:type]
  337. when :data
  338. 21 frame.merge(payload: frame[:payload].bytesize)
  339. when :headers, :ping
  340. 21 frame.merge(payload: log_redact_headers(frame[:payload]))
  341. else
  342. 42 frame
  343. end
  344. 84 "#{frame[:stream]}: #{payload}"
  345. end
  346. end
  347. 26 def on_frame_received(frame)
  348. 16542 log(level: 2) { "#{frame[:stream]}: frame was received!" }
  349. 16481 log(level: 2, color: :magenta) do
  350. payload =
  351. 60 case frame[:type]
  352. when :data
  353. 19 frame.merge(payload: frame[:payload].bytesize)
  354. when :headers, :ping
  355. 14 frame.merge(payload: log_redact_headers(frame[:payload]))
  356. else
  357. 28 frame
  358. end
  359. 61 "#{frame[:stream]}: #{payload}"
  360. end
  361. end
  362. 26 def on_altsvc(origin, frame)
  363. log(level: 2) { "#{frame[:stream]}: altsvc frame was received" }
  364. log(level: 2) { "#{frame[:stream]}: #{log_redact_headers(frame.inspect)}" }
  365. alt_origin = URI.parse("#{frame[:proto]}://#{frame[:host]}:#{frame[:port]}")
  366. params = { "ma" => frame[:max_age] }
  367. emit(:altsvc, origin, alt_origin, origin, params)
  368. end
  369. 26 def on_promise(stream)
  370. 21 emit(:promise, @streams.key(stream.parent), stream)
  371. end
  372. 26 def on_origin(origin)
  373. emit(:origin, origin)
  374. end
  375. 26 def on_pong(ping)
  376. 7 raise PingError unless @pings.delete(ping.to_s)
  377. 7 emit(:pong)
  378. end
  379. 26 def teardown(request = nil)
  380. 3128 if request
  381. 3098 @drains.delete(request)
  382. 3098 @streams.delete(request)
  383. else
  384. 30 @drains.clear
  385. 30 @streams.clear
  386. end
  387. end
  388. end
  389. 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. 26 require "ipaddr"
  28. 26 module HTTPX
  29. # Represents a domain name ready for extracting its registered domain
  30. # and TLD.
  31. 26 class DomainName
  32. 26 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. 26 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. 26 attr_reader :domain
  47. 26 class << self
  48. 26 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. 26 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. 26 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. 26 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. 26 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.67% lines covered

43 relevant lines. 42 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 module HTTPX
  3. # the default exception class for exceptions raised by HTTPX.
  4. 26 class Error < StandardError; end
  5. 26 class UnsupportedSchemeError < Error; end
  6. 26 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. 26 class TimeoutError < Error
  10. # The timeout value which caused this error to be raised.
  11. 26 attr_reader :timeout
  12. # initializes the timeout exception with the +timeout+ causing the error, and the
  13. # error +message+ for it.
  14. 26 def initialize(timeout, message)
  15. 473 @timeout = timeout
  16. 473 super(message)
  17. end
  18. # clones this error into a HTTPX::ConnectionTimeoutError.
  19. 26 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. # Raise when it can't acquire a connection from the pool.
  26. 26 class PoolTimeoutError < TimeoutError; end
  27. # Error raised when there was a timeout establishing the connection to a server.
  28. # This may be raised due to timeouts during TCP and TLS (when applicable) connection
  29. # establishment.
  30. 26 class ConnectTimeoutError < TimeoutError; end
  31. # Error raised when there was a timeout while sending a request, or receiving a response
  32. # from the server.
  33. 26 class RequestTimeoutError < TimeoutError
  34. # The HTTPX::Request request object this exception refers to.
  35. 26 attr_reader :request
  36. # initializes the exception with the +request+ and +response+ it refers to, and the
  37. # +timeout+ causing the error, and the
  38. 26 def initialize(request, response, timeout)
  39. 360 @request = request
  40. 360 @response = response
  41. 360 super(timeout, "Timed out after #{timeout} seconds")
  42. end
  43. 26 def marshal_dump
  44. [message]
  45. end
  46. end
  47. # Error raised when there was a timeout while receiving a response from the server.
  48. 26 class ReadTimeoutError < RequestTimeoutError; end
  49. # Error raised when there was a timeout while sending a request from the server.
  50. 26 class WriteTimeoutError < RequestTimeoutError; end
  51. # Error raised when there was a timeout while waiting for the HTTP/2 settings frame from the server.
  52. 26 class SettingsTimeoutError < TimeoutError; end
  53. # Error raised when there was a timeout while resolving a domain to an IP.
  54. 26 class ResolveTimeoutError < TimeoutError; end
  55. # Error raise when there was a timeout waiting for readiness of the socket the request is related to.
  56. 26 class OperationTimeoutError < TimeoutError; end
  57. # Error raised when there was an error while resolving a domain to an IP.
  58. 26 class ResolveError < Error; end
  59. # Error raised when there was an error while resolving a domain to an IP
  60. # using a HTTPX::Resolver::Native resolver.
  61. 26 class NativeResolveError < ResolveError
  62. 26 attr_reader :host
  63. 26 attr_accessor :connection
  64. # initializes the exception with the +connection+ it refers to, the +host+ domain
  65. # which failed to resolve, and the error +message+.
  66. 26 def initialize(connection, host, message = "Can't resolve #{host}")
  67. 128 @connection = connection
  68. 128 @host = host
  69. 128 super(message)
  70. end
  71. end
  72. # The exception class for HTTP responses with 4xx or 5xx status.
  73. 26 class HTTPError < Error
  74. # The HTTPX::Response response object this exception refers to.
  75. 26 attr_reader :response
  76. # Creates the instance and assigns the HTTPX::Response +response+.
  77. 26 def initialize(response)
  78. 78 @response = response
  79. 78 super("HTTP Error: #{@response.status} #{@response.headers}\n#{@response.body}")
  80. end
  81. # The HTTP response status.
  82. #
  83. # error.status #=> 404
  84. 26 def status
  85. 14 @response.status
  86. end
  87. end
  88. 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. 26 require "uri"
  3. 26 module HTTPX
  4. 26 module ArrayExtensions
  5. 26 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. 25 end unless Array.method_defined?(:filter_map)
  16. end
  17. 26 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. 25 end unless Array.method_defined?(:intersect?)
  29. end
  30. end
  31. 26 module URIExtensions
  32. # uri 0.11 backport, ships with ruby 3.1
  33. 26 refine URI::Generic do
  34. 26 def non_ascii_hostname
  35. 420 @non_ascii_hostname
  36. end
  37. 26 def non_ascii_hostname=(hostname)
  38. 28 @non_ascii_hostname = hostname
  39. end
  40. def authority
  41. 5825 return host if port == default_port
  42. 650 "#{host}:#{port}"
  43. 25 end unless URI::HTTP.method_defined?(:authority)
  44. def origin
  45. 4739 "#{scheme}://#{authority}"
  46. 25 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. 26 module HTTPX
  3. 26 class Headers
  4. 26 class << self
  5. 26 def new(headers = nil)
  6. 23646 return headers if headers.is_a?(self)
  7. 10759 super
  8. end
  9. end
  10. 26 def initialize(headers = nil)
  11. 10759 if headers.nil? || headers.empty?
  12. 1572 @headers = headers.to_h
  13. 1572 return
  14. end
  15. 9187 @headers = {}
  16. 9187 headers.each do |field, value|
  17. 56630 field = downcased(field)
  18. 56630 value = array_value(value)
  19. 56630 current = @headers[field]
  20. 56630 if current.nil?
  21. 56582 @headers[field] = value
  22. else
  23. 48 current.concat(value)
  24. end
  25. end
  26. end
  27. # cloned initialization
  28. 26 def initialize_clone(orig, **kwargs)
  29. 7 super
  30. 7 @headers = orig.instance_variable_get(:@headers).clone(**kwargs)
  31. end
  32. # dupped initialization
  33. 26 def initialize_dup(orig)
  34. 18261 super
  35. 18261 @headers = orig.instance_variable_get(:@headers).dup
  36. end
  37. # freezes the headers hash
  38. 26 def freeze
  39. 18897 @headers.freeze
  40. 18897 super
  41. end
  42. # merges headers with another header-quack.
  43. # the merge rule is, if the header already exists,
  44. # ignore what the +other+ headers has. Otherwise, set
  45. #
  46. 26 def merge(other)
  47. 4496 headers = dup
  48. 4496 other.each do |field, value|
  49. 12446 headers[downcased(field)] = value
  50. end
  51. 4496 headers
  52. end
  53. # returns the comma-separated values of the header field
  54. # identified by +field+, or nil otherwise.
  55. #
  56. 26 def [](field)
  57. 58791 a = @headers[downcased(field)] || return
  58. 24547 a.join(", ")
  59. end
  60. # sets +value+ (if not nil) as single value for the +field+ header.
  61. #
  62. 26 def []=(field, value)
  63. 22571 return unless value
  64. 22571 @headers[downcased(field)] = array_value(value)
  65. end
  66. # deletes all values associated with +field+ header.
  67. #
  68. 26 def delete(field)
  69. 261 canonical = downcased(field)
  70. 261 @headers.delete(canonical) if @headers.key?(canonical)
  71. end
  72. # adds additional +value+ to the existing, for header +field+.
  73. #
  74. 26 def add(field, value)
  75. 518 (@headers[downcased(field)] ||= []) << String(value)
  76. end
  77. # helper to be used when adding an header field as a value to another field
  78. #
  79. # h2_headers.add_header("vary", "accept-encoding")
  80. # h2_headers["vary"] #=> "accept-encoding"
  81. # h1_headers.add_header("vary", "accept-encoding")
  82. # h1_headers["vary"] #=> "Accept-Encoding"
  83. #
  84. 26 alias_method :add_header, :add
  85. # returns the enumerable headers store in pairs of header field + the values in
  86. # the comma-separated string format
  87. #
  88. 26 def each(extra_headers = nil)
  89. 62242 return enum_for(__method__, extra_headers) { @headers.size } unless block_given?
  90. 33202 @headers.each do |field, value|
  91. 112831 yield(field, value.join(", ")) unless value.empty?
  92. end
  93. 5210 extra_headers.each do |field, value|
  94. 22501 yield(field, value) unless value.empty?
  95. 33201 end if extra_headers
  96. end
  97. 26 def ==(other)
  98. 19372 other == to_hash
  99. end
  100. 26 def empty?
  101. 280 @headers.empty?
  102. end
  103. # the headers store in Hash format
  104. 26 def to_hash
  105. 20921 Hash[to_a]
  106. end
  107. 26 alias_method :to_h, :to_hash
  108. # the headers store in array of pairs format
  109. 26 def to_a
  110. 20941 Array(each)
  111. end
  112. # headers as string
  113. 26 def to_s
  114. 1762 @headers.to_s
  115. end
  116. skipped # :nocov:
  117. skipped def inspect
  118. skipped "#<#{self.class}:#{object_id} " \
  119. skipped "#{to_hash.inspect}>"
  120. skipped end
  121. skipped # :nocov:
  122. # this is internal API and doesn't abide to other public API
  123. # guarantees, like downcasing strings.
  124. # Please do not use this outside of core!
  125. #
  126. 26 def key?(downcased_key)
  127. 66891 @headers.key?(downcased_key)
  128. end
  129. # returns the values for the +field+ header in array format.
  130. # This method is more internal, and for this reason doesn't try
  131. # to "correct" the user input, i.e. it doesn't downcase the key.
  132. #
  133. 26 def get(field)
  134. 243 @headers[field] || EMPTY
  135. end
  136. 26 private
  137. 26 def array_value(value)
  138. 79201 Array(value)
  139. end
  140. 26 def downcased(field)
  141. 151217 String(field).downcase
  142. end
  143. end
  144. 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. 26 require "socket"
  3. 26 require "httpx/io/udp"
  4. 26 require "httpx/io/tcp"
  5. 26 require "httpx/io/unix"
  6. begin
  7. 26 require "httpx/io/ssl"
  8. rescue LoadError
  9. end

lib/httpx/io/ssl.rb

97.5% lines covered

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

lib/httpx/io/tcp.rb

92.19% lines covered

128 relevant lines. 118 lines covered and 10 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "resolv"
  3. 26 module HTTPX
  4. 26 class TCP
  5. 26 include Loggable
  6. 26 using URIExtensions
  7. 26 attr_reader :ip, :port, :addresses, :state, :interests
  8. 26 alias_method :host, :ip
  9. 26 def initialize(origin, addresses, options)
  10. 6485 @state = :idle
  11. 6485 @keep_open = false
  12. 6485 @addresses = []
  13. 6485 @ip_index = -1
  14. 6485 @ip = nil
  15. 6485 @hostname = origin.host
  16. 6485 @options = options
  17. 6485 @fallback_protocol = @options.fallback_protocol
  18. 6485 @port = origin.port
  19. 6485 @interests = :w
  20. 6485 if @options.io
  21. 47 @io = case @options.io
  22. when Hash
  23. 14 @options.io[origin.authority]
  24. else
  25. 33 @options.io
  26. end
  27. 47 raise Error, "Given IO objects do not match the request authority" unless @io
  28. 47 _, _, _, ip = @io.addr
  29. 47 @ip = Resolver::Entry.new(ip)
  30. 47 @addresses << @ip
  31. 47 @keep_open = true
  32. 47 @state = :connected
  33. else
  34. 6438 add_addresses(addresses)
  35. end
  36. 6485 @ip_index = @addresses.size - 1
  37. end
  38. 26 def socket
  39. 171 @io
  40. end
  41. 26 def add_addresses(addrs)
  42. 6736 return if addrs.empty?
  43. 6729 ip_index = @ip_index || (@addresses.size - 1)
  44. 6729 if addrs.first.ipv6?
  45. # should be the next in line
  46. 307 @addresses = [*@addresses[0, ip_index], *addrs, *@addresses[ip_index..-1]]
  47. else
  48. 6422 @addresses.unshift(*addrs)
  49. end
  50. 6729 @ip_index += addrs.size
  51. end
  52. # eliminates expired entries and returns whether there are still any left.
  53. 26 def addresses?
  54. 594 prev_addr_size = @addresses.size
  55. 594 @addresses.delete_if(&:expired?).sort! do |addr1, addr2|
  56. 666 if addr1.ipv6?
  57. addr2.ipv6? ? 0 : 1
  58. else
  59. 666 addr2.ipv6? ? -1 : 0
  60. end
  61. end
  62. 594 @ip_index = @addresses.size - 1 if prev_addr_size != @addresses.size
  63. 594 @addresses.any?
  64. end
  65. 26 def to_io
  66. 24470 @io.to_io
  67. end
  68. 26 def protocol
  69. 4056 @fallback_protocol
  70. end
  71. 26 def connect
  72. 25755 return unless closed?
  73. 25643 if @addresses.empty?
  74. # an idle connection trying to connect with no available addresses is a connection
  75. # out of the initial context which is back to the DNS resolution loop. This may
  76. # happen in a fiber-aware context where a connection reconnects with expired addresses,
  77. # and context is passed back to a fiber on the same connection while waiting for the
  78. # DNS answer.
  79. log { "tried connecting while resolving, skipping..." }
  80. return
  81. end
  82. 25643 if !@io || @io.closed?
  83. 7065 transition(:idle)
  84. 7065 @io = build_socket
  85. end
  86. 25643 try_connect
  87. rescue Errno::EHOSTUNREACH,
  88. Errno::ENETUNREACH => e
  89. 51 @ip_index -= 1
  90. 51 raise e if @ip_index.negative?
  91. 41 log { "failed connecting to #{@ip} (#{e.message}), evict from cache and trying next..." }
  92. 41 Resolver.cached_lookup_evict(@hostname, @ip)
  93. 41 @io = build_socket
  94. 41 retry
  95. rescue Errno::ECONNREFUSED,
  96. Errno::EADDRNOTAVAIL,
  97. SocketError,
  98. IOError => e
  99. 885 @ip_index -= 1
  100. 885 raise e if @ip_index.negative?
  101. 833 log { "failed connecting to #{@ip} (#{e.message}), trying next..." }
  102. 821 @io = build_socket
  103. 821 retry
  104. rescue Errno::ETIMEDOUT => e
  105. @ip_index -= 1
  106. raise ConnectTimeoutError.new(@options.timeout[:connect_timeout], e.message) if @ip_index.negative?
  107. log { "failed connecting to #{@ip} (#{e.message}), trying next..." }
  108. @io = build_socket
  109. retry
  110. end
  111. 26 def try_connect
  112. 25643 ret = @io.connect_nonblock(Socket.sockaddr_in(@port, @ip.to_s), exception: false)
  113. 15041 log(level: 3, color: :cyan) { "TCP CONNECT: #{ret}..." }
  114. 14905 case ret
  115. when :wait_readable
  116. @interests = :r
  117. return
  118. when :wait_writable
  119. 7915 @interests = :w
  120. 7915 return
  121. end
  122. 6990 transition(:connected)
  123. 6990 @interests = :w
  124. rescue Errno::EALREADY
  125. 9802 @interests = :w
  126. end
  127. 26 private :try_connect
  128. 26 def read(size, buffer)
  129. 51401 ret = @io.read_nonblock(size, buffer, exception: false)
  130. 51399 if ret == :wait_readable
  131. 12712 buffer.clear
  132. 12712 return 0
  133. end
  134. 38687 return if ret.nil?
  135. 38762 log { "READ: #{buffer.bytesize} bytes..." }
  136. 38673 buffer.bytesize
  137. end
  138. 26 def write(buffer)
  139. 17175 siz = @io.write_nonblock(buffer, exception: false)
  140. 17169 return 0 if siz == :wait_writable
  141. 17155 return if siz.nil?
  142. 17239 log { "WRITE: #{siz} bytes..." }
  143. 17155 buffer.shift!(siz)
  144. 17155 siz
  145. end
  146. 26 def close
  147. 7719 return if @keep_open || closed?
  148. 877 begin
  149. 6803 @io.close
  150. ensure
  151. 6803 transition(:closed)
  152. end
  153. end
  154. 26 def connected?
  155. 18136 @state == :connected
  156. end
  157. 26 def closed?
  158. 33461 @state == :idle || @state == :closed
  159. end
  160. skipped # :nocov:
  161. skipped def inspect
  162. skipped "#<#{self.class}:#{object_id} " \
  163. skipped "#{@ip}:#{@port} " \
  164. skipped "@state=#{@state} " \
  165. skipped "@hostname=#{@hostname} " \
  166. skipped "@addresses=#{@addresses} " \
  167. skipped "@state=#{@state}>"
  168. skipped end
  169. skipped # :nocov:
  170. 26 private
  171. 26 def build_socket
  172. 7927 @ip = @addresses[@ip_index]
  173. 7927 Socket.new(@ip.family, :STREAM, 0)
  174. end
  175. 26 def transition(nextstate)
  176. 12353 case nextstate
  177. # when :idle
  178. when :connected
  179. 4162 return unless @state == :idle
  180. when :closed
  181. 3995 return unless @state == :connected
  182. end
  183. 12353 do_transition(nextstate)
  184. end
  185. 26 def do_transition(nextstate)
  186. 23959 log(level: 1) { log_transition_state(nextstate) }
  187. 23765 @state = nextstate
  188. end
  189. 26 def log_transition_state(nextstate)
  190. 194 label = host
  191. 194 label = "#{label}(##{@io.fileno})" if nextstate == :connected
  192. 194 "#{label} #{@state} -> #{nextstate}"
  193. end
  194. end
  195. 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. 26 require "ipaddr"
  3. 26 module HTTPX
  4. 26 class UDP
  5. 26 include Loggable
  6. 26 def initialize(ip, port, options)
  7. 345 @host = ip
  8. 345 @port = port
  9. 345 @io = UDPSocket.new(IPAddr.new(ip).family)
  10. 345 @options = options
  11. end
  12. 26 def to_io
  13. 1299 @io.to_io
  14. end
  15. 26 def connect; end
  16. 26 def connected?
  17. 345 true
  18. end
  19. 26 def close
  20. 346 @io.close
  21. end
  22. 26 if RUBY_ENGINE == "jruby"
  23. # In JRuby, sendmsg_nonblock is not implemented
  24. 1 def write(buffer)
  25. 60 siz = @io.send(buffer.to_s, 0, @host, @port)
  26. 60 log { "WRITE: #{siz} bytes..." }
  27. 60 buffer.shift!(siz)
  28. 60 siz
  29. end
  30. else
  31. 25 def write(buffer)
  32. 664 siz = @io.sendmsg_nonblock(buffer.to_s, 0, Socket.sockaddr_in(@port, @host.to_s), exception: false)
  33. 664 return 0 if siz == :wait_writable
  34. 664 return if siz.nil?
  35. 664 log { "WRITE: #{siz} bytes..." }
  36. 664 buffer.shift!(siz)
  37. 664 siz
  38. end
  39. end
  40. 26 def read(size, buffer)
  41. 1295 ret = @io.recvfrom_nonblock(size, 0, buffer, exception: false)
  42. 1295 return 0 if ret == :wait_readable
  43. 648 return if ret.nil?
  44. 648 log { "READ: #{buffer.bytesize} bytes..." }
  45. 648 buffer.bytesize
  46. rescue IOError
  47. end
  48. end
  49. end

lib/httpx/io/unix.rb

97.14% lines covered

35 relevant lines. 34 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 module HTTPX
  3. 26 class UNIX < TCP
  4. 26 using URIExtensions
  5. 26 attr_reader :path
  6. 26 alias_method :host, :path
  7. 26 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. 26 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. # the path is always explicitly passed, so no point in resolving.
  47. 26 def addresses?
  48. 12 true
  49. end
  50. skipped # :nocov:
  51. skipped def inspect
  52. skipped "#<#{self.class}:#{object_id} @path=#{@path}) @state=#{@state})>"
  53. skipped end
  54. skipped # :nocov:
  55. 26 private
  56. 26 def build_socket
  57. 18 Socket.new(Socket::PF_UNIX, :STREAM, 0)
  58. end
  59. end
  60. end

lib/httpx/loggable.rb

100.0% lines covered

25 relevant lines. 25 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 module HTTPX
  3. 26 module Loggable
  4. 26 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. 26 USE_DEBUG_LOG = ENV.key?("HTTPX_DEBUG")
  15. 26 def log(
  16. level: @options.debug_level,
  17. color: nil,
  18. debug_level: @options.debug_level,
  19. debug: @options.debug,
  20. &msg
  21. )
  22. 9185026 return unless debug_level >= level
  23. 271311 debug_stream = debug || ($stderr if USE_DEBUG_LOG)
  24. 271311 return unless debug_stream
  25. 3806 klass = self.class
  26. 8980 until (class_name = klass.name)
  27. 2303 klass = klass.superclass
  28. end
  29. 3806 message = +"(pid:#{Process.pid}, " \
  30. "tid:#{Thread.current.object_id}, " \
  31. "fid:#{Fiber.current.object_id}, " \
  32. "self:#{class_name}##{object_id}) "
  33. 3806 message << msg.call << "\n"
  34. 3806 message = "\e[#{COLORS[color]}m#{message}\e[0m" if color && debug_stream.respond_to?(:isatty) && debug_stream.isatty
  35. 3806 debug_stream << message
  36. end
  37. 26 def log_exception(ex, level: @options.debug_level, color: nil, debug_level: @options.debug_level, debug: @options.debug)
  38. 1102 log(level: level, color: color, debug_level: debug_level, debug: debug) { ex.full_message }
  39. end
  40. 26 def log_redact_headers(text)
  41. 812 log_redact(text, @options.debug_redact == :headers)
  42. end
  43. 26 def log_redact_body(text)
  44. 82 log_redact(text, @options.debug_redact == :body)
  45. end
  46. 26 def log_redact(text, should_redact)
  47. 894 should_redact ||= @options.debug_redact == true
  48. 894 return text.to_s unless should_redact
  49. 196 "[REDACTED]"
  50. end
  51. end
  52. end

lib/httpx/options.rb

97.96% lines covered

196 relevant lines. 192 lines covered and 4 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 module HTTPX
  3. # Contains a set of options which are passed and shared across from session to its requests or
  4. # responses.
  5. 26 class Options
  6. 26 BUFFER_SIZE = 1 << 14
  7. 26 WINDOW_SIZE = 1 << 14 # 16K
  8. 26 MAX_BODY_THRESHOLD_SIZE = (1 << 10) * 112 # 112K
  9. 26 KEEP_ALIVE_TIMEOUT = 20
  10. 26 SETTINGS_TIMEOUT = 10
  11. 26 CLOSE_HANDSHAKE_TIMEOUT = 10
  12. 26 CONNECT_TIMEOUT = READ_TIMEOUT = WRITE_TIMEOUT = 60
  13. 26 REQUEST_TIMEOUT = OPERATION_TIMEOUT = nil
  14. # default value used for "user-agent" header, when not overridden.
  15. 26 USER_AGENT = "httpx.rb/#{VERSION}".freeze # rubocop:disable Style/RedundantFreeze
  16. 26 @options_names = []
  17. 26 class << self
  18. 26 attr_reader :options_names
  19. 26 def inherited(klass)
  20. 41 super
  21. 41 klass.instance_variable_set(:@options_names, @options_names.dup)
  22. end
  23. 26 def new(options = {})
  24. # let enhanced options go through
  25. 10819 return options if self == Options && options.class < self
  26. 8332 return options if options.is_a?(self)
  27. 4037 super
  28. end
  29. 26 def freeze
  30. 11327 @options_names.freeze
  31. 11327 super
  32. end
  33. 26 def method_added(meth)
  34. 19856 super
  35. 19856 return unless meth =~ /^option_(.+)$/
  36. 9177 optname = Regexp.last_match(1)
  37. 9177 if optname =~ /^(.+[^_])_+with/
  38. # ignore alias method chain generated methods.
  39. # this is the case with RBS runtime tests.
  40. # it relies on the "_with/_without" separator, which is the most used convention,
  41. # however it shouldn't be used in practice in httpx given the plugin architecture
  42. # as the main extension API.
  43. orig_name = Regexp.last_match(1)
  44. return if @options_names.include?(orig_name.to_sym)
  45. end
  46. 9177 optname = optname.to_sym
  47. 9177 attr_reader(optname)
  48. 9177 @options_names << optname unless @options_names.include?(optname)
  49. end
  50. end
  51. # creates a new options instance from a given hash, which optionally define the following:
  52. #
  53. # :debug :: an object which log messages are written to (must respond to <tt><<</tt>)
  54. # :debug_level :: the log level of messages (can be 1, 2, or 3).
  55. # :debug_redact :: whether header/body payload should be redacted (defaults to <tt>false</tt>).
  56. # :ssl :: a hash of options which can be set as params of OpenSSL::SSL::SSLContext (see HTTPX::SSL)
  57. # :http2_settings :: a hash of options to be passed to a HTTP2::Connection (ex: <tt>{ max_concurrent_streams: 2 }</tt>)
  58. # :fallback_protocol :: version of HTTP protocol to use by default in the absence of protocol negotiation
  59. # like ALPN (defaults to <tt>"http/1.1"</tt>)
  60. # :supported_compression_formats :: list of compressions supported by the transcoder layer (defaults to <tt>%w[gzip deflate]</tt>).
  61. # :decompress_response_body :: whether to auto-decompress response body (defaults to <tt>true</tt>).
  62. # :compress_request_body :: whether to auto-decompress response body (defaults to <tt>true</tt>)
  63. # :timeout :: hash of timeout configurations (supports <tt>:connect_timeout</tt>, <tt>:settings_timeout</tt>,
  64. # <tt>:operation_timeout</tt>, <tt>:keep_alive_timeout</tt>, <tt>:read_timeout</tt>, <tt>:write_timeout</tt>
  65. # and <tt>:request_timeout</tt>
  66. # :headers :: hash of HTTP headers (ex: <tt>{ "x-custom-foo" => "bar" }</tt>)
  67. # :window_size :: number of bytes to read from a socket
  68. # :buffer_size :: internal read and write buffer size in bytes
  69. # :body_threshold_size :: maximum size in bytes of response payload that is buffered in memory.
  70. # :request_class :: class used to instantiate a request
  71. # :response_class :: class used to instantiate a response
  72. # :headers_class :: class used to instantiate headers
  73. # :request_body_class :: class used to instantiate a request body
  74. # :response_body_class :: class used to instantiate a response body
  75. # :connection_class :: class used to instantiate connections
  76. # :http1_class :: class used to manage HTTP1 sessions
  77. # :http2_class :: class used to imanage HTTP2 sessions
  78. # :resolver_native_class :: class used to resolve names using pure ruby DNS implementation
  79. # :resolver_system_class :: class used to resolve names using system-based (getaddrinfo) name resolution
  80. # :resolver_https_class :: class used to resolve names using DoH
  81. # :pool_class :: class used to instantiate the session connection pool
  82. # :options_class :: class used to instantiate options
  83. # :transport :: type of transport to use (set to "unix" for UNIX sockets)
  84. # :addresses :: bucket of peer addresses (can be a list of IP addresses, a hash of domain to list of adddresses;
  85. # paths should be used for UNIX sockets instead)
  86. # :io :: open socket, or domain/ip-to-socket hash, which requests should be sent to
  87. # :persistent :: whether to persist connections in between requests (defaults to <tt>true</tt>)
  88. # :resolver_class :: which resolver to use (defaults to <tt>:native</tt>, can also be <tt>:system<tt> for
  89. # using getaddrinfo or <tt>:https</tt> for DoH resolver, or a custom class)
  90. # :resolver_options :: hash of options passed to the resolver. Accepted keys depend on the resolver type.
  91. # :pool_options :: hash of options passed to the connection pool (See Pool#initialize).
  92. # :ip_families :: which socket families are supported (system-dependent)
  93. # :origin :: HTTP origin to set on requests with relative path (ex: "https://api.serv.com")
  94. # :base_path :: path to prefix given relative paths with (ex: "/v2")
  95. # :max_concurrent_requests :: max number of requests which can be set concurrently
  96. # :max_requests :: max number of requests which can be made on socket before it reconnects.
  97. # :close_on_fork :: whether the session automatically closes when the process is fork (defaults to <tt>false</tt>).
  98. # it only works if the session is persistent (and ruby 3.1 or higher is used).
  99. #
  100. # This list of options are enhanced with each loaded plugin, see the plugin docs for details.
  101. 26 def initialize(options = EMPTY_HASH)
  102. 4037 options_names = self.class.options_names
  103. 513 defaults =
  104. 3524 case options
  105. when Options
  106. 2733 unknown_options = options.class.options_names - options_names
  107. 2733 raise Error, "unknown option: #{unknown_options.first}" unless unknown_options.empty?
  108. 2733 DEFAULT_OPTIONS.merge(options)
  109. else
  110. 1304 options.each_key do |k|
  111. 8976 raise Error, "unknown option: #{k}" unless options_names.include?(k)
  112. end
  113. 1297 options.empty? ? DEFAULT_OPTIONS : DEFAULT_OPTIONS.merge(options)
  114. end
  115. 4030 options_names.each do |k|
  116. 171559 v = defaults[k]
  117. 171559 if v.nil?
  118. 41757 instance_variable_set(:"@#{k}", v)
  119. 41757 next
  120. end
  121. 129802 value = __send__(:"option_#{k}", v)
  122. 129795 instance_variable_set(:"@#{k}", value)
  123. end
  124. 4023 do_initialize
  125. 4023 freeze
  126. end
  127. 26 def freeze
  128. 11326 self.class.options_names.each do |ivar|
  129. # avoid freezing debug option, as when it's set, it's usually an
  130. # object which cannot be frozen, like stderr or stdout. It's a
  131. # documented exception then, and still does not defeat the purpose
  132. # here, which is to make option objects shareable across ractors,
  133. # and in most cases debug should be nil, or one of the objects
  134. # which will eventually be shareable, like STDOUT or STDERR.
  135. 483371 next if ivar == :debug
  136. 472045 instance_variable_get(:"@#{ivar}").freeze
  137. end
  138. 11326 super
  139. end
  140. 26 REQUEST_BODY_IVARS = %i[@headers].freeze
  141. 26 def ==(other)
  142. 1866 super || options_equals?(other)
  143. end
  144. 26 def options_equals?(other, ignore_ivars = REQUEST_BODY_IVARS)
  145. # headers and other request options do not play a role, as they are
  146. # relevant only for the request.
  147. 414 ivars = instance_variables - ignore_ivars
  148. 414 other_ivars = other.instance_variables - ignore_ivars
  149. 414 return false if ivars.size != other_ivars.size
  150. 414 return false if ivars.sort != other_ivars.sort
  151. 414 ivars.all? do |ivar|
  152. 16504 instance_variable_get(ivar) == other.instance_variable_get(ivar)
  153. end
  154. end
  155. 26 def merge(other)
  156. 33022 ivar_map = nil
  157. 33022 other_ivars = case other
  158. when Options
  159. 10107 other.instance_variables
  160. else
  161. 22915 other = Hash[other] unless other.is_a?(Hash)
  162. 39847 ivar_map = other.keys.to_h { |k| [:"@#{k}", k] }
  163. 22909 ivar_map.keys
  164. end
  165. 33016 return self if other_ivars.empty?
  166. 413925 return self if other_ivars.all? { |ivar| instance_variable_get(ivar) == access_option(other, ivar, ivar_map) }
  167. 12196 opts = dup
  168. 12196 other_ivars.each do |ivar|
  169. 127756 v = access_option(other, ivar, ivar_map)
  170. 127756 unless v
  171. 33124 opts.instance_variable_set(ivar, v)
  172. 33124 next
  173. end
  174. 94632 v = opts.__send__(:"option_#{ivar[1..-1]}", v)
  175. 94618 orig_v = instance_variable_get(ivar)
  176. 94618 v = orig_v.merge(v) if orig_v.respond_to?(:merge) && v.respond_to?(:merge)
  177. 94618 opts.instance_variable_set(ivar, v)
  178. end
  179. 12182 opts
  180. end
  181. 26 def to_hash
  182. 3141 instance_variables.each_with_object({}) do |ivar, hs|
  183. 128114 val = instance_variable_get(ivar)
  184. 128114 next if val.nil?
  185. 101431 hs[ivar[1..-1].to_sym] = val
  186. end
  187. end
  188. 26 def extend_with_plugin_classes(pl)
  189. # extend request class
  190. 7263 if defined?(pl::RequestMethods) || defined?(pl::RequestClassMethods)
  191. 2412 @request_class = @request_class.dup
  192. 2412 SET_TEMPORARY_NAME[@request_class, pl]
  193. 2412 @request_class.__send__(:include, pl::RequestMethods) if defined?(pl::RequestMethods)
  194. 2412 @request_class.extend(pl::RequestClassMethods) if defined?(pl::RequestClassMethods)
  195. end
  196. # extend response class
  197. 7263 if defined?(pl::ResponseMethods) || defined?(pl::ResponseClassMethods)
  198. 2190 @response_class = @response_class.dup
  199. 2190 SET_TEMPORARY_NAME[@response_class, pl]
  200. 2190 @response_class.__send__(:include, pl::ResponseMethods) if defined?(pl::ResponseMethods)
  201. 2190 @response_class.extend(pl::ResponseClassMethods) if defined?(pl::ResponseClassMethods)
  202. end
  203. # extend headers class
  204. 7263 if defined?(pl::HeadersMethods) || defined?(pl::HeadersClassMethods)
  205. 140 @headers_class = @headers_class.dup
  206. 140 SET_TEMPORARY_NAME[@headers_class, pl]
  207. 140 @headers_class.__send__(:include, pl::HeadersMethods) if defined?(pl::HeadersMethods)
  208. 140 @headers_class.extend(pl::HeadersClassMethods) if defined?(pl::HeadersClassMethods)
  209. end
  210. # extend request body class
  211. 7263 if defined?(pl::RequestBodyMethods) || defined?(pl::RequestBodyClassMethods)
  212. 316 @request_body_class = @request_body_class.dup
  213. 316 SET_TEMPORARY_NAME[@request_body_class, pl]
  214. 316 @request_body_class.__send__(:include, pl::RequestBodyMethods) if defined?(pl::RequestBodyMethods)
  215. 316 @request_body_class.extend(pl::RequestBodyClassMethods) if defined?(pl::RequestBodyClassMethods)
  216. end
  217. # extend response body class
  218. 7263 if defined?(pl::ResponseBodyMethods) || defined?(pl::ResponseBodyClassMethods)
  219. 732 @response_body_class = @response_body_class.dup
  220. 732 SET_TEMPORARY_NAME[@response_body_class, pl]
  221. 732 @response_body_class.__send__(:include, pl::ResponseBodyMethods) if defined?(pl::ResponseBodyMethods)
  222. 732 @response_body_class.extend(pl::ResponseBodyClassMethods) if defined?(pl::ResponseBodyClassMethods)
  223. end
  224. # extend connection pool class
  225. 7263 if defined?(pl::PoolMethods)
  226. 597 @pool_class = @pool_class.dup
  227. 597 SET_TEMPORARY_NAME[@pool_class, pl]
  228. 597 @pool_class.__send__(:include, pl::PoolMethods)
  229. end
  230. # extend connection class
  231. 7263 if defined?(pl::ConnectionMethods)
  232. 3186 @connection_class = @connection_class.dup
  233. 3186 SET_TEMPORARY_NAME[@connection_class, pl]
  234. 3186 @connection_class.__send__(:include, pl::ConnectionMethods)
  235. end
  236. # extend http1 class
  237. 7263 if defined?(pl::HTTP1Methods)
  238. 484 @http1_class = @http1_class.dup
  239. 484 SET_TEMPORARY_NAME[@http1_class, pl]
  240. 484 @http1_class.__send__(:include, pl::HTTP1Methods)
  241. end
  242. # extend http2 class
  243. 7263 if defined?(pl::HTTP2Methods)
  244. 484 @http2_class = @http2_class.dup
  245. 484 SET_TEMPORARY_NAME[@http2_class, pl]
  246. 484 @http2_class.__send__(:include, pl::HTTP2Methods)
  247. end
  248. # extend native resolver class
  249. 7263 if defined?(pl::ResolverNativeMethods)
  250. 14 @resolver_native_class = @resolver_native_class.dup
  251. 14 SET_TEMPORARY_NAME[@resolver_native_class, pl]
  252. 14 @resolver_native_class.__send__(:include, pl::ResolverNativeMethods)
  253. end
  254. # extend system resolver class
  255. 7263 if defined?(pl::ResolverSystemMethods)
  256. 14 @resolver_system_class = @resolver_system_class.dup
  257. 14 SET_TEMPORARY_NAME[@resolver_system_class, pl]
  258. 14 @resolver_system_class.__send__(:include, pl::ResolverSystemMethods)
  259. end
  260. # extend https resolver class
  261. 7263 if defined?(pl::ResolverHTTPSMethods)
  262. 14 @resolver_https_class = @resolver_https_class.dup
  263. 14 SET_TEMPORARY_NAME[@resolver_https_class, pl]
  264. 14 @resolver_https_class.__send__(:include, pl::ResolverHTTPSMethods)
  265. end
  266. 7263 return unless defined?(pl::OptionsMethods)
  267. # extend option class
  268. # works around lack of initialize_dup callback
  269. 2733 @options_class = @options_class.dup
  270. # (self.class.options_names)
  271. 2733 @options_class.__send__(:include, pl::OptionsMethods)
  272. end
  273. 26 private
  274. # number options
  275. 26 %i[
  276. max_concurrent_requests max_requests window_size buffer_size
  277. body_threshold_size debug_level
  278. ].each do |option|
  279. 156 class_eval(<<-OUT, __FILE__, __LINE__ + 1)
  280. # converts +v+ into an Integer before setting the +#{option}+ option.
  281. private def option_#{option}(value) # private def option_max_requests(v)
  282. value = Integer(value) unless value.respond_to?(:infinite?) && value.infinite?
  283. raise TypeError, ":#{option} must be positive" unless value.positive? # raise TypeError, ":max_requests must be positive" unless value.positive?
  284. value
  285. end
  286. OUT
  287. end
  288. # hashable options
  289. 26 %i[ssl http2_settings resolver_options pool_options].each do |option|
  290. 104 class_eval(<<-OUT, __FILE__, __LINE__ + 1)
  291. # converts +v+ into an Hash before setting the +#{option}+ option.
  292. private def option_#{option}(value) # def option_ssl(v)
  293. Hash[value]
  294. end
  295. OUT
  296. end
  297. 26 %i[
  298. request_class response_class headers_class request_body_class
  299. response_body_class connection_class http1_class http2_class
  300. resolver_native_class resolver_system_class resolver_https_class options_class pool_class
  301. io fallback_protocol debug debug_redact resolver_class
  302. compress_request_body decompress_response_body
  303. persistent close_on_fork
  304. ].each do |method_name|
  305. 572 class_eval(<<-OUT, __FILE__, __LINE__ + 1)
  306. # sets +v+ as the value of the +#{method_name}+ option
  307. private def option_#{method_name}(v); v; end # private def option_smth(v); v; end
  308. OUT
  309. end
  310. 26 def option_origin(value)
  311. 568 URI(value)
  312. end
  313. 26 def option_base_path(value)
  314. 28 String(value)
  315. end
  316. 26 def option_headers(value)
  317. 7275 value = value.dup if value.frozen?
  318. 7275 headers_class.new(value)
  319. end
  320. 26 def option_timeout(value)
  321. 7841 Hash[value]
  322. end
  323. 26 def option_supported_compression_formats(value)
  324. 6743 Array(value).map(&:to_s)
  325. end
  326. 26 def option_transport(value)
  327. 42 transport = value.to_s
  328. 42 raise TypeError, "#{transport} is an unsupported transport type" unless %w[unix].include?(transport)
  329. 42 transport
  330. end
  331. 26 def option_addresses(value)
  332. 82 Array(value).map { |entry| Resolver::Entry.convert(entry) }
  333. end
  334. 26 def option_ip_families(value)
  335. Array(value)
  336. end
  337. # called after all options are initialized
  338. 26 def do_initialize
  339. 4023 hs = @headers
  340. # initialized default request headers
  341. 4023 hs["user-agent"] = USER_AGENT unless hs.key?("user-agent")
  342. 4023 hs["accept"] = "*/*" unless hs.key?("accept")
  343. 4023 if hs.key?("range")
  344. hs.delete("accept-encoding")
  345. else
  346. 4023 hs["accept-encoding"] = supported_compression_formats unless hs.key?("accept-encoding")
  347. end
  348. end
  349. 26 def access_option(obj, k, ivar_map)
  350. 521406 case obj
  351. when Hash
  352. 27166 obj[ivar_map[k]]
  353. else
  354. 494240 obj.instance_variable_get(k)
  355. end
  356. end
  357. 26 SET_TEMPORARY_NAME = ->(klass, pl = nil) do
  358. 10921 if klass.respond_to?(:set_temporary_name) # ruby 3.4 only
  359. 3472 name = klass.name || "#{klass.superclass.name}(plugin)"
  360. 3472 name = "#{name}/#{pl}" if pl
  361. 3472 klass.set_temporary_name(name)
  362. end
  363. end
  364. 1 DEFAULT_OPTIONS = {
  365. 25 :max_requests => Float::INFINITY,
  366. :debug => nil,
  367. 26 :debug_level => (ENV["HTTPX_DEBUG"] || 1).to_i,
  368. :debug_redact => ENV.key?("HTTPX_DEBUG_REDACT"),
  369. :ssl => EMPTY_HASH,
  370. :http2_settings => { settings_enable_push: 0 }.freeze,
  371. :fallback_protocol => "http/1.1",
  372. :supported_compression_formats => %w[gzip deflate],
  373. :decompress_response_body => true,
  374. :compress_request_body => true,
  375. :timeout => {
  376. connect_timeout: CONNECT_TIMEOUT,
  377. settings_timeout: SETTINGS_TIMEOUT,
  378. close_handshake_timeout: CLOSE_HANDSHAKE_TIMEOUT,
  379. operation_timeout: OPERATION_TIMEOUT,
  380. keep_alive_timeout: KEEP_ALIVE_TIMEOUT,
  381. read_timeout: READ_TIMEOUT,
  382. write_timeout: WRITE_TIMEOUT,
  383. request_timeout: REQUEST_TIMEOUT,
  384. }.freeze,
  385. :headers_class => Class.new(Headers, &SET_TEMPORARY_NAME),
  386. :headers => EMPTY_HASH,
  387. :window_size => WINDOW_SIZE,
  388. :buffer_size => BUFFER_SIZE,
  389. :body_threshold_size => MAX_BODY_THRESHOLD_SIZE,
  390. :request_class => Class.new(Request, &SET_TEMPORARY_NAME),
  391. :response_class => Class.new(Response, &SET_TEMPORARY_NAME),
  392. :request_body_class => Class.new(Request::Body, &SET_TEMPORARY_NAME),
  393. :response_body_class => Class.new(Response::Body, &SET_TEMPORARY_NAME),
  394. :pool_class => Class.new(Pool, &SET_TEMPORARY_NAME),
  395. :connection_class => Class.new(Connection, &SET_TEMPORARY_NAME),
  396. :http1_class => Class.new(Connection::HTTP1, &SET_TEMPORARY_NAME),
  397. :http2_class => Class.new(Connection::HTTP2, &SET_TEMPORARY_NAME),
  398. :resolver_native_class => Class.new(Resolver::Native, &SET_TEMPORARY_NAME),
  399. :resolver_system_class => Class.new(Resolver::System, &SET_TEMPORARY_NAME),
  400. :resolver_https_class => Class.new(Resolver::HTTPS, &SET_TEMPORARY_NAME),
  401. :options_class => Class.new(self, &SET_TEMPORARY_NAME),
  402. :transport => nil,
  403. :addresses => nil,
  404. :persistent => false,
  405. 26 :resolver_class => (ENV["HTTPX_RESOLVER"] || :native).to_sym,
  406. :resolver_options => { cache: true }.freeze,
  407. :pool_options => EMPTY_HASH,
  408. :ip_families => nil,
  409. :close_on_fork => false,
  410. }.freeze
  411. end
  412. 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. 26 module HTTPX
  3. 26 module Parser
  4. 26 class Error < Error; end
  5. 26 class HTTP1
  6. 26 VERSIONS = %w[1.0 1.1].freeze
  7. 26 attr_reader :status_code, :http_version, :headers
  8. 26 def initialize(observer)
  9. 4180 @observer = observer
  10. 4180 @state = :idle
  11. 4180 @buffer = "".b
  12. 4180 @headers = {}
  13. end
  14. 26 def <<(chunk)
  15. 6734 @buffer << chunk
  16. 6734 parse
  17. end
  18. 26 def reset!
  19. 8650 @state = :idle
  20. 8650 @headers = {}
  21. 8650 @content_length = nil
  22. 8650 @_has_trailers = nil
  23. end
  24. 26 def upgrade?
  25. 4244 @upgrade
  26. end
  27. 26 def upgrade_data
  28. 27 @buffer
  29. end
  30. 26 private
  31. 26 def parse
  32. 6734 loop do
  33. 14326 state = @state
  34. 14326 case @state
  35. when :idle
  36. 4566 parse_headline
  37. when :headers, :trailers
  38. 4643 parse_headers
  39. when :data
  40. 5114 parse_data
  41. end
  42. 10503 return if @buffer.empty? || state == @state
  43. end
  44. end
  45. 26 def parse_headline
  46. 4566 idx = @buffer.index("\n")
  47. 4566 return unless idx
  48. 4566 (m = %r{\AHTTP(?:/(\d+\.\d+))?\s+(\d\d\d)(?:\s+(.*))?}in.match(@buffer)) ||
  49. raise(Error, "wrong head line format")
  50. 4559 version, code, _ = m.captures
  51. 4559 raise(Error, "unsupported HTTP version (HTTP/#{version})") unless version && VERSIONS.include?(version)
  52. 4552 @http_version = version.split(".").map(&:to_i)
  53. 4552 @status_code = code.to_i
  54. 4552 raise(Error, "wrong status code (#{@status_code})") unless (100..599).cover?(@status_code)
  55. 4545 @buffer = @buffer.byteslice((idx + 1)..-1)
  56. 4545 nextstate(:headers)
  57. end
  58. 26 def parse_headers
  59. 4646 headers = @headers
  60. 4646 buffer = @buffer
  61. 36181 while (idx = buffer.index("\n"))
  62. # @type var line: String
  63. 35582 line = buffer.byteslice(0..idx)
  64. 35582 raise Error, "wrong header format" if line.start_with?("\s", "\t")
  65. 35575 line.lstrip!
  66. 35575 buffer = @buffer = buffer.byteslice((idx + 1)..-1)
  67. 35575 if line.empty?
  68. 4545 case @state
  69. when :headers
  70. 4531 prepare_data(headers)
  71. 4531 @observer.on_headers(headers)
  72. 3945 return unless @state == :headers
  73. # state might have been reset
  74. # in the :headers callback
  75. 3875 nextstate(:data)
  76. 3875 headers.clear
  77. when :trailers
  78. 14 @observer.on_trailers(headers)
  79. 14 headers.clear
  80. 14 nextstate(:complete)
  81. end
  82. 3882 return
  83. end
  84. 31030 separator_index = line.index(":")
  85. 31030 raise Error, "wrong header format" unless separator_index
  86. # @type var key: String
  87. 31023 key = line.byteslice(0..(separator_index - 1))
  88. 31023 key.rstrip! # was lstripped previously!
  89. # @type var value: String
  90. 31023 value = line.byteslice((separator_index + 1)..-1)
  91. 31023 value.strip!
  92. 31023 raise Error, "wrong header format" if value.nil?
  93. 31023 (headers[key.downcase] ||= []) << value
  94. end
  95. end
  96. 26 def parse_data
  97. 5114 if @buffer.respond_to?(:each)
  98. 136 @buffer.each do |chunk|
  99. 199 @observer.on_data(chunk)
  100. end
  101. 4977 elsif @content_length
  102. # @type var data: String
  103. 4943 data = @buffer.byteslice(0, @content_length)
  104. 4943 @buffer = @buffer.byteslice(@content_length..-1) || "".b
  105. 4943 @content_length -= data.bytesize
  106. 4943 @observer.on_data(data)
  107. 4923 data.clear
  108. else
  109. 35 @observer.on_data(@buffer)
  110. 35 @buffer.clear
  111. end
  112. 5087 return unless no_more_data?
  113. 3743 @buffer = @buffer.to_s
  114. 3743 if @_has_trailers
  115. 14 nextstate(:trailers)
  116. else
  117. 3729 nextstate(:complete)
  118. end
  119. end
  120. 26 def prepare_data(headers)
  121. 4531 @upgrade = headers.key?("upgrade")
  122. 4531 @_has_trailers = headers.key?("trailer")
  123. 4531 if (tr_encodings = headers["transfer-encoding"])
  124. 101 tr_encodings.reverse_each do |tr_encoding|
  125. 101 tr_encoding.split(/ *, */).each do |encoding|
  126. 101 case encoding
  127. when "chunked"
  128. 101 @buffer = Transcoder::Chunker::Decoder.new(@buffer, @_has_trailers)
  129. end
  130. end
  131. end
  132. else
  133. 4430 @content_length = headers["content-length"][0].to_i if headers.key?("content-length")
  134. end
  135. end
  136. 26 def no_more_data?
  137. 5087 if @content_length
  138. 4923 @content_length <= 0
  139. 163 elsif @buffer.respond_to?(:finished?)
  140. 129 @buffer.finished?
  141. else
  142. 35 false
  143. end
  144. end
  145. 26 def nextstate(state)
  146. 12177 @state = state
  147. 12177 case state
  148. when :headers
  149. 4545 @observer.on_start
  150. when :complete
  151. 3743 @observer.on_complete
  152. 568 reset!
  153. 568 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. 269 @user = user
  9. 269 @password = password
  10. end
  11. 8 def authenticate(*)
  12. 253 "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

57 relevant lines. 57 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. 154 @user = user
  11. 154 @password = password
  12. 154 @nonce = 0
  13. 154 @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. [
  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. 20 header = [
  60. 120 %(username="#{@user}"),
  61. %(nonce="#{nonce}"),
  62. %(uri="#{uri}"),
  63. %(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. 140 @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. 3 require "httpx/base64"
  3. 3 require "ntlm"
  4. 3 module HTTPX
  5. 3 module Plugins
  6. 3 module Authentication
  7. 3 class Ntlm
  8. 3 def initialize(user, password, domain: nil)
  9. 4 @user = user
  10. 4 @password = password
  11. 4 @domain = domain
  12. end
  13. 3 def can_authenticate?(authenticate)
  14. 2 authenticate && /NTLM .*/.match?(authenticate)
  15. end
  16. 3 def negotiate
  17. 4 "NTLM #{NTLM.negotiate(domain: @domain).to_base64}"
  18. end
  19. 3 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

44 relevant lines. 44 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 private
  66. 7 def option_aws_profile(value)
  67. 70 String(value)
  68. end
  69. end
  70. 7 module InstanceMethods
  71. #
  72. # aws_authentication
  73. # aws_authentication(credentials: Aws::Credentials.new('akid', 'secret'))
  74. # aws_authentication()
  75. #
  76. 7 def aws_sdk_authentication(
  77. credentials: AwsSdkAuthentication.credentials(@options.aws_profile),
  78. region: AwsSdkAuthentication.region(@options.aws_profile),
  79. **options
  80. )
  81. 14 aws_sigv4_authentication(
  82. credentials: credentials,
  83. region: region,
  84. provider_prefix: "aws",
  85. header_provider_field: "amz",
  86. **options
  87. )
  88. end
  89. 7 alias_method :aws_auth, :aws_sdk_authentication
  90. end
  91. end
  92. 7 register_plugin :aws_sdk_authentication, AwsSdkAuthentication
  93. end
  94. end

lib/httpx/plugins/aws_sigv4.rb

100.0% lines covered

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

lib/httpx/plugins/callbacks.rb

91.53% lines covered

59 relevant lines. 54 lines covered and 5 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 module HTTPX
  3. 26 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. 26 module Callbacks
  10. 26 CALLBACKS = %i[
  11. connection_opened connection_closed
  12. request_error
  13. request_started request_body_chunk request_completed
  14. response_started response_body_chunk response_completed
  15. ].freeze
  16. # connection closed user-space errors happen after errors can be surfaced to requests,
  17. # so they need to pierce through the scheduler, which is only possible by simulating an
  18. # interrupt.
  19. 26 class CallbackError < Exception; end # rubocop:disable Lint/InheritException
  20. 26 module InstanceMethods
  21. 26 include HTTPX::Callbacks
  22. 26 CALLBACKS.each do |meth|
  23. 234 class_eval(<<-MOD, __FILE__, __LINE__ + 1)
  24. def on_#{meth}(&blk) # def on_connection_opened(&blk)
  25. on(:#{meth}, &blk) # on(:connection_opened, &blk)
  26. self # self
  27. end # end
  28. MOD
  29. end
  30. 26 def plugin(*args, &blk)
  31. super(*args).tap do |sess|
  32. CALLBACKS.each do |cb|
  33. next unless callbacks_for?(cb)
  34. sess.callbacks(cb).concat(callbacks(cb))
  35. end
  36. sess.wrap(&blk) if blk
  37. end
  38. end
  39. 26 private
  40. 26 def branch(options, &blk)
  41. 28 super(options).tap do |sess|
  42. 28 CALLBACKS.each do |cb|
  43. 252 next unless callbacks_for?(cb)
  44. 14 sess.callbacks(cb).concat(callbacks(cb))
  45. end
  46. 28 sess.wrap(&blk) if blk
  47. end
  48. end
  49. 26 def do_init_connection(connection, selector)
  50. 197 super
  51. 197 connection.on(:open) do
  52. 171 next unless connection.current_session == self
  53. 171 emit_or_callback_error(:connection_opened, connection.origin, connection.io.socket)
  54. end
  55. 197 connection.on(:close) do
  56. 185 next unless connection.current_session == self
  57. 185 emit_or_callback_error(:connection_closed, connection.origin) if connection.used?
  58. end
  59. 197 connection
  60. end
  61. 26 def set_request_callbacks(request)
  62. 199 super
  63. 199 request.on(:headers) do
  64. 157 emit_or_callback_error(:request_started, request)
  65. end
  66. 199 request.on(:body_chunk) do |chunk|
  67. 14 emit_or_callback_error(:request_body_chunk, request, chunk)
  68. end
  69. 199 request.on(:done) do
  70. 143 emit_or_callback_error(:request_completed, request)
  71. end
  72. 199 request.on(:response_started) do |res|
  73. 157 if res.is_a?(Response)
  74. 129 emit_or_callback_error(:response_started, request, res)
  75. 115 res.on(:chunk_received) do |chunk|
  76. 147 emit_or_callback_error(:response_body_chunk, request, res, chunk)
  77. end
  78. else
  79. 28 emit_or_callback_error(:request_error, request, res.error)
  80. end
  81. end
  82. 199 request.on(:response) do |res|
  83. 115 emit_or_callback_error(:response_completed, request, res) if res.is_a?(Response)
  84. end
  85. end
  86. 26 def emit_or_callback_error(*args)
  87. 1061 emit(*args)
  88. rescue StandardError => e
  89. 112 ex = CallbackError.new(e.message)
  90. 112 ex.set_backtrace(e.backtrace)
  91. 112 raise ex
  92. end
  93. 26 def receive_requests(*)
  94. 199 super
  95. rescue CallbackError => e
  96. 105 raise e.cause
  97. end
  98. 26 def close(*)
  99. 197 super
  100. rescue CallbackError => e
  101. 7 raise e.cause
  102. end
  103. end
  104. end
  105. 26 register_plugin :callbacks, Callbacks
  106. end
  107. end

lib/httpx/plugins/circuit_breaker.rb

100.0% lines covered

65 relevant lines. 65 lines covered and 0 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 %i[circuit_open].each do |meth|
  30. 7 class_eval(<<-MOD, __FILE__, __LINE__ + 1)
  31. def on_#{meth}(&blk) # def on_circuit_open(&blk)
  32. on(:#{meth}, &blk) # on(:circuit_open, &blk)
  33. self # self
  34. end # end
  35. MOD
  36. end
  37. 7 private
  38. 7 def send_requests(*requests)
  39. # @type var short_circuit_responses: Array[response]
  40. 196 short_circuit_responses = []
  41. # run all requests through the circuit breaker, see if the circuit is
  42. # open for any of them.
  43. 196 real_requests = requests.each_with_index.with_object([]) do |(req, idx), real_reqs|
  44. 196 short_circuit_response = @circuit_store.try_respond(req)
  45. 196 if short_circuit_response.nil?
  46. 154 real_reqs << req
  47. 154 next
  48. end
  49. 42 short_circuit_responses[idx] = short_circuit_response
  50. end
  51. # run requests for the remainder
  52. 196 unless real_requests.empty?
  53. 154 responses = super(*real_requests)
  54. 154 real_requests.each_with_index do |request, idx|
  55. 154 short_circuit_responses[requests.index(request)] = responses[idx]
  56. end
  57. end
  58. 196 short_circuit_responses
  59. end
  60. 7 def set_request_callbacks(request)
  61. 196 super
  62. 196 request.on(:response) do |response|
  63. 154 emit(:circuit_open, request) if try_circuit_open(request, response)
  64. end
  65. end
  66. 7 def try_circuit_open(request, response)
  67. 154 if response.is_a?(ErrorResponse)
  68. 112 case response.error
  69. when RequestTimeoutError
  70. 70 @circuit_store.try_open(request.uri, response)
  71. else
  72. 42 @circuit_store.try_open(request.origin, response)
  73. end
  74. 42 elsif (break_on = request.options.circuit_breaker_break_on) && break_on.call(response)
  75. 14 @circuit_store.try_open(request.uri, response)
  76. else
  77. 28 @circuit_store.try_close(request.uri)
  78. 8 nil
  79. end
  80. end
  81. end
  82. # adds support for the following options:
  83. #
  84. # :circuit_breaker_max_attempts :: the number of attempts the circuit allows, before it is opened (defaults to <tt>3</tt>).
  85. # :circuit_breaker_reset_attempts_in :: the time a circuit stays open at most, before it resets (defaults to <tt>60</tt>).
  86. # :circuit_breaker_break_on :: callable defining an alternative rule for a response to break
  87. # (i.e. <tt>->(res) { res.status == 429 } </tt>)
  88. # :circuit_breaker_break_in :: the time that must elapse before an open circuit can transit to the half-open state
  89. # (defaults to <tt><60</tt>).
  90. # :circuit_breaker_half_open_drip_rate :: the rate of requests a circuit allows to be performed when in an half-open state
  91. # (defaults to <tt>1</tt>).
  92. 7 module OptionsMethods
  93. 7 private
  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. 196 case @state
  26. when :closed
  27. 34 nil
  28. when :half_open
  29. 49 @attempts += 1
  30. # do real requests while drip rate valid
  31. 49 if (@real_attempts % @drip_factor).zero?
  32. 35 @real_attempts += 1
  33. 35 return
  34. end
  35. 14 @response
  36. when :open
  37. 28 @response
  38. end
  39. end
  40. 7 def try_open(response)
  41. 126 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. 105 @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. 224 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. 49 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/content_digest.rb

100.0% lines covered

101 relevant lines. 101 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin adds `Content-Digest` headers to requests
  6. # and can validate these headers on responses
  7. #
  8. # https://datatracker.ietf.org/doc/html/rfc9530
  9. #
  10. 7 module ContentDigest
  11. 7 class Error < HTTPX::Error; end
  12. # Error raised on response "content-digest" header validation.
  13. 7 class ValidationError < Error
  14. 7 attr_reader :response
  15. 7 def initialize(message, response)
  16. 42 super(message)
  17. 42 @response = response
  18. end
  19. end
  20. 7 class MissingContentDigestError < ValidationError; end
  21. 7 class InvalidContentDigestError < ValidationError; end
  22. 1 SUPPORTED_ALGORITHMS = {
  23. 6 "sha-256" => OpenSSL::Digest::SHA256,
  24. "sha-512" => OpenSSL::Digest::SHA512,
  25. }.freeze
  26. 7 class << self
  27. 7 def extra_options(options)
  28. 182 options.merge(encode_content_digest: true, validate_content_digest: false, content_digest_algorithm: "sha-256")
  29. end
  30. end
  31. # add support for the following options:
  32. #
  33. # :content_digest_algorithm :: the digest algorithm to use. Currently supports `sha-256` and `sha-512`. (defaults to `sha-256`)
  34. # :encode_content_digest :: whether a <tt>Content-Digest</tt> header should be computed for the request;
  35. # can also be a callable object (i.e. <tt>->(req) { ... }</tt>, defaults to <tt>true</tt>)
  36. # :validate_content_digest :: whether a <tt>Content-Digest</tt> header in the response should be validated;
  37. # can also be a callable object (i.e. <tt>->(res) { ... }</tt>, defaults to <tt>false</tt>)
  38. 7 module OptionsMethods
  39. 7 private
  40. 7 def option_content_digest_algorithm(value)
  41. 189 raise TypeError, ":content_digest_algorithm must be one of 'sha-256', 'sha-512'" unless SUPPORTED_ALGORITHMS.key?(value)
  42. 189 value
  43. end
  44. 7 def option_encode_content_digest(value)
  45. 182 value
  46. end
  47. 7 def option_validate_content_digest(value)
  48. 126 value
  49. end
  50. end
  51. 7 module ResponseBodyMethods
  52. 7 attr_reader :content_digest_buffer
  53. 7 def initialize(response, options)
  54. 154 super
  55. 154 return unless response.headers.key?("content-digest")
  56. 112 should_validate = options.validate_content_digest
  57. 112 should_validate = should_validate.call(response) if should_validate.respond_to?(:call)
  58. 112 return unless should_validate
  59. 98 @content_digest_buffer = Response::Buffer.new(
  60. threshold_size: @options.body_threshold_size,
  61. bytesize: @length,
  62. encoding: @encoding
  63. )
  64. end
  65. 7 def write(chunk)
  66. 253 @content_digest_buffer.write(chunk) if @content_digest_buffer
  67. 253 super
  68. end
  69. 7 def close
  70. 98 if @content_digest_buffer
  71. 98 @content_digest_buffer.close
  72. 98 @content_digest_buffer = nil
  73. end
  74. 98 super
  75. end
  76. end
  77. 7 module InstanceMethods
  78. 7 def build_request(*)
  79. 196 request = super
  80. 196 return request if request.empty?
  81. 42 return request if request.headers.key?("content-digest")
  82. 42 perform_encoding = @options.encode_content_digest
  83. 42 perform_encoding = perform_encoding.call(request) if perform_encoding.respond_to?(:call)
  84. 42 return request unless perform_encoding
  85. 35 digest = base64digest(request.body)
  86. 35 request.headers.add("content-digest", "#{@options.content_digest_algorithm}=:#{digest}:")
  87. 35 request
  88. end
  89. 7 private
  90. 7 def fetch_response(request, _, _)
  91. 508 response = super
  92. 508 return response unless response.is_a?(Response)
  93. 154 perform_validation = @options.validate_content_digest
  94. 154 perform_validation = perform_validation.call(response) if perform_validation.respond_to?(:call)
  95. 154 validate_content_digest(response) if perform_validation
  96. 112 response
  97. rescue ValidationError => e
  98. 42 ErrorResponse.new(request, e)
  99. end
  100. 7 def validate_content_digest(response)
  101. 112 content_digest_header = response.headers["content-digest"]
  102. 112 raise MissingContentDigestError.new("response is missing a `content-digest` header", response) unless content_digest_header
  103. 98 digests = extract_content_digests(content_digest_header)
  104. 98 included_algorithms = SUPPORTED_ALGORITHMS.keys & digests.keys
  105. 98 raise MissingContentDigestError.new("unsupported algorithms: #{digests.keys.join(", ")}", response) if included_algorithms.empty?
  106. 98 content_buffer = response.body.content_digest_buffer
  107. 98 included_algorithms.each do |algorithm|
  108. 98 digest = SUPPORTED_ALGORITHMS.fetch(algorithm).new
  109. 98 digest_received = digests[algorithm]
  110. digest_computed =
  111. 97 if content_buffer.respond_to?(:to_path)
  112. 14 content_buffer.flush
  113. 14 digest.file(content_buffer.to_path).base64digest
  114. else
  115. 84 digest.base64digest(content_buffer.to_s)
  116. end
  117. raise InvalidContentDigestError.new("#{algorithm} digest does not match content",
  118. 97 response) unless digest_received == digest_computed
  119. end
  120. end
  121. 7 def extract_content_digests(header)
  122. 98 header.split(",").to_h do |entry|
  123. 112 algorithm, digest = entry.split("=", 2)
  124. 112 raise Error, "#{entry} is an invalid digest format" unless algorithm && digest
  125. 112 [algorithm, digest.byteslice(1..-2)]
  126. end
  127. end
  128. 7 def base64digest(body)
  129. 35 digest = SUPPORTED_ALGORITHMS.fetch(@options.content_digest_algorithm).new
  130. 35 if body.respond_to?(:read)
  131. 28 if body.respond_to?(:to_path)
  132. 7 digest.file(body.to_path).base64digest
  133. else
  134. 21 raise ContentDigestError, "request body must be rewindable" unless body.respond_to?(:rewind)
  135. 21 buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
  136. 2 begin
  137. 21 IO.copy_stream(body, buffer)
  138. 21 buffer.flush
  139. 21 digest.file(buffer.to_path).base64digest
  140. ensure
  141. 21 body.rewind
  142. 21 buffer.close
  143. 21 buffer.unlink
  144. end
  145. end
  146. else
  147. 7 raise ContentDigestError, "base64digest for endless enumerators is not supported" if body.unbounded_body?
  148. 7 buffer = "".b
  149. 14 body.each { |chunk| buffer << chunk }
  150. 7 digest.base64digest(buffer)
  151. end
  152. end
  153. end
  154. end
  155. 7 register_plugin :content_digest, ContentDigest
  156. end
  157. end

lib/httpx/plugins/cookies.rb

100.0% lines covered

52 relevant lines. 52 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 set_request_callbacks(request)
  42. 280 super
  43. 280 request.on(:response) do |response|
  44. 280 next unless response && response.respond_to?(:headers) && (set_cookie = response.headers["set-cookie"])
  45. 56 log { "cookies: set-cookie is over #{Cookie::MAX_LENGTH}" } if set_cookie.bytesize > Cookie::MAX_LENGTH
  46. 56 @options.cookies.parse(set_cookie)
  47. end
  48. end
  49. end
  50. 7 module HeadersMethods
  51. 7 def set_cookie(cookies)
  52. 280 return if cookies.empty?
  53. 238 header_value = cookies.sort.join("; ")
  54. 238 add("cookie", header_value)
  55. end
  56. end
  57. # adds support for the following options:
  58. #
  59. # :cookies :: cookie jar for the session (can be a Hash, an Array, an instance of HTTPX::Plugins::Cookies::CookieJar)
  60. 7 module OptionsMethods
  61. 7 private
  62. 7 def option_headers(*)
  63. 280 value = super
  64. 280 merge_cookie_in_jar(value.delete("cookie"), @cookies) if defined?(@cookies) && value.key?("cookie")
  65. 280 value
  66. end
  67. 7 def option_cookies(value)
  68. 420 jar = value.is_a?(Jar) ? value : Jar.new(value)
  69. 420 merge_cookie_in_jar(@headers.delete("cookie"), jar) if defined?(@headers) && @headers.key?("cookie")
  70. 420 jar
  71. end
  72. 7 def merge_cookie_in_jar(cookies, jar)
  73. 14 cookies.each do |ck|
  74. 14 ck.split(/ *; */).each do |cookie|
  75. 28 name, value = cookie.split("=", 2)
  76. 28 jar.add(Cookie.new(name, value))
  77. end
  78. end
  79. end
  80. end
  81. end
  82. 7 register_plugin :cookies, Cookies
  83. end
  84. end

lib/httpx/plugins/cookies/cookie.rb

100.0% lines covered

76 relevant lines. 76 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. 602 (@name <=> other.name).nonzero? ||
  36. 52 (other.path.length <=> @path.length).nonzero? ||
  37. 30 (@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. attr_hash.each do |key, val|
  82. 273 key = key.downcase.tr("-", "_").to_sym unless key.is_a?(Symbol)
  83. 273 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. 483 "#{@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

46 relevant lines. 46 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. 100 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 now = Time.now
  48. 413 tpath = uri.path
  49. 413 @cookies.delete_if do |cookie|
  50. 637 if cookie.expired?(now)
  51. 14 true
  52. else
  53. 623 yield cookie if cookie.valid_for_uri?(uri) && Cookie.path_match?(cookie.path, tpath)
  54. 623 false
  55. end
  56. end
  57. end
  58. 7 def merge(other)
  59. 175 cookies_dup = dup
  60. 175 other.each do |elem|
  61. 189 cookie = case elem
  62. when Cookie
  63. 175 elem
  64. when Array
  65. 7 Cookie.new(*elem)
  66. else
  67. 7 Cookie.new(elem)
  68. end
  69. 189 cookies_dup.add(cookie)
  70. end
  71. 175 cookies_dup
  72. end
  73. end
  74. end
  75. end

lib/httpx/plugins/cookies/set_cookie_parser.rb

100.0% lines covered

72 relevant lines. 72 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. 14 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. 385 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. 126 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 && name.empty?
  68. 182 attrs = {}
  69. 182 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.nil? || aname.empty?) || value.nil?
  79. 203 aname.downcase!
  80. 203 case aname
  81. when "expires"
  82. 14 next unless avalue
  83. # RFC 6265 5.2.1
  84. 14 (avalue = Time.parse(avalue)) || next
  85. when "max-age"
  86. 7 next unless avalue
  87. # RFC 6265 5.2.2
  88. 7 next unless /\A-?\d+\z/.match?(avalue)
  89. 7 avalue = Integer(avalue)
  90. when "domain"
  91. # RFC 6265 5.2.3
  92. # An empty value SHOULD be ignored.
  93. 21 next if avalue.nil? || avalue.empty?
  94. when "path"
  95. # RFC 6265 5.2.4
  96. # A relative path must be ignored rather than normalizing it
  97. # to "/".
  98. 154 next unless avalue && avalue.start_with?("/")
  99. when "secure", "httponly"
  100. # RFC 6265 5.2.5, 5.2.6
  101. 6 avalue = true
  102. end
  103. 203 attrs[aname] = avalue
  104. end
  105. end
  106. 182 len ||= scanner.pos - start
  107. 182 next if len > Cookie::MAX_LENGTH
  108. 182 yield(name, value, attrs) if name && !name.empty? && value
  109. end
  110. end
  111. end
  112. end
  113. end

lib/httpx/plugins/digest_auth.rb

100.0% lines covered

30 relevant lines. 30 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 private
  24. 7 def option_digest(value)
  25. 280 raise TypeError, ":digest must be a #{Authentication::Digest}" unless value.is_a?(Authentication::Digest)
  26. 280 value
  27. end
  28. end
  29. 7 module InstanceMethods
  30. 7 def digest_auth(user, password, hashed: false)
  31. 140 with(digest: Authentication::Digest.new(user, password, hashed: hashed))
  32. end
  33. 7 private
  34. 7 def send_requests(*requests)
  35. 168 requests.flat_map do |request|
  36. 168 digest = request.options.digest
  37. 168 next super(request) unless digest
  38. 280 probe_response = wrap { super(request).first }
  39. 140 return probe_response unless probe_response.is_a?(Response)
  40. 140 if probe_response.status == 401 && digest.can_authenticate?(probe_response.headers["www-authenticate"])
  41. 126 request.transition(:idle)
  42. 126 request.headers["authorization"] = digest.authenticate(request, probe_response.headers["www-authenticate"])
  43. 126 super(request)
  44. else
  45. 14 probe_response
  46. end
  47. end
  48. end
  49. end
  50. end
  51. 7 register_plugin :digest_auth, DigestAuth
  52. end
  53. end

lib/httpx/plugins/expect.rb

100.0% lines covered

57 relevant lines. 57 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. 158 @no_expect_store ||= []
  14. end
  15. 7 def extra_options(options)
  16. 189 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 private
  26. 7 def option_expect_timeout(value)
  27. 336 seconds = Float(value)
  28. 336 raise TypeError, ":expect_timeout must be positive" unless seconds.positive?
  29. 336 seconds
  30. end
  31. 7 def option_expect_threshold_size(value)
  32. 14 bytes = Integer(value)
  33. 14 raise TypeError, ":expect_threshold_size must be positive" unless bytes.positive?
  34. 14 bytes
  35. end
  36. end
  37. 7 module RequestMethods
  38. 7 def initialize(*)
  39. 217 super
  40. 217 return if @body.empty?
  41. 147 threshold = @options.expect_threshold_size
  42. 147 return if threshold && !@body.unbounded_body? && @body.bytesize < threshold
  43. 133 return if Expect.no_expect_store.include?(origin)
  44. 126 @headers["expect"] = "100-continue"
  45. end
  46. 7 def response=(response)
  47. 161 if response.is_a?(Response) &&
  48. response.status == 100 &&
  49. !@headers.key?("expect") &&
  50. 2 (@state == :body || @state == :done)
  51. # if we're past this point, this means that we just received a 100-Continue response,
  52. # but the request doesn't have the expect flag, and is already flushing (or flushed) the body.
  53. #
  54. # this means that expect was deactivated for this request too soon, i.e. response took longer.
  55. #
  56. # so we have to reactivate it again.
  57. 9 @headers["expect"] = "100-continue"
  58. 9 @informational_status = 100
  59. 9 Expect.no_expect_store.delete(origin)
  60. end
  61. 161 super
  62. end
  63. end
  64. 7 module ConnectionMethods
  65. 7 def send_request_to_parser(request)
  66. 98 super
  67. 98 return unless request.headers["expect"] == "100-continue"
  68. 70 expect_timeout = request.options.expect_timeout
  69. 70 return if expect_timeout.nil? || expect_timeout.infinite?
  70. 70 set_request_timeout(:expect_timeout, request, expect_timeout, :expect, %i[body response]) do
  71. # expect timeout expired
  72. 16 if request.state == :expect && !request.expects?
  73. 16 Expect.no_expect_store << request.origin
  74. 16 request.headers.delete("expect")
  75. 16 consume
  76. end
  77. end
  78. end
  79. end
  80. 7 module InstanceMethods
  81. 7 def fetch_response(request, selector, options)
  82. 408 response = super
  83. 408 return unless response
  84. 98 if response.is_a?(Response) && response.status == 417 && request.headers.key?("expect")
  85. 14 response.close
  86. 14 request.headers.delete("expect")
  87. 14 request.transition(:idle)
  88. 14 send_request(request, selector, options)
  89. 14 return
  90. end
  91. 84 response
  92. end
  93. end
  94. end
  95. 7 register_plugin :expect, Expect
  96. end
  97. end

lib/httpx/plugins/fiber_concurrency.rb

88.04% lines covered

92 relevant lines. 81 lines covered and 11 lines missed.
    
  1. # frozen_string_literal: true
  2. 16 module HTTPX
  3. 16 module Plugins
  4. # This plugin makes a session reuse the same selector across all fibers in a given thread.
  5. #
  6. # This enables integration with fiber scheduler implementations such as [async](https://github.com/async).
  7. #
  8. # # https://gitlab.com/os85/httpx/wikis/FiberConcurrency
  9. #
  10. 16 module FiberConcurrency
  11. 16 def self.subplugins
  12. {
  13. 1730 h2c: FiberConcurrencyH2C,
  14. }
  15. end
  16. 16 module InstanceMethods
  17. 16 private
  18. 16 def send_request(request, *)
  19. 568 request.set_context!
  20. 568 super
  21. end
  22. 16 def get_current_selector
  23. 489 super(&nil) || begin
  24. 450 return unless block_given?
  25. 450 default = yield
  26. 450 set_current_selector(default)
  27. 450 default
  28. end
  29. end
  30. end
  31. 16 module RequestMethods
  32. # the execution context (fiber) this request was sent on.
  33. 16 attr_reader :context
  34. 16 def initialize(*)
  35. 510 super
  36. 510 @context = nil
  37. end
  38. # sets the execution context for this request. the default is the current fiber.
  39. 16 def set_context!
  40. 1141 @context ||= Fiber.current # rubocop:disable Naming/MemoizedInstanceVariableName
  41. end
  42. # checks whether the current execution context is the one where the request was created.
  43. 16 def current_context?
  44. 3939 @context == Fiber.current
  45. end
  46. 16 def complete!(response = @response)
  47. 510 @context = nil
  48. 510 super
  49. end
  50. end
  51. 16 module ConnectionMethods
  52. 16 def current_context?
  53. @pending.any?(&:current_context?) || (
  54. @sibling && @sibling.pending.any?(&:current_context?)
  55. )
  56. end
  57. 16 def interests
  58. 9904 return if connecting? && @pending.none?(&:current_context?)
  59. 9302 super
  60. end
  61. 16 def send(request)
  62. # DoH requests bypass the session, so context needs to be set here.
  63. 573 request.set_context!
  64. 573 super
  65. end
  66. end
  67. 16 module HTTP1Methods
  68. 16 def interests
  69. 1088 request = @request || @requests.first
  70. 1088 return unless request
  71. 1072 return unless request.current_context? || @requests.any?(&:current_context?) || @pending.any?(&:current_context?)
  72. 1072 super
  73. end
  74. end
  75. 16 module HTTP2Methods
  76. 16 def initialize(*)
  77. 353 super
  78. 1108 @contexts = Hash.new { |hs, k| hs[k] = Set.new }
  79. end
  80. 16 def interests
  81. 7122 if @connection.state == :connected && @handshake_completed && !@contexts.key?(Fiber.current)
  82. 405 return :w unless @pings.empty?
  83. 361 return
  84. end
  85. 6717 super
  86. end
  87. 16 def send(request, *)
  88. 788 add_to_context(request)
  89. 788 super
  90. end
  91. 16 private
  92. 16 def on_close(_, error, _)
  93. 16 if error == :http_1_1_required
  94. # remove all pending requests context
  95. @pending.each do |req|
  96. clear_from_context(req)
  97. end
  98. end
  99. 16 super
  100. end
  101. 16 def on_stream_close(_, request, error)
  102. 397 clear_from_context(request) if error != :stream_closed && @streams.key?(request)
  103. 397 super
  104. end
  105. 16 def teardown(request = nil)
  106. 389 super
  107. 389 if request
  108. 373 clear_from_context(request)
  109. else
  110. 16 @contexts.clear
  111. end
  112. end
  113. 16 def add_to_context(request)
  114. 788 @contexts[request.context] << request
  115. end
  116. 16 def clear_from_context(request)
  117. 746 requests = @contexts[request.context]
  118. 746 requests.delete(request)
  119. 746 @contexts.delete(request.context) if requests.empty?
  120. end
  121. end
  122. 16 module NativeResolverMethods
  123. 16 private
  124. 16 def calculate_interests
  125. return if @queries.empty?
  126. return unless @queries.values.any?(&:current_context?) || @connections.any?(&:current_context?)
  127. super
  128. end
  129. end
  130. 16 module SystemResolverMethods
  131. 16 def interests
  132. return unless @queries.any? { |_, conn| conn.current_context? }
  133. super
  134. end
  135. end
  136. 16 module FiberConcurrencyH2C
  137. 16 module HTTP2Methods
  138. 16 def upgrade(request, *)
  139. @contexts[request.context] << request
  140. super
  141. end
  142. end
  143. end
  144. end
  145. 16 register_plugin :fiber_concurrency, FiberConcurrency
  146. end
  147. end

lib/httpx/plugins/follow_redirects.rb

100.0% lines covered

109 relevant lines. 109 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 14 module HTTPX
  3. 14 InsecureRedirectError = Class.new(Error)
  4. 14 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. 14 module FollowRedirects
  21. 14 MAX_REDIRECTS = 3
  22. 14 REDIRECT_STATUS = (300..399).freeze
  23. 14 REQUEST_BODY_HEADERS = %w[transfer-encoding content-encoding content-type content-length content-language content-md5 trailer].freeze
  24. 14 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. 14 module OptionsMethods
  34. 14 private
  35. 14 def option_max_redirects(value)
  36. 405 num = Integer(value)
  37. 405 raise TypeError, ":max_redirects must be positive" if num.negative?
  38. 405 num
  39. end
  40. 14 def option_follow_insecure_redirects(value)
  41. 21 value
  42. end
  43. 14 def option_allow_auth_to_other_origins(value)
  44. 21 value
  45. end
  46. 14 def option_redirect_on(value)
  47. 42 raise TypeError, ":redirect_on must be callable" unless value.respond_to?(:call)
  48. 42 value
  49. end
  50. end
  51. 14 module InstanceMethods
  52. # returns a session with the *max_redirects* option set to +n+
  53. 14 def max_redirects(n)
  54. 42 with(max_redirects: n.to_i)
  55. end
  56. 14 private
  57. 14 def fetch_response(request, selector, options)
  58. 3497506 redirect_request = request.redirect_request
  59. 3497506 response = super(redirect_request, selector, options)
  60. 3497506 return unless response
  61. 498 max_redirects = redirect_request.max_redirects
  62. 498 return response unless response.is_a?(Response)
  63. 484 return response unless REDIRECT_STATUS.include?(response.status) && response.headers.key?("location")
  64. 316 return response unless max_redirects.positive?
  65. 288 redirect_uri = __get_location_from_response(response)
  66. 288 if options.redirect_on
  67. 28 redirect_allowed = options.redirect_on.call(redirect_uri)
  68. 28 return response unless redirect_allowed
  69. end
  70. # build redirect request
  71. 274 request_body = redirect_request.body
  72. 274 redirect_method = "GET"
  73. 274 redirect_params = {}
  74. 274 if response.status == 305 && options.respond_to?(:proxy)
  75. 7 request_body.rewind
  76. # The requested resource MUST be accessed through the proxy given by
  77. # the Location field. The Location field gives the URI of the proxy.
  78. 7 redirect_options = options.merge(headers: redirect_request.headers,
  79. proxy: { uri: redirect_uri },
  80. max_redirects: max_redirects - 1)
  81. 7 redirect_params[:body] = request_body
  82. 7 redirect_uri = redirect_request.uri
  83. 7 options = redirect_options
  84. else
  85. 267 redirect_headers = redirect_request_headers(redirect_request.uri, redirect_uri, request.headers, options)
  86. 267 redirect_opts = Hash[options]
  87. 267 redirect_params[:max_redirects] = max_redirects - 1
  88. 267 unless request_body.empty?
  89. 21 if response.status == 307
  90. # The method and the body of the original request are reused to perform the redirected request.
  91. 7 redirect_method = redirect_request.verb
  92. 7 request_body.rewind
  93. 7 redirect_params[:body] = request_body
  94. else
  95. # redirects are **ALWAYS** GET, so remove body-related headers
  96. 14 REQUEST_BODY_HEADERS.each do |h|
  97. 98 redirect_headers.delete(h)
  98. end
  99. 14 redirect_params[:body] = nil
  100. end
  101. end
  102. 267 options = options.class.new(redirect_opts.merge(headers: redirect_headers.to_h))
  103. end
  104. 274 redirect_uri = Utils.to_uri(redirect_uri)
  105. 274 if !options.follow_insecure_redirects &&
  106. response.uri.scheme == "https" &&
  107. redirect_uri.scheme == "http"
  108. 7 error = InsecureRedirectError.new(redirect_uri.to_s)
  109. 7 error.set_backtrace(caller)
  110. 7 return ErrorResponse.new(request, error)
  111. end
  112. 267 retry_request = build_request(redirect_method, redirect_uri, redirect_params, options)
  113. 267 request.redirect_request = retry_request
  114. 267 redirect_after = response.headers["retry-after"]
  115. 267 if redirect_after
  116. # Servers send the "Retry-After" header field to indicate how long the
  117. # user agent ought to wait before making a follow-up request.
  118. # When sent with any 3xx (Redirection) response, Retry-After indicates
  119. # the minimum time that the user agent is asked to wait before issuing
  120. # the redirected request.
  121. #
  122. 26 redirect_after = Utils.parse_retry_after(redirect_after)
  123. 26 retry_start = Utils.now
  124. 26 log { "redirecting after #{redirect_after} secs..." }
  125. 26 selector.after(redirect_after) do
  126. 26 if (response = request.response)
  127. 12 response.finish!
  128. 12 retry_request.response = response
  129. # request has terminated abruptly meanwhile
  130. 12 retry_request.emit(:response, response)
  131. else
  132. 14 log { "redirecting (elapsed time: #{Utils.elapsed_time(retry_start)})!!" }
  133. 14 send_request(retry_request, selector, options)
  134. end
  135. end
  136. else
  137. 241 send_request(retry_request, selector, options)
  138. end
  139. 77 nil
  140. end
  141. # :nodoc:
  142. 14 def redirect_request_headers(original_uri, redirect_uri, headers, options)
  143. 267 headers = headers.dup
  144. 267 return headers if options.allow_auth_to_other_origins
  145. 260 return headers unless headers.key?("authorization")
  146. 7 return headers if original_uri.origin == redirect_uri.origin
  147. 7 headers.delete("authorization")
  148. 7 headers
  149. end
  150. # :nodoc:
  151. 14 def __get_location_from_response(response)
  152. # @type var location_uri: http_uri
  153. 288 location_uri = URI(response.headers["location"])
  154. 288 location_uri = response.uri.merge(location_uri) if location_uri.relative?
  155. 288 location_uri
  156. end
  157. end
  158. 14 module RequestMethods
  159. # returns the top-most original HTTPX::Request from the redirect chain
  160. 14 attr_accessor :root_request
  161. # returns the follow-up redirect request, or itself
  162. 14 def redirect_request
  163. 3497506 @redirect_request || self
  164. end
  165. # sets the follow-up redirect request
  166. 14 def redirect_request=(req)
  167. 267 @redirect_request = req
  168. 267 req.root_request = @root_request || self
  169. 267 @response = nil
  170. end
  171. 14 def response
  172. 3499289 return super unless @redirect_request && @response.nil?
  173. 87 @redirect_request.response
  174. end
  175. 14 def max_redirects
  176. 498 @options.max_redirects || MAX_REDIRECTS
  177. end
  178. end
  179. 14 module ConnectionMethods
  180. 14 private
  181. 14 def set_request_request_timeout(request)
  182. 474 return unless request.root_request.nil?
  183. 225 super
  184. end
  185. end
  186. end
  187. 14 register_plugin :follow_redirects, FollowRedirects
  188. end
  189. end

lib/httpx/plugins/grpc.rb

100.0% lines covered

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

47 relevant lines. 46 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 6 module HTTPX
  3. 6 module Transcoder
  4. 6 module GRPCEncoding
  5. 6 class Deflater
  6. 6 extend Forwardable
  7. 6 attr_reader :content_type
  8. 6 def initialize(body, compressed:)
  9. 126 @content_type = body.content_type
  10. 126 @body = BodyReader.new(body)
  11. 126 @compressed = compressed
  12. end
  13. 6 def bytesize
  14. 450 return @body.bytesize if @body.respond_to?(:bytesize)
  15. Float::INFINITY
  16. end
  17. 6 def read(length = nil, outbuf = nil)
  18. 276 buf = @body.read(length, outbuf)
  19. 252 return unless buf
  20. 138 compressed_flag = @compressed ? 1 : 0
  21. 138 buf = outbuf if outbuf
  22. 138 buf = buf.b if buf.frozen?
  23. 138 buf.prepend([compressed_flag, buf.bytesize].pack("CL>"))
  24. 138 buf
  25. end
  26. end
  27. 6 class Inflater
  28. 6 def initialize(response)
  29. 90 @response = response
  30. 90 @grpc_encodings = nil
  31. end
  32. 6 def call(message, &blk)
  33. 114 data = "".b
  34. 114 until message.empty?
  35. 114 compressed, size = message.unpack("CL>")
  36. 114 encoded_data = message.byteslice(5..size + 5 - 1)
  37. 114 if compressed == 1
  38. 12 grpc_encodings.reverse_each do |encoding|
  39. 12 decoder = @response.body.class.initialize_inflater_by_encoding(encoding, @response, bytesize: encoded_data.bytesize)
  40. 12 encoded_data = decoder.call(encoded_data)
  41. 12 blk.call(encoded_data) if blk
  42. 12 data << encoded_data
  43. end
  44. else
  45. 102 blk.call(encoded_data) if blk
  46. 102 data << encoded_data
  47. end
  48. 114 message = message.byteslice((size + 5)..-1)
  49. end
  50. 114 data
  51. end
  52. 6 private
  53. 6 def grpc_encodings
  54. 12 @grpc_encodings ||= @response.headers.get("grpc-encoding")
  55. end
  56. end
  57. 6 def self.encode(*args, **kwargs)
  58. 126 Deflater.new(*args, **kwargs)
  59. end
  60. 6 def self.decode(response)
  61. 90 Inflater.new(response)
  62. end
  63. end
  64. end
  65. 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. 6 module HTTPX
  3. 6 module Plugins
  4. 6 module GRPC
  5. # Encoding module for GRPC responses
  6. #
  7. # Can encode and decode grpc messages.
  8. 6 module Message
  9. 6 module_function
  10. # decodes a unary grpc response
  11. 6 def unary(response)
  12. 90 verify_status(response)
  13. 66 decoder = Transcoder::GRPCEncoding.decode(response)
  14. 66 decoder.call(response.to_s)
  15. end
  16. # lazy decodes a grpc stream response
  17. 6 def stream(response, &block)
  18. 48 return enum_for(__method__, response) unless block
  19. 24 decoder = Transcoder::GRPCEncoding.decode(response)
  20. 24 response.each do |frame|
  21. 48 decoder.call(frame, &block)
  22. end
  23. 24 verify_status(response)
  24. end
  25. 6 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. 6 def verify_status(response)
  31. # return standard errors if need be
  32. 114 response.raise_for_status
  33. 114 status = Integer(response.headers["grpc-status"])
  34. 114 message = response.headers["grpc-message"]
  35. 114 return if status.zero?
  36. 24 response.close
  37. 24 raise GRPCError.new(status, message, response.trailing_metadata)
  38. end
  39. end
  40. end
  41. end
  42. end

lib/httpx/plugins/h2c.rb

95.24% lines covered

63 relevant lines. 60 lines covered and 3 lines missed.
    
  1. # frozen_string_literal: true
  2. 16 module HTTPX
  3. 16 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. 16 module H2C
  11. 16 VALID_H2C_VERBS = %w[GET OPTIONS HEAD].freeze
  12. 16 class << self
  13. 16 def load_dependencies(klass)
  14. 14 klass.plugin(:upgrade)
  15. end
  16. 16 def call(connection, request, response)
  17. 14 connection.upgrade_to_h2c(request, response)
  18. end
  19. 16 def extra_options(options)
  20. 16 options.merge(
  21. 14 h2c_class: Class.new(options.http2_class) { include(H2CParser) },
  22. max_concurrent_requests: 1,
  23. upgrade_handlers: options.upgrade_handlers.merge("h2c" => self),
  24. )
  25. end
  26. end
  27. 16 module OptionsMethods
  28. 16 def option_h2c_class(value)
  29. 14 value
  30. end
  31. end
  32. 16 module RequestMethods
  33. 16 def valid_h2c_verb?
  34. 14 VALID_H2C_VERBS.include?(@verb)
  35. end
  36. end
  37. 16 module ConnectionMethods
  38. 16 using URIExtensions
  39. 16 def initialize(*)
  40. 14 super
  41. 14 @h2c_handshake = false
  42. end
  43. 16 def send(request)
  44. 49 return super if @h2c_handshake
  45. 14 return super unless request.valid_h2c_verb? && request.scheme == "http"
  46. 14 return super if @upgrade_protocol == "h2c"
  47. 14 @h2c_handshake = true
  48. # build upgrade request
  49. 14 request.headers.add("connection", "upgrade")
  50. 14 request.headers.add("connection", "http2-settings")
  51. 14 request.headers["upgrade"] = "h2c"
  52. 14 request.headers["http2-settings"] = ::HTTP2::Client.settings_header(request.options.http2_settings)
  53. 14 super
  54. end
  55. 16 def upgrade_to_h2c(request, response)
  56. 14 prev_parser = @parser
  57. 14 if prev_parser
  58. 14 prev_parser.reset
  59. 14 @inflight -= prev_parser.requests.size
  60. end
  61. 14 @parser = request.options.h2c_class.new(@write_buffer, @options)
  62. 14 set_parser_callbacks(@parser)
  63. 14 @inflight += 1
  64. 14 @parser.upgrade(request, response)
  65. 14 @upgrade_protocol = "h2c"
  66. 14 prev_parser.requests.each do |req|
  67. 14 req.transition(:idle)
  68. 14 send(req)
  69. end
  70. end
  71. 16 private
  72. 16 def send_request_to_parser(request)
  73. 49 super
  74. 49 return unless request.headers["upgrade"] == "h2c" && parser.is_a?(Connection::HTTP1)
  75. 14 max_concurrent_requests = parser.max_concurrent_requests
  76. 14 return if max_concurrent_requests == 1
  77. parser.max_concurrent_requests = 1
  78. request.once(:response) do
  79. parser.max_concurrent_requests = max_concurrent_requests
  80. end
  81. end
  82. end
  83. 16 module H2CParser
  84. 16 def upgrade(request, response)
  85. # skip checks, it is assumed that this is the first
  86. # request in the connection
  87. 14 stream = @connection.upgrade
  88. # on_settings
  89. 14 handle_stream(stream, request)
  90. 14 @streams[request] = stream
  91. # clean up data left behind in the buffer, if the server started
  92. # sending frames
  93. 14 data = response.read
  94. 14 @connection << data
  95. end
  96. end
  97. end
  98. 16 register_plugin(:h2c, H2C)
  99. end
  100. end

lib/httpx/plugins/ntlm_auth.rb

100.0% lines covered

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

lib/httpx/plugins/oauth.rb

100.0% lines covered

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

lib/httpx/plugins/persistent.rb

100.0% lines covered

31 relevant lines. 31 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 16 module HTTPX
  3. 16 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. 16 module Persistent
  20. 16 class << self
  21. 16 def load_dependencies(klass)
  22. 470 klass.plugin(:fiber_concurrency)
  23. 470 max_retries = if klass.default_options.respond_to?(:max_retries)
  24. 7 [klass.default_options.max_retries, 1].max
  25. else
  26. 463 1
  27. end
  28. 470 klass.plugin(:retries, max_retries: max_retries)
  29. end
  30. end
  31. 16 def self.extra_options(options)
  32. 470 options.merge(persistent: true)
  33. end
  34. 16 module InstanceMethods
  35. 16 def close(*)
  36. 259 super
  37. # traverse other threads and unlink respective selector
  38. # WARNING: this is not thread safe, make sure that the session isn't being
  39. # used anymore, or all non-main threads are stopped.
  40. 259 Thread.list.each do |th|
  41. 3824 store = thread_selector_store(th)
  42. 3824 next unless store && store.key?(self)
  43. 258 selector = store.delete(self)
  44. 258 selector_close(selector)
  45. end
  46. end
  47. 16 private
  48. 16 def repeatable_request?(request, _)
  49. 528 super || begin
  50. 188 response = request.response
  51. 188 return false unless response && response.is_a?(ErrorResponse)
  52. 26 error = response.error
  53. 286 Retries::RECONNECTABLE_ERRORS.any? { |klass| error.is_a?(klass) }
  54. end
  55. end
  56. 16 def retryable_error?(ex)
  57. 78 super &&
  58. # under the persistent plugin rules, requests are only retried for connection related errors,
  59. # which do not include request timeout related errors. This only gets overriden if the end user
  60. # manually changed +:max_retries+ to something else, which means it is aware of the
  61. # consequences.
  62. 65 (!ex.is_a?(RequestTimeoutError) || @options.max_retries != 1)
  63. end
  64. end
  65. end
  66. 16 register_plugin :persistent, Persistent
  67. end
  68. end

lib/httpx/plugins/proxy.rb

94.71% lines covered

170 relevant lines. 161 lines covered and 9 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module HTTPX
  3. 9 class ProxyError < 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 class ProxyConnectionError < ProxyError; end
  17. 9 PROXY_ERRORS = [TimeoutError, IOError, SystemCallError, Error].freeze
  18. 9 class << self
  19. 9 def configure(klass)
  20. 302 klass.plugin(:"proxy/http")
  21. 302 klass.plugin(:"proxy/socks4")
  22. 302 klass.plugin(:"proxy/socks5")
  23. end
  24. 9 def extra_options(options)
  25. 302 options.merge(supported_proxy_protocols: [])
  26. end
  27. 9 def subplugins
  28. {
  29. 1224 retries: ProxyRetries,
  30. }
  31. end
  32. end
  33. 9 class Parameters
  34. 9 attr_reader :uri, :username, :password, :scheme, :no_proxy
  35. 9 def initialize(uri: nil, scheme: nil, username: nil, password: nil, no_proxy: nil, **extra)
  36. 332 @no_proxy = Array(no_proxy) if no_proxy
  37. 332 @uris = Array(uri)
  38. 332 uri = @uris.first
  39. 332 @username = username
  40. 332 @password = password
  41. 332 @ns = 0
  42. 332 if uri
  43. 297 @uri = uri.is_a?(URI::Generic) ? uri : URI(uri)
  44. 297 @username ||= @uri.user
  45. 297 @password ||= @uri.password
  46. end
  47. 332 @scheme = scheme
  48. 332 return unless @uri && @username && @password
  49. 185 @authenticator = nil
  50. 185 @scheme ||= infer_default_auth_scheme(@uri)
  51. 185 return unless @scheme
  52. 143 @authenticator = load_authenticator(@scheme, @username, @password, **extra)
  53. end
  54. 9 def shift
  55. # TODO: this operation must be synchronized
  56. 14 @ns += 1
  57. 14 @uri = @uris[@ns]
  58. 14 return unless @uri
  59. 14 @uri = URI(@uri) unless @uri.is_a?(URI::Generic)
  60. 14 scheme = infer_default_auth_scheme(@uri)
  61. 14 return unless scheme != @scheme
  62. 14 @scheme = scheme
  63. 14 @username = username || @uri.user
  64. 14 @password = password || @uri.password
  65. 14 @authenticator = load_authenticator(scheme, @username, @password)
  66. end
  67. 9 def can_authenticate?(*args)
  68. 161 return false unless @authenticator
  69. 56 @authenticator.can_authenticate?(*args)
  70. end
  71. 9 def authenticate(*args)
  72. 141 return unless @authenticator
  73. 141 @authenticator.authenticate(*args)
  74. end
  75. 9 def ==(other)
  76. 402 case other
  77. when Parameters
  78. 367 @uri == other.uri &&
  79. @username == other.username &&
  80. @password == other.password &&
  81. @scheme == other.scheme
  82. when URI::Generic, String
  83. 21 proxy_uri = @uri.dup
  84. 21 proxy_uri.user = @username
  85. 21 proxy_uri.password = @password
  86. 21 other_uri = other.is_a?(URI::Generic) ? other : URI.parse(other)
  87. 21 proxy_uri == other_uri
  88. else
  89. 14 super
  90. end
  91. end
  92. 9 private
  93. 9 def infer_default_auth_scheme(uri)
  94. 185 case uri.scheme
  95. when "socks5"
  96. 42 uri.scheme
  97. when "http", "https"
  98. 88 "basic"
  99. end
  100. end
  101. 9 def load_authenticator(scheme, username, password, **extra)
  102. 157 auth_scheme = scheme.to_s.capitalize
  103. 157 require_relative "auth/#{scheme}" unless defined?(Authentication) && Authentication.const_defined?(auth_scheme, false)
  104. 157 Authentication.const_get(auth_scheme).new(username, password, **extra)
  105. end
  106. end
  107. # adds support for the following options:
  108. #
  109. # :proxy :: proxy options defining *:uri*, *:username*, *:password* or
  110. # *:scheme* (i.e. <tt>{ uri: "http://proxy" }</tt>)
  111. 9 module OptionsMethods
  112. 9 private
  113. 9 def option_proxy(value)
  114. 603 value.is_a?(Parameters) ? value : Parameters.new(**Hash[value])
  115. end
  116. 9 def option_supported_proxy_protocols(value)
  117. 1523 raise TypeError, ":supported_proxy_protocols must be an Array" unless value.is_a?(Array)
  118. 1523 value.map(&:to_s)
  119. end
  120. end
  121. 9 module InstanceMethods
  122. 9 def find_connection(request_uri, selector, options)
  123. 386 return super unless options.respond_to?(:proxy)
  124. 386 if (next_proxy = request_uri.find_proxy)
  125. 4 return super(request_uri, selector, options.merge(proxy: Parameters.new(uri: next_proxy)))
  126. end
  127. 382 proxy = options.proxy
  128. 382 return super unless proxy
  129. 373 next_proxy = proxy.uri
  130. 373 raise ProxyError, "Failed to connect to proxy" unless next_proxy
  131. raise ProxyError,
  132. 359 "#{next_proxy.scheme}: unsupported proxy protocol" unless options.supported_proxy_protocols.include?(next_proxy.scheme)
  133. 352 if (no_proxy = proxy.no_proxy)
  134. 14 no_proxy = no_proxy.join(",") if no_proxy.is_a?(Array)
  135. # TODO: setting proxy to nil leaks the connection object in the pool
  136. 14 return super(request_uri, selector, options.merge(proxy: nil)) unless URI::Generic.use_proxy?(request_uri.host, next_proxy.host,
  137. next_proxy.port, no_proxy)
  138. end
  139. 345 super(request_uri, selector, options.merge(proxy: proxy))
  140. end
  141. 9 private
  142. 9 def fetch_response(request, selector, options)
  143. 1641 response = request.response # in case it goes wrong later
  144. 168 begin
  145. 1641 response = super
  146. 1641 if response.is_a?(ErrorResponse) && proxy_error?(request, response, options)
  147. 14 options.proxy.shift
  148. # return last error response if no more proxies to try
  149. 14 return response if options.proxy.uri.nil?
  150. 14 log { "failed connecting to proxy, trying next..." }
  151. 14 request.transition(:idle)
  152. 14 send_request(request, selector, options)
  153. 14 return
  154. end
  155. 1627 response
  156. rescue ProxyError
  157. # may happen if coupled with retries, and there are no more proxies to try, in which case
  158. # it'll end up here
  159. response
  160. end
  161. end
  162. 9 def proxy_error?(_request, response, options)
  163. 148 return false unless options.proxy
  164. 147 error = response.error
  165. 147 case error
  166. when NativeResolveError
  167. 14 proxy_uri = URI(options.proxy.uri)
  168. 14 unresolved_host = error.host
  169. # failed resolving proxy domain
  170. 14 unresolved_host == proxy_uri.host
  171. when ResolveError
  172. proxy_uri = URI(options.proxy.uri)
  173. error.message.end_with?(proxy_uri.to_s)
  174. when ProxyConnectionError
  175. # timeout errors connecting to proxy
  176. true
  177. else
  178. 133 false
  179. end
  180. end
  181. end
  182. 9 module ConnectionMethods
  183. 9 using URIExtensions
  184. 9 def initialize(*)
  185. 345 super
  186. 345 return unless @options.proxy
  187. # redefining the connection origin as the proxy's URI,
  188. # as this will be used as the tcp peer ip.
  189. 329 @proxy_uri = URI(@options.proxy.uri)
  190. end
  191. 9 def peer
  192. 834 @proxy_uri || super
  193. end
  194. 9 def connecting?
  195. 4999 return super unless @options.proxy
  196. 4852 super || @state == :connecting || @state == :connected
  197. end
  198. 9 def call
  199. 1238 super
  200. 1238 return unless @options.proxy
  201. 1206 case @state
  202. when :connecting
  203. 327 consume
  204. end
  205. rescue *PROXY_ERRORS => e
  206. if connecting?
  207. error = ProxyConnectionError.new(e.message)
  208. error.set_backtrace(e.backtrace)
  209. raise error
  210. end
  211. raise e
  212. end
  213. 9 def reset
  214. 350 return super unless @options.proxy
  215. 335 @state = :open
  216. 335 super
  217. # emit(:close)
  218. end
  219. 9 private
  220. 9 def initialize_type(uri, options)
  221. 345 return super unless options.proxy
  222. 329 "tcp"
  223. end
  224. 9 def connect
  225. 994 return super unless @options.proxy
  226. 964 case @state
  227. when :idle
  228. 651 transition(:connecting)
  229. when :connected
  230. 313 transition(:open)
  231. end
  232. end
  233. 9 def handle_transition(nextstate)
  234. 2001 return super unless @options.proxy
  235. 1924 case nextstate
  236. when :closing
  237. # this is a hack so that we can use the super method
  238. # and it'll think that the current state is open
  239. 342 @state = :open if @state == :connecting
  240. end
  241. 1924 super
  242. end
  243. 9 def purge_after_closed
  244. 371 super
  245. 371 @io = @io.proxy_io if @io.respond_to?(:proxy_io)
  246. end
  247. end
  248. 9 module ProxyRetries
  249. 9 module InstanceMethods
  250. 9 def retryable_error?(ex)
  251. 48 super || ex.is_a?(ProxyConnectionError)
  252. end
  253. end
  254. end
  255. end
  256. 9 register_plugin :proxy, Proxy
  257. end
  258. 9 class ProxySSL < SSL
  259. 9 attr_reader :proxy_io
  260. 9 def initialize(tcp, request_uri, options)
  261. 91 @proxy_io = tcp
  262. 91 @io = tcp.to_io
  263. 91 super(request_uri, tcp.addresses, options)
  264. 91 @hostname = request_uri.host
  265. 91 @state = :connected
  266. end
  267. end
  268. end

lib/httpx/plugins/proxy/http.rb

100.0% lines covered

104 relevant lines. 104 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. 302 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, selector, options)
  22. 1641 response = super
  23. 1641 if response &&
  24. response.is_a?(Response) &&
  25. response.status == 407 &&
  26. !request.headers.key?("proxy-authorization") &&
  27. response.headers.key?("proxy-authenticate") && options.proxy.can_authenticate?(response.headers["proxy-authenticate"])
  28. 7 request.transition(:idle)
  29. 7 request.headers["proxy-authorization"] =
  30. options.proxy.authenticate(request, response.headers["proxy-authenticate"])
  31. 7 send_request(request, selector, options)
  32. 7 return
  33. end
  34. 1634 response
  35. end
  36. end
  37. 9 module ConnectionMethods
  38. 9 def connecting?
  39. 4999 super || @state == :connecting || @state == :connected
  40. end
  41. 9 private
  42. 9 def handle_transition(nextstate)
  43. 2225 return super unless @options.proxy && @options.proxy.uri.scheme == "http"
  44. 1163 case nextstate
  45. when :connecting
  46. 294 return unless @state == :idle
  47. 294 @io.connect
  48. 294 return unless @io.connected?
  49. 147 @parser || begin
  50. 140 @parser = parser_type(@io.protocol).new(@write_buffer, @options.merge(max_concurrent_requests: 1))
  51. 140 parser = @parser
  52. 140 parser.extend(ProxyParser)
  53. 140 parser.on(:response, &method(:__http_on_connect))
  54. 140 parser.on(:close) do |force|
  55. 63 next unless @parser
  56. 7 if force
  57. 7 reset
  58. 7 emit(:terminate)
  59. end
  60. end
  61. 140 parser.on(:reset) do
  62. 14 if parser.empty?
  63. 7 reset
  64. else
  65. 7 transition(:closing)
  66. 7 transition(:closed)
  67. 7 parser.reset if @parser
  68. 7 transition(:idle)
  69. 7 transition(:connecting)
  70. end
  71. end
  72. 140 __http_proxy_connect(parser)
  73. end
  74. 147 return if @state == :connected
  75. when :connected
  76. 133 return unless @state == :idle || @state == :connecting
  77. 133 case @state
  78. when :connecting
  79. 56 parser = @parser
  80. 56 @parser = nil
  81. 56 parser.close
  82. when :idle
  83. 77 @parser.callbacks.clear
  84. 77 set_parser_callbacks(@parser)
  85. end
  86. end
  87. 939 super
  88. end
  89. 9 def __http_proxy_connect(parser)
  90. 140 req = @pending.first
  91. 140 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. 63 connect_request = ConnectRequest.new(req.uri, @options)
  97. 63 @inflight += 1
  98. 63 parser.send(connect_request)
  99. else
  100. 77 handle_transition(:connected)
  101. end
  102. end
  103. 9 def __http_on_connect(request, response)
  104. 70 @inflight -= 1
  105. 70 if response.is_a?(Response) && response.status == 200
  106. 56 req = @pending.first
  107. 56 request_uri = req.uri
  108. 56 @io = ProxySSL.new(@io, request_uri, @options)
  109. 56 transition(:connected)
  110. 56 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. 7 request.headers["proxy-authorization"] = @options.proxy.authenticate(request, response.headers["proxy-authenticate"])
  117. 7 @parser.send(request)
  118. 7 @inflight += 1
  119. else
  120. 7 pending = @pending + @parser.pending
  121. 19 while (req = pending.shift)
  122. 7 response.finish!
  123. 7 req.response = response
  124. 7 req.emit(:response, response)
  125. end
  126. 7 reset
  127. end
  128. end
  129. end
  130. 9 module ProxyParser
  131. 9 def join_headline(request)
  132. 140 return super if request.verb == "CONNECT"
  133. 70 "#{request.verb} #{request.uri} HTTP/#{@version.join(".")}"
  134. end
  135. 9 def set_protocol_headers(request)
  136. 147 extra_headers = super
  137. 147 proxy_params = @options.proxy
  138. 147 if proxy_params.scheme == "basic"
  139. # opt for basic auth
  140. 85 extra_headers["proxy-authorization"] = proxy_params.authenticate(extra_headers)
  141. end
  142. 147 extra_headers["proxy-connection"] = extra_headers.delete("connection") if extra_headers.key?("connection")
  143. 147 extra_headers
  144. end
  145. end
  146. 9 class ConnectRequest < Request
  147. 9 def initialize(uri, options)
  148. 63 super("CONNECT", uri, options)
  149. 63 @headers.delete("accept")
  150. end
  151. 9 def path
  152. 77 "#{@uri.hostname}:#{@uri.port}"
  153. end
  154. end
  155. end
  156. end
  157. 9 register_plugin :"proxy/http", Proxy::HTTP
  158. end
  159. end

lib/httpx/plugins/proxy/socks4.rb

97.47% lines covered

79 relevant lines. 77 lines covered and 2 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 require "resolv"
  3. 9 require "ipaddr"
  4. 9 module HTTPX
  5. 9 class Socks4Error < ProxyError; 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. 302 options.merge(supported_proxy_protocols: options.supported_proxy_protocols + PROTOCOLS)
  17. end
  18. end
  19. 9 module ConnectionMethods
  20. 9 def interests
  21. 3749 if @state == :connecting
  22. return @write_buffer.empty? ? :r : :w
  23. end
  24. 3749 super
  25. end
  26. 9 private
  27. 9 def handle_transition(nextstate)
  28. 2281 return super unless @options.proxy && PROTOCOLS.include?(@options.proxy.uri.scheme)
  29. 383 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. 327 log(level: 1) { "SOCKS4: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
  44. 327 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. 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. 56 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

99.12% lines covered

113 relevant lines. 112 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module HTTPX
  3. 9 class Socks5Error < ProxyError; 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. 302 require_relative "../auth/socks5"
  20. end
  21. 9 def extra_options(options)
  22. 302 options.merge(supported_proxy_protocols: options.supported_proxy_protocols + %w[socks5])
  23. end
  24. end
  25. 9 module ConnectionMethods
  26. 9 def call
  27. 1238 super
  28. 1238 return unless @options.proxy && @options.proxy.uri.scheme == "socks5"
  29. 339 case @state
  30. when :connecting,
  31. :negotiating,
  32. :authenticating
  33. 160 consume
  34. end
  35. end
  36. 9 def connecting?
  37. 4999 super || @state == :authenticating || @state == :negotiating
  38. end
  39. 9 def interests
  40. 6259 if @state == :connecting || @state == :authenticating || @state == :negotiating
  41. 2510 return @write_buffer.empty? ? :r : :w
  42. end
  43. 3749 super
  44. end
  45. 9 private
  46. 9 def handle_transition(nextstate)
  47. 2533 return super unless @options.proxy && @options.proxy.uri.scheme == "socks5"
  48. 910 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. 658 log(level: 1) { "SOCKS5: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
  68. 658 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. 210 case @state
  77. when :connecting
  78. 126 version, method = packet.unpack("CC")
  79. 126 __socks5_check_version(version)
  80. 126 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. 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.45% lines covered

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

100.0% lines covered

14 relevant lines. 14 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 using the experimental QUERY HTTP method
  6. #
  7. # https://gitlab.com/os85/httpx/wikis/Query
  8. 7 module Query
  9. 7 def self.subplugins
  10. {
  11. 20 retries: QueryRetries,
  12. }
  13. end
  14. 7 module InstanceMethods
  15. 7 def query(*uri, **options)
  16. 14 request("QUERY", uri, **options)
  17. end
  18. end
  19. 7 module QueryRetries
  20. 7 module InstanceMethods
  21. 7 private
  22. 7 def repeatable_request?(request, options)
  23. 21 super || request.verb == "QUERY"
  24. end
  25. end
  26. end
  27. end
  28. 7 register_plugin :query, Query
  29. end
  30. 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

144 relevant lines. 144 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 SUPPORTED_VARY_HEADERS = %w[accept accept-encoding accept-language cookie origin].sort.freeze
  13. 7 private_constant :CACHEABLE_VERBS
  14. 7 private_constant :CACHEABLE_STATUS_CODES
  15. 7 class << self
  16. 7 def load_dependencies(*)
  17. 196 require_relative "response_cache/store"
  18. 196 require_relative "response_cache/file_store"
  19. end
  20. # whether the +response+ can be stored in the response cache.
  21. # (i.e. has a cacheable body, does not contain directives prohibiting storage, etc...)
  22. 7 def cacheable_response?(response)
  23. 119 response.is_a?(Response) &&
  24. (
  25. 119 response.cache_control.nil? ||
  26. # TODO: !response.cache_control.include?("private") && is shared cache
  27. !response.cache_control.include?("no-store")
  28. ) &&
  29. CACHEABLE_STATUS_CODES.include?(response.status) &&
  30. # RFC 2616 13.4 - A response received with a status code of 200, 203, 206, 300, 301 or
  31. # 410 MAY be stored by a cache and used in reply to a subsequent
  32. # request, subject to the expiration mechanism, unless a cache-control
  33. # directive prohibits caching. However, a cache that does not support
  34. # the Range and Content-Range headers MUST NOT cache 206 (Partial
  35. # Content) responses.
  36. response.status != 206
  37. end
  38. # whether the +response+
  39. 7 def not_modified?(response)
  40. 147 response.is_a?(Response) && response.status == 304
  41. end
  42. 7 def extra_options(options)
  43. 196 options.merge(
  44. supported_vary_headers: SUPPORTED_VARY_HEADERS,
  45. response_cache_store: :store,
  46. )
  47. end
  48. end
  49. # adds support for the following options:
  50. #
  51. # :supported_vary_headers :: array of header values that will be considered for a "vary" header based cache validation
  52. # (defaults to {SUPPORTED_VARY_HEADERS}).
  53. # :response_cache_store :: object where cached responses are fetch from or stored in; defaults to <tt>:store</tt> (in-memory
  54. # cache), can be set to <tt>:file_store</tt> (file system cache store) as well, or any object which
  55. # abides by the Cache Store Interface
  56. #
  57. # The Cache Store Interface requires implementation of the following methods:
  58. #
  59. # * +#get(request) -> response or nil+
  60. # * +#set(request, response) -> void+
  61. # * +#clear() -> void+)
  62. #
  63. 7 module OptionsMethods
  64. 7 private
  65. 7 def option_response_cache_store(value)
  66. 329 case value
  67. when :store
  68. 210 Store.new
  69. when :file_store
  70. 14 FileStore.new
  71. else
  72. 105 value
  73. end
  74. end
  75. 7 def option_supported_vary_headers(value)
  76. 196 Array(value).sort
  77. end
  78. end
  79. 7 module InstanceMethods
  80. # wipes out all cached responses from the cache store.
  81. 7 def clear_response_cache
  82. 119 @options.response_cache_store.clear
  83. end
  84. 7 def build_request(*)
  85. 420 request = super
  86. 420 return request unless cacheable_request?(request)
  87. 406 prepare_cache(request)
  88. 406 request
  89. end
  90. 7 private
  91. 7 def send_request(request, *)
  92. 147 return request if request.response
  93. 133 super
  94. end
  95. 7 def fetch_response(request, *)
  96. 513 response = super
  97. 513 return unless response
  98. 147 if ResponseCache.not_modified?(response)
  99. 28 log { "returning cached response for #{request.uri}" }
  100. 28 response.copy_from_cached!
  101. 118 elsif request.cacheable_verb? && ResponseCache.cacheable_response?(response)
  102. 98 unless response.cached?
  103. 84 log { "caching response for #{request.uri}..." }
  104. 84 request.options.response_cache_store.set(request, response)
  105. end
  106. end
  107. 147 response
  108. end
  109. # will either assign a still-fresh cached response to +request+, or set up its HTTP
  110. # cache invalidation headers in case it's not fresh anymore.
  111. 7 def prepare_cache(request)
  112. 602 cached_response = request.options.response_cache_store.get(request)
  113. 602 return unless cached_response && match_by_vary?(request, cached_response)
  114. 266 cached_response.body.rewind
  115. 266 if cached_response.fresh?
  116. 56 cached_response = cached_response.dup
  117. 56 cached_response.mark_as_cached!
  118. 56 request.response = cached_response
  119. 56 request.emit(:response, cached_response)
  120. 56 return
  121. end
  122. 210 request.cached_response = cached_response
  123. 210 if !request.headers.key?("if-modified-since") && (last_modified = cached_response.headers["last-modified"])
  124. 28 request.headers.add("if-modified-since", last_modified)
  125. end
  126. 210 if !request.headers.key?("if-none-match") && (etag = cached_response.headers["etag"]) # rubocop:disable Style/GuardClause
  127. 154 request.headers.add("if-none-match", etag)
  128. end
  129. end
  130. 7 def cacheable_request?(request)
  131. 420 request.cacheable_verb? &&
  132. (
  133. 406 !request.headers.key?("cache-control") || !request.headers.get("cache-control").include?("no-store")
  134. )
  135. end
  136. # whether the +response+ complies with the directives set by the +request+ "vary" header
  137. # (true when none is available).
  138. 7 def match_by_vary?(request, response)
  139. 266 vary = response.vary
  140. 266 return true unless vary
  141. 84 original_request = response.original_request
  142. 84 if vary == %w[*]
  143. 28 request.options.supported_vary_headers.each do |field|
  144. 140 return false unless request.headers[field] == original_request.headers[field]
  145. end
  146. 28 return true
  147. end
  148. 56 vary.all? do |field|
  149. 56 !original_request.headers.key?(field) || request.headers[field] == original_request.headers[field]
  150. end
  151. end
  152. end
  153. 7 module RequestMethods
  154. # points to a previously cached Response corresponding to this request.
  155. 7 attr_accessor :cached_response
  156. 7 def initialize(*)
  157. 560 super
  158. 560 @cached_response = nil
  159. end
  160. 7 def merge_headers(*)
  161. 259 super
  162. 259 @response_cache_key = nil
  163. end
  164. # returns whether this request is cacheable as per HTTP caching rules.
  165. 7 def cacheable_verb?
  166. 539 CACHEABLE_VERBS.include?(@verb)
  167. end
  168. # returns a unique cache key as a String identifying this request
  169. 7 def response_cache_key
  170. 1162 @response_cache_key ||= begin
  171. 427 keys = [@verb, @uri.merge(path)]
  172. 427 @options.supported_vary_headers.each do |field|
  173. 2135 value = @headers[field]
  174. 2135 keys << value if value
  175. end
  176. 427 Digest::SHA1.hexdigest("httpx-response-cache-#{keys.join("-")}")
  177. end
  178. end
  179. end
  180. 7 module ResponseMethods
  181. 7 attr_writer :original_request
  182. 7 def initialize(*)
  183. 441 super
  184. 441 @cached = false
  185. end
  186. # a copy of the request this response was originally cached from
  187. 7 def original_request
  188. 84 @original_request || @request
  189. end
  190. # whether this Response was duplicated from a previously {RequestMethods#cached_response}.
  191. 7 def cached?
  192. 98 @cached
  193. end
  194. # sets this Response as being duplicated from a previously cached response.
  195. 7 def mark_as_cached!
  196. 56 @cached = true
  197. end
  198. # eager-copies the response headers and body from {RequestMethods#cached_response}.
  199. 7 def copy_from_cached!
  200. 28 cached_response = @request.cached_response
  201. 28 return unless cached_response
  202. # 304 responses do not have content-type, which are needed for decoding.
  203. 28 @headers = @headers.class.new(cached_response.headers.merge(@headers))
  204. 28 @body = cached_response.body.dup
  205. 28 @body.rewind
  206. end
  207. # A response is fresh if its age has not yet exceeded its freshness lifetime.
  208. # other (#cache_control} directives may influence the outcome, as per the rules
  209. # from the {rfc}[https://www.rfc-editor.org/rfc/rfc7234]
  210. 7 def fresh?
  211. 266 if cache_control
  212. 98 return false if cache_control.include?("no-cache")
  213. 70 return true if cache_control.include?("immutable")
  214. # check age: max-age
  215. 168 max_age = cache_control.find { |directive| directive.start_with?("s-maxage") }
  216. 168 max_age ||= cache_control.find { |directive| directive.start_with?("max-age") }
  217. 70 max_age = max_age[/age=(\d+)/, 1] if max_age
  218. 70 max_age = max_age.to_i if max_age
  219. 70 return max_age > age if max_age
  220. end
  221. # check age: expires
  222. 168 if @headers.key?("expires")
  223. 5 begin
  224. 42 expires = Time.httpdate(@headers["expires"])
  225. rescue ArgumentError
  226. 14 return false
  227. end
  228. 28 return (expires - Time.now).to_i.positive?
  229. end
  230. 126 false
  231. end
  232. # returns the "cache-control" directives as an Array of String(s).
  233. 7 def cache_control
  234. 742 return @cache_control if defined?(@cache_control)
  235. @cache_control = begin
  236. 336 return unless @headers.key?("cache-control")
  237. 98 @headers["cache-control"].split(/ *, */)
  238. end
  239. end
  240. # returns the "vary" header value as an Array of (String) headers.
  241. 7 def vary
  242. 266 return @vary if defined?(@vary)
  243. @vary = begin
  244. 238 return unless @headers.key?("vary")
  245. 56 @headers["vary"].split(/ *, */).map(&:downcase)
  246. end
  247. end
  248. 7 private
  249. # returns the value of the "age" header as an Integer (time since epoch).
  250. # if no "age" of header exists, it returns the number of seconds since {#date}.
  251. 7 def age
  252. 70 return @headers["age"].to_i if @headers.key?("age")
  253. 70 (Time.now - date).to_i
  254. end
  255. # returns the value of the "date" header as a Time object
  256. 7 def date
  257. 70 @date ||= Time.httpdate(@headers["date"])
  258. rescue NoMethodError, ArgumentError
  259. 14 Time.now
  260. end
  261. end
  262. end
  263. 7 register_plugin :response_cache, ResponseCache
  264. end
  265. end

lib/httpx/plugins/response_cache/file_store.rb

100.0% lines covered

72 relevant lines. 72 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 require "pathname"
  3. 7 module HTTPX::Plugins
  4. 7 module ResponseCache
  5. # Implementation of a file system based cache store.
  6. #
  7. # It stores cached responses in a file under a directory pointed by the +dir+
  8. # variable (defaults to the default temp directory from the OS), in a custom
  9. # format (similar but different from HTTP/1.1 request/response framing).
  10. 7 class FileStore
  11. 7 CRLF = HTTPX::Connection::HTTP1::CRLF
  12. 7 attr_reader :dir
  13. 7 def initialize(dir = Dir.tmpdir)
  14. 70 @dir = Pathname.new(dir).join("httpx-response-cache")
  15. 70 FileUtils.mkdir_p(@dir)
  16. end
  17. 7 def clear
  18. 56 FileUtils.rm_rf(@dir)
  19. end
  20. 7 def get(request)
  21. 273 path = file_path(request)
  22. 273 return unless File.exist?(path)
  23. 133 File.open(path, mode: File::RDONLY | File::BINARY) do |f|
  24. 133 f.flock(File::Constants::LOCK_SH)
  25. 133 read_from_file(request, f)
  26. end
  27. end
  28. 7 def set(request, response)
  29. 84 path = file_path(request)
  30. 84 file_exists = File.exist?(path)
  31. 84 mode = file_exists ? File::RDWR : File::CREAT | File::Constants::WRONLY
  32. 84 File.open(path, mode: mode | File::BINARY) do |f|
  33. 84 f.flock(File::Constants::LOCK_EX)
  34. 84 if file_exists
  35. 7 cached_response = read_from_file(request, f)
  36. 7 if cached_response
  37. 7 next if cached_response == request.cached_response
  38. 7 cached_response.close
  39. 7 f.truncate(0)
  40. 7 f.rewind
  41. end
  42. end
  43. # cache the request headers
  44. 84 f << request.verb << CRLF
  45. 84 f << request.uri << CRLF
  46. 84 request.headers.each do |field, value|
  47. 252 f << field << ":" << value << CRLF
  48. end
  49. 84 f << CRLF
  50. # cache the response
  51. 84 f << response.status << CRLF
  52. 84 f << response.version << CRLF
  53. 84 response.headers.each do |field, value|
  54. 231 f << field << ":" << value << CRLF
  55. end
  56. 84 f << CRLF
  57. 84 response.body.rewind
  58. 84 IO.copy_stream(response.body, f)
  59. end
  60. end
  61. 7 private
  62. 7 def file_path(request)
  63. 357 @dir.join(request.response_cache_key)
  64. end
  65. 7 def read_from_file(request, f)
  66. # if it's an empty file
  67. 140 return if f.eof?
  68. # read request data
  69. 140 verb = f.readline.delete_suffix!(CRLF)
  70. 140 uri = f.readline.delete_suffix!(CRLF)
  71. 140 request_headers = {}
  72. 620 while (line = f.readline) != CRLF
  73. 420 line.delete_suffix!(CRLF)
  74. 420 sep_index = line.index(":")
  75. 420 field = line.byteslice(0..(sep_index - 1))
  76. 420 value = line.byteslice((sep_index + 1)..-1)
  77. 420 request_headers[field] = value
  78. end
  79. 140 status = f.readline.delete_suffix!(CRLF)
  80. 140 version = f.readline.delete_suffix!(CRLF)
  81. 140 response_headers = {}
  82. 590 while (line = f.readline) != CRLF
  83. 385 line.delete_suffix!(CRLF)
  84. 385 sep_index = line.index(":")
  85. 385 field = line.byteslice(0..(sep_index - 1))
  86. 385 value = line.byteslice((sep_index + 1)..-1)
  87. 385 response_headers[field] = value
  88. end
  89. 140 original_request = request.options.request_class.new(verb, uri, request.options)
  90. 140 original_request.merge_headers(request_headers)
  91. 140 response = request.options.response_class.new(request, status, version, response_headers)
  92. 140 response.original_request = original_request
  93. 140 response.finish!
  94. 140 IO.copy_stream(f, response.body)
  95. 140 response
  96. end
  97. end
  98. end
  99. end

lib/httpx/plugins/response_cache/store.rb

100.0% lines covered

16 relevant lines. 16 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX::Plugins
  3. 7 module ResponseCache
  4. # Implementation of a thread-safe in-memory cache store.
  5. 7 class Store
  6. 7 def initialize
  7. 259 @store = {}
  8. 259 @store_mutex = Thread::Mutex.new
  9. end
  10. 7 def clear
  11. 126 @store_mutex.synchronize { @store.clear }
  12. end
  13. 7 def get(request)
  14. 406 @store_mutex.synchronize do
  15. 406 @store[request.response_cache_key]
  16. end
  17. end
  18. 7 def set(request, response)
  19. 175 @store_mutex.synchronize do
  20. 175 cached_response = @store[request.response_cache_key]
  21. 175 cached_response.close if cached_response
  22. 175 @store[request.response_cache_key] = response
  23. end
  24. end
  25. end
  26. end
  27. end

lib/httpx/plugins/retries.rb

96.91% lines covered

97 relevant lines. 94 lines covered and 3 lines missed.
    
  1. # frozen_string_literal: true
  2. 16 module HTTPX
  3. 16 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. 16 module Retries
  15. 16 MAX_RETRIES = 3
  16. # TODO: pass max_retries in a configure/load block
  17. 16 IDEMPOTENT_METHODS = %w[GET OPTIONS HEAD PUT DELETE].freeze
  18. # subset of retryable errors which are safe to retry when reconnecting
  19. 1 RECONNECTABLE_ERRORS = [
  20. 15 IOError,
  21. EOFError,
  22. Errno::ECONNRESET,
  23. Errno::ECONNABORTED,
  24. Errno::EPIPE,
  25. Errno::EINVAL,
  26. Errno::ETIMEDOUT,
  27. ConnectionError,
  28. TLSError,
  29. Connection::HTTP2::Error,
  30. ].freeze
  31. 16 RETRYABLE_ERRORS = (RECONNECTABLE_ERRORS + [
  32. Parser::Error,
  33. TimeoutError,
  34. ]).freeze
  35. 16 DEFAULT_JITTER = ->(interval) { interval * ((rand + 1) * 0.5) }
  36. 16 if ENV.key?("HTTPX_NO_JITTER")
  37. 15 def self.extra_options(options)
  38. 708 options.merge(max_retries: MAX_RETRIES)
  39. end
  40. else
  41. 1 def self.extra_options(options)
  42. 6 options.merge(max_retries: MAX_RETRIES, retry_jitter: DEFAULT_JITTER)
  43. end
  44. end
  45. # adds support for the following options:
  46. #
  47. # :max_retries :: max number of times a request will be retried (defaults to <tt>3</tt>).
  48. # :retry_change_requests :: whether idempotent requests are retried (defaults to <tt>false</tt>).
  49. # :retry_after:: seconds after which a request is retried; can also be a callable object (i.e. <tt>->(req, res) { ... } </tt>)
  50. # :retry_jitter :: number of seconds applied to *:retry_after* (must be a callable, i.e. <tt>->(retry_after) { ... } </tt>).
  51. # :retry_on :: callable which alternatively defines a different rule for when a response is to be retried
  52. # (i.e. <tt>->(res) { ... }</tt>).
  53. 16 module OptionsMethods
  54. 16 private
  55. 16 def option_retry_after(value)
  56. # return early if callable
  57. 182 unless value.respond_to?(:call)
  58. 84 value = Float(value)
  59. 84 raise TypeError, ":retry_after must be positive" unless value.positive?
  60. end
  61. 182 value
  62. end
  63. 16 def option_retry_jitter(value)
  64. # return early if callable
  65. 54 raise TypeError, ":retry_jitter must be callable" unless value.respond_to?(:call)
  66. 54 value
  67. end
  68. 16 def option_max_retries(value)
  69. 2190 num = Integer(value)
  70. 2190 raise TypeError, ":max_retries must be positive" unless num >= 0
  71. 2190 num
  72. end
  73. 16 def option_retry_change_requests(v)
  74. 112 v
  75. end
  76. 16 def option_retry_on(value)
  77. 251 raise TypeError, ":retry_on must be called with the response" unless value.respond_to?(:call)
  78. 251 value
  79. end
  80. end
  81. 16 module InstanceMethods
  82. # returns a `:retries` plugin enabled session with +n+ maximum retries per request setting.
  83. 16 def max_retries(n)
  84. 84 with(max_retries: n)
  85. end
  86. 16 private
  87. 16 def fetch_response(request, selector, options)
  88. 5057409 response = super
  89. 5057409 if response &&
  90. request.retries.positive? &&
  91. repeatable_request?(request, options) &&
  92. (
  93. (
  94. 271 response.is_a?(ErrorResponse) && retryable_error?(response.error)
  95. ) ||
  96. (
  97. 198 options.retry_on && options.retry_on.call(response)
  98. )
  99. )
  100. 440 try_partial_retry(request, response)
  101. 440 log { "failed to get response, #{request.retries} tries to go..." }
  102. 440 request.retries -= 1 unless request.ping? # do not exhaust retries on connection liveness probes
  103. 440 request.transition(:idle)
  104. 440 retry_after = options.retry_after
  105. 440 retry_after = retry_after.call(request, response) if retry_after.respond_to?(:call)
  106. 440 if retry_after
  107. # apply jitter
  108. 84 if (jitter = request.options.retry_jitter)
  109. 14 retry_after = jitter.call(retry_after)
  110. end
  111. 84 retry_start = Utils.now
  112. 84 log { "retrying after #{retry_after} secs..." }
  113. 84 selector.after(retry_after) do
  114. 84 if (response = request.response)
  115. response.finish!
  116. # request has terminated abruptly meanwhile
  117. request.emit(:response, response)
  118. else
  119. 84 log { "retrying (elapsed time: #{Utils.elapsed_time(retry_start)})!!" }
  120. 84 send_request(request, selector, options)
  121. end
  122. end
  123. else
  124. 356 send_request(request, selector, options)
  125. end
  126. 440 return
  127. end
  128. 5056969 response
  129. end
  130. # returns whether +request+ can be retried.
  131. 16 def repeatable_request?(request, options)
  132. 1015 IDEMPOTENT_METHODS.include?(request.verb) || options.retry_change_requests
  133. end
  134. # returns whether the +ex+ exception happend for a retriable request.
  135. 16 def retryable_error?(ex)
  136. 3281 RETRYABLE_ERRORS.any? { |klass| ex.is_a?(klass) }
  137. end
  138. 16 def proxy_error?(request, response, _)
  139. 56 super && !request.retries.positive?
  140. end
  141. #
  142. # Attempt to set the request to perform a partial range request.
  143. # This happens if the peer server accepts byte-range requests, and
  144. # the last response contains some body payload.
  145. #
  146. 16 def try_partial_retry(request, response)
  147. 440 response = response.response if response.is_a?(ErrorResponse)
  148. 440 return unless response
  149. 207 unless response.headers.key?("accept-ranges") &&
  150. response.headers["accept-ranges"] == "bytes" && # there's nothing else supported though...
  151. 14 (original_body = response.body)
  152. 193 response.body.close
  153. 193 return
  154. end
  155. 14 request.partial_response = response
  156. 14 size = original_body.bytesize
  157. 14 request.headers["range"] = "bytes=#{size}-"
  158. end
  159. end
  160. 16 module RequestMethods
  161. # number of retries left.
  162. 16 attr_accessor :retries
  163. # a response partially received before.
  164. 16 attr_writer :partial_response
  165. # initializes the request instance, sets the number of retries for the request.
  166. 16 def initialize(*args)
  167. 768 super
  168. 768 @retries = @options.max_retries
  169. end
  170. 16 def response=(response)
  171. 1222 if @partial_response
  172. 14 if response.is_a?(Response) && response.status == 206
  173. 14 response.from_partial_response(@partial_response)
  174. else
  175. @partial_response.close
  176. end
  177. 14 @partial_response = nil
  178. end
  179. 1222 super
  180. end
  181. end
  182. 16 module ResponseMethods
  183. 16 def from_partial_response(response)
  184. 14 @status = response.status
  185. 14 @headers = response.headers
  186. 14 @body = response.body
  187. end
  188. end
  189. end
  190. 16 register_plugin :retries, Retries
  191. end
  192. 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. 112 mask_addr >>= 1 while (mask_addr & 0x1).zero?
  17. 112 length = 0
  18. 112 while mask_addr & 0x1 == 0x1
  19. 1771 length += 1
  20. 1771 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. 1 IPV4_BLACKLIST = [
  29. 6 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. 2 IPV6_BLACKLIST = ([
  47. 6 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. 68 range = ipaddr.to_range
  70. 68 return true if range.first != range.last
  71. 82 return IPV6_BLACKLIST.any? { |r| r.include?(ipaddr) } if ipaddr.ipv6?
  72. 584 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 private
  80. 7 def option_allowed_schemes(value)
  81. 68 Array(value)
  82. end
  83. end
  84. 7 module InstanceMethods
  85. 7 def send_requests(*requests)
  86. 75 responses = requests.map do |request|
  87. 75 next if @options.allowed_schemes.include?(request.uri.scheme)
  88. 7 error = ServerSideRequestForgeryError.new("#{request.uri} URI scheme not allowed")
  89. 7 error.set_backtrace(caller)
  90. 7 response = ErrorResponse.new(request, error)
  91. 7 request.emit(:response, response)
  92. 7 response
  93. end
  94. 150 allowed_requests = requests.select { |req| responses[requests.index(req)].nil? }
  95. 75 allowed_responses = super(*allowed_requests)
  96. 75 allowed_responses.each_with_index do |res, idx|
  97. 68 req = allowed_requests[idx]
  98. 68 responses[requests.index(req)] = res
  99. end
  100. 75 responses
  101. end
  102. end
  103. 7 module ConnectionMethods
  104. 7 def initialize(*)
  105. begin
  106. 68 super
  107. 8 rescue ServerSideRequestForgeryError => e
  108. # may raise when IPs are passed as options via :addresses
  109. 14 throw(:resolve_error, e)
  110. end
  111. end
  112. 7 def addresses=(addrs)
  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

97.78% lines covered

90 relevant lines. 88 lines covered and 2 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 module HTTPX
  3. 13 class StreamResponse
  4. 13 attr_reader :request
  5. 13 def initialize(request, session)
  6. 168 @request = request
  7. 168 @options = @request.options
  8. 168 @session = session
  9. 168 @response_enum = nil
  10. 168 @buffered_chunks = []
  11. end
  12. 13 def each(&block)
  13. 280 return enum_for(__method__) unless block
  14. 182 if (response_enum = @response_enum)
  15. 14 @response_enum = nil
  16. # streaming already started, let's finish it
  17. 38 while (chunk = @buffered_chunks.shift)
  18. 14 block.call(chunk)
  19. end
  20. # consume enum til the end
  21. 1 begin
  22. 47 while (chunk = response_enum.next)
  23. 23 block.call(chunk)
  24. end
  25. rescue StopIteration
  26. 14 return
  27. end
  28. end
  29. 168 @request.stream = self
  30. 17 begin
  31. 168 @on_chunk = block
  32. 168 response = @session.request(@request)
  33. 154 response.raise_for_status
  34. ensure
  35. 154 @on_chunk = nil
  36. end
  37. end
  38. 13 def each_line
  39. 96 return enum_for(__method__) unless block_given?
  40. 48 line = "".b
  41. 48 each do |chunk|
  42. 39 line << chunk
  43. 116 while (idx = line.index("\n"))
  44. 48 yield line.byteslice(0..idx - 1)
  45. 48 line = line.byteslice(idx + 1..-1)
  46. end
  47. end
  48. 20 yield line unless line.empty?
  49. end
  50. # This is a ghost method. It's to be used ONLY internally, when processing streams
  51. 13 def on_chunk(chunk)
  52. 311 raise NoMethodError unless @on_chunk
  53. 311 @on_chunk.call(chunk)
  54. end
  55. skipped # :nocov:
  56. skipped def inspect
  57. skipped "#<#{self.class}:#{object_id}>"
  58. skipped end
  59. skipped # :nocov:
  60. 13 def to_s
  61. 14 if @request.response
  62. @request.response.to_s
  63. else
  64. 14 @buffered_chunks.join
  65. end
  66. end
  67. 13 private
  68. 13 def response
  69. 340 @request.response || begin
  70. 28 response_enum = each
  71. 52 while (chunk = response_enum.next)
  72. 28 @buffered_chunks << chunk
  73. 28 break if @request.response
  74. end
  75. 28 @response_enum = response_enum
  76. 28 @request.response
  77. end
  78. end
  79. 13 def respond_to_missing?(meth, include_private)
  80. 18 if (response = @request.response)
  81. response.respond_to_missing?(meth, include_private)
  82. else
  83. 18 @options.response_class.method_defined?(meth) || (include_private && @options.response_class.private_method_defined?(meth))
  84. end || super
  85. end
  86. 13 def method_missing(meth, *args, **kwargs, &block)
  87. 170 return super unless response.respond_to?(meth)
  88. 170 response.__send__(meth, *args, **kwargs, &block)
  89. end
  90. end
  91. 13 module Plugins
  92. #
  93. # This plugin adds support for streaming a response (useful for i.e. "text/event-stream" payloads).
  94. #
  95. # https://gitlab.com/os85/httpx/wikis/Stream
  96. #
  97. 13 module Stream
  98. 13 def self.extra_options(options)
  99. 296 options.merge(timeout: { read_timeout: Float::INFINITY, operation_timeout: 60 })
  100. end
  101. 13 module InstanceMethods
  102. 13 def request(*args, stream: false, **options)
  103. 466 return super(*args, **options) unless stream
  104. 182 requests = args.first.is_a?(Request) ? args : build_requests(*args, options)
  105. 182 raise Error, "only 1 response at a time is supported for streaming requests" unless requests.size == 1
  106. 168 request = requests.first
  107. 168 StreamResponse.new(request, self)
  108. end
  109. end
  110. 13 module RequestMethods
  111. 13 attr_accessor :stream
  112. end
  113. 13 module ResponseMethods
  114. 13 def stream
  115. 278 request = @request.root_request if @request.respond_to?(:root_request)
  116. 278 request ||= @request
  117. 278 request.stream
  118. end
  119. end
  120. 13 module ResponseBodyMethods
  121. 13 def initialize(*)
  122. 278 super
  123. 278 @stream = @response.stream
  124. end
  125. 13 def write(chunk)
  126. 437 return super unless @stream
  127. 353 return 0 if chunk.empty?
  128. 311 chunk = decode_chunk(chunk)
  129. 311 @stream.on_chunk(chunk.dup)
  130. 297 chunk.size
  131. end
  132. 13 private
  133. 13 def transition(*)
  134. 108 return if @stream
  135. 108 super
  136. end
  137. end
  138. end
  139. 13 register_plugin :stream, Stream
  140. end
  141. end

lib/httpx/plugins/stream_bidi.rb

99.28% lines covered

138 relevant lines. 137 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin adds support for bidirectional HTTP/2 streams.
  6. #
  7. # https://gitlab.com/os85/httpx/wikis/StreamBidi
  8. #
  9. # It is required that the request body allows chunk to be buffered, (i.e., responds to +#<<(chunk)+).
  10. 7 module StreamBidi
  11. # Extension of the Connection::HTTP2 class, which adds functionality to
  12. # deal with a request that can't be drained and must be interleaved with
  13. # the response streams.
  14. #
  15. # The streams keeps send DATA frames while there's data; when they're ain't,
  16. # the stream is kept open; it must be explicitly closed by the end user.
  17. #
  18. 7 class HTTP2Bidi < Connection::HTTP2
  19. 7 def initialize(*)
  20. 14 super
  21. 14 @lock = Thread::Mutex.new
  22. end
  23. 7 %i[close empty? exhausted? send <<].each do |lock_meth|
  24. 35 class_eval(<<-METH, __FILE__, __LINE__ + 1)
  25. # lock.aware version of +#{lock_meth}+
  26. def #{lock_meth}(*) # def close(*)
  27. return super if @lock.owned?
  28. # small race condition between
  29. # checking for ownership and
  30. # acquiring lock.
  31. # TODO: fix this at the parser.
  32. @lock.synchronize { super }
  33. end
  34. METH
  35. end
  36. 7 private
  37. 7 %i[join_headers join_trailers join_body].each do |lock_meth|
  38. 21 class_eval(<<-METH, __FILE__, __LINE__ + 1)
  39. # lock.aware version of +#{lock_meth}+
  40. private def #{lock_meth}(*) # private def join_headers(*)
  41. return super if @lock.owned?
  42. # small race condition between
  43. # checking for ownership and
  44. # acquiring lock.
  45. # TODO: fix this at the parser.
  46. @lock.synchronize { super }
  47. end
  48. METH
  49. end
  50. 7 def handle_stream(stream, request)
  51. 14 request.on(:body) do
  52. 84 next unless request.headers_sent
  53. 70 handle(request, stream)
  54. 70 emit(:flush_buffer)
  55. end
  56. 14 super
  57. end
  58. # when there ain't more chunks, it makes the buffer as full.
  59. 7 def send_chunk(request, stream, chunk, next_chunk)
  60. 84 super
  61. 84 return if next_chunk
  62. 84 request.transition(:waiting_for_chunk)
  63. 84 throw(:buffer_full)
  64. end
  65. # sets end-stream flag when the request is closed.
  66. 7 def end_stream?(request, next_chunk)
  67. 84 request.closed? && next_chunk.nil?
  68. end
  69. end
  70. # BidiBuffer is a Buffer which can be receive data from threads othr
  71. # than the thread of the corresponding Connection/Session.
  72. #
  73. # It synchronizes access to a secondary internal +@oob_buffer+, which periodically
  74. # is reconciled to the main internal +@buffer+.
  75. 7 class BidiBuffer < Buffer
  76. 7 def initialize(*)
  77. 14 super
  78. 14 @parent_thread = Thread.current
  79. 14 @oob_mutex = Thread::Mutex.new
  80. 14 @oob_buffer = "".b
  81. end
  82. # buffers the +chunk+ to be sent
  83. 7 def <<(chunk)
  84. 154 return super if Thread.current == @parent_thread
  85. 70 @oob_mutex.synchronize { @oob_buffer << chunk }
  86. end
  87. # reconciles the main and secondary buffer (which receives data from other threads).
  88. 7 def rebuffer
  89. 889 raise Error, "can only rebuffer while waiting on a response" unless Thread.current == @parent_thread
  90. 889 @oob_mutex.synchronize do
  91. 889 @buffer << @oob_buffer
  92. 889 @oob_buffer.clear
  93. end
  94. end
  95. end
  96. # Proxy to wake up the session main loop when one
  97. # of the connections has buffered data to write. It abides by the HTTPX::_Selectable API,
  98. # which allows it to be registered in the selector alongside actual HTTP-based
  99. # HTTPX::Connection objects.
  100. 7 class Signal
  101. 7 def initialize
  102. 14 @closed = false
  103. 14 @pipe_read, @pipe_write = IO.pipe
  104. end
  105. 7 def state
  106. 212 @closed ? :closed : :open
  107. end
  108. # noop
  109. 7 def log(**, &_); end
  110. 7 def to_io
  111. 424 @pipe_read.to_io
  112. end
  113. 7 def wakeup
  114. 70 return if @closed
  115. 70 @pipe_write.write("\0")
  116. end
  117. 7 def call
  118. 65 return if @closed
  119. 65 @pipe_read.readpartial(1)
  120. end
  121. 7 def interests
  122. 212 return if @closed
  123. 212 :r
  124. end
  125. 7 def timeout; end
  126. 7 def terminate
  127. 14 @pipe_write.close
  128. 14 @pipe_read.close
  129. 14 @closed = true
  130. end
  131. # noop (the owner connection will take of it)
  132. 7 def handle_socket_timeout(interval); end
  133. end
  134. 7 class << self
  135. 7 def load_dependencies(klass)
  136. 14 klass.plugin(:stream)
  137. end
  138. 7 def extra_options(options)
  139. 14 options.merge(fallback_protocol: "h2")
  140. end
  141. end
  142. 7 module InstanceMethods
  143. 7 def initialize(*)
  144. 14 @signal = Signal.new
  145. 14 super
  146. end
  147. 7 def close(selector = Selector.new)
  148. 14 @signal.terminate
  149. 14 selector.deregister(@signal)
  150. 14 super(selector)
  151. end
  152. 7 def select_connection(connection, selector)
  153. 28 super
  154. 28 selector.register(@signal)
  155. 28 connection.signal = @signal
  156. end
  157. 7 def deselect_connection(connection, *)
  158. 14 super
  159. 14 connection.signal = nil
  160. end
  161. end
  162. # Adds synchronization to request operations which may buffer payloads from different
  163. # threads.
  164. 7 module RequestMethods
  165. 7 attr_accessor :headers_sent
  166. 7 def initialize(*)
  167. 14 super
  168. 14 @headers_sent = false
  169. 14 @closed = false
  170. 14 @mutex = Thread::Mutex.new
  171. end
  172. 7 def closed?
  173. 84 @closed
  174. end
  175. 7 def can_buffer?
  176. 193 super && @state != :waiting_for_chunk
  177. end
  178. # overrides state management transitions to introduce an intermediate
  179. # +:waiting_for_chunk+ state, which the request transitions to once payload
  180. # is buffered.
  181. 7 def transition(nextstate)
  182. 326 headers_sent = @headers_sent
  183. 326 case nextstate
  184. when :waiting_for_chunk
  185. 84 return unless @state == :body
  186. when :body
  187. 155 case @state
  188. when :headers
  189. 14 headers_sent = true
  190. when :waiting_for_chunk
  191. # HACK: to allow super to pass through
  192. 70 @state = :headers
  193. end
  194. end
  195. 326 super.tap do
  196. # delay setting this up until after the first transition to :body
  197. 326 @headers_sent = headers_sent
  198. end
  199. end
  200. 7 def <<(chunk)
  201. 70 @mutex.synchronize do
  202. 70 if @drainer
  203. 70 @body.clear if @body.respond_to?(:clear)
  204. 70 @drainer = nil
  205. end
  206. 70 @body << chunk
  207. 70 transition(:body)
  208. end
  209. end
  210. 7 def close
  211. 14 @mutex.synchronize do
  212. 14 return if @closed
  213. 14 @closed = true
  214. end
  215. # last chunk to send which ends the stream
  216. 14 self << ""
  217. end
  218. end
  219. 7 module RequestBodyMethods
  220. 7 def initialize(*, **)
  221. 14 super
  222. 14 @headers.delete("content-length")
  223. end
  224. 7 def empty?
  225. 99 false
  226. end
  227. end
  228. # overrides the declaration of +@write_buffer+, which is now a thread-safe buffer
  229. # responding to the same API.
  230. 7 module ConnectionMethods
  231. 7 attr_writer :signal
  232. 7 def initialize(*)
  233. 14 super
  234. 14 @write_buffer = BidiBuffer.new(@options.buffer_size)
  235. end
  236. # rebuffers the +@write_buffer+ before calculating interests.
  237. 7 def interests
  238. 889 @write_buffer.rebuffer
  239. 889 super
  240. end
  241. 7 private
  242. 7 def parser_type(protocol)
  243. 14 return HTTP2Bidi if protocol == "h2"
  244. super
  245. end
  246. 7 def set_parser_callbacks(parser)
  247. 14 super
  248. 14 parser.on(:flush_buffer) do
  249. 70 @signal.wakeup if @signal
  250. end
  251. end
  252. end
  253. end
  254. 7 register_plugin :stream_bidi, StreamBidi
  255. end
  256. end

lib/httpx/plugins/upgrade.rb

100.0% lines covered

38 relevant lines. 38 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. 27 klass.plugin(:"upgrade/h2")
  14. end
  15. 7 def extra_options(options)
  16. 27 options.merge(upgrade_handlers: {})
  17. end
  18. end
  19. 7 module OptionsMethods
  20. 7 private
  21. 7 def option_upgrade_handlers(value)
  22. 89 raise TypeError, ":upgrade_handlers must be a Hash" unless value.is_a?(Hash)
  23. 89 value
  24. end
  25. end
  26. 7 module InstanceMethods
  27. 7 def fetch_response(request, selector, options)
  28. 240 response = super
  29. 240 if response
  30. 93 return response unless response.is_a?(Response)
  31. 93 return response unless response.headers.key?("upgrade")
  32. 45 upgrade_protocol = response.headers["upgrade"].split(/ *, */).first
  33. 45 return response unless upgrade_protocol && options.upgrade_handlers.key?(upgrade_protocol)
  34. 45 protocol_handler = options.upgrade_handlers[upgrade_protocol]
  35. 45 return response unless protocol_handler
  36. 45 log { "upgrading to #{upgrade_protocol}..." }
  37. 45 connection = find_connection(request.uri, selector, options)
  38. # do not upgrade already upgraded connections
  39. 45 return if connection.upgrade_protocol == upgrade_protocol
  40. 27 protocol_handler.call(connection, request, response)
  41. # keep in the loop if the server is switching, unless
  42. # the connection has been hijacked, in which case you want
  43. # to terminante immediately
  44. 27 return if response.status == 101 && !connection.hijacked
  45. end
  46. 160 response
  47. end
  48. end
  49. 7 module ConnectionMethods
  50. 7 attr_reader :upgrade_protocol, :hijacked
  51. 7 def initialize(*)
  52. 34 super
  53. 34 @upgrade_protocol = nil
  54. end
  55. 7 def hijack_io
  56. 7 @hijacked = true
  57. # connection is taken away from selector and not given back to the pool.
  58. 7 @current_session.deselect_connection(self, @current_selector, true)
  59. end
  60. end
  61. end
  62. 7 register_plugin(:upgrade, Upgrade)
  63. end
  64. end

lib/httpx/plugins/upgrade/h2.rb

89.66% lines covered

29 relevant lines. 26 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 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. 27 options.merge(upgrade_handlers: options.upgrade_handlers.merge("h2" => self))
  14. end
  15. 7 def call(connection, _request, _response)
  16. 6 connection.upgrade_to_h2
  17. end
  18. end
  19. 7 module ConnectionMethods
  20. 7 using URIExtensions
  21. 7 def interests
  22. 755 return super unless connecting? && @parser
  23. 12 connect
  24. 12 return @io.interests if connecting?
  25. super
  26. end
  27. 7 def upgrade_to_h2
  28. 6 prev_parser = @parser
  29. 6 if prev_parser
  30. 6 prev_parser.reset
  31. 6 @inflight -= prev_parser.requests.size
  32. end
  33. 6 @parser = @options.http2_class.new(@write_buffer, @options)
  34. 6 set_parser_callbacks(@parser)
  35. 6 @upgrade_protocol = "h2"
  36. # what's happening here:
  37. # a deviation from the state machine is done to perform the actions when a
  38. # connection is closed, without transitioning, so the connection is kept in the pool.
  39. # the state is reset to initial, so that the socket reconnect works out of the box,
  40. # while the parser is already here.
  41. 6 purge_after_closed
  42. 6 transition(:idle)
  43. 6 prev_parser.requests.each do |req|
  44. req.transition(:idle)
  45. send(req)
  46. end
  47. end
  48. end
  49. end
  50. 7 register_plugin(:"upgrade/h2", H2)
  51. end
  52. end

lib/httpx/plugins/webdav.rb

100.0% lines covered

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

lib/httpx/plugins/xml.rb

100.0% lines covered

34 relevant lines. 34 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 7 module HTTPX
  3. 7 module Plugins
  4. #
  5. # This plugin supports request XML encoding/response decoding using the nokogiri gem.
  6. #
  7. # https://gitlab.com/os85/httpx/wikis/XML
  8. #
  9. 7 module XML
  10. 7 MIME_TYPES = %r{\b(application|text)/(.+\+)?xml\b}.freeze
  11. 7 module Transcoder
  12. 7 module_function
  13. 7 class Encoder
  14. 7 def initialize(xml)
  15. 140 @raw = xml
  16. end
  17. 7 def content_type
  18. 140 charset = @raw.respond_to?(:encoding) && @raw.encoding ? @raw.encoding.to_s.downcase : "utf-8"
  19. 140 "application/xml; charset=#{charset}"
  20. end
  21. 7 def bytesize
  22. 448 @raw.to_s.bytesize
  23. end
  24. 7 def to_s
  25. 140 @raw.to_s
  26. end
  27. end
  28. 7 def encode(xml)
  29. 140 Encoder.new(xml)
  30. end
  31. 7 def decode(response)
  32. 21 content_type = response.content_type.mime_type
  33. 21 raise HTTPX::Error, "invalid form mime type (#{content_type})" unless MIME_TYPES.match?(content_type)
  34. 21 Nokogiri::XML.method(:parse)
  35. end
  36. end
  37. 7 class << self
  38. 7 def load_dependencies(*)
  39. 126 require "nokogiri"
  40. end
  41. end
  42. 7 module ResponseMethods
  43. # decodes the response payload into a Nokogiri::XML::Node object **if** the payload is valid
  44. # "application/xml" (requires the "nokogiri" gem).
  45. 7 def xml
  46. 14 decode(Transcoder)
  47. end
  48. end
  49. 7 module RequestBodyClassMethods
  50. # ..., xml: Nokogiri::XML::Node #=> xml encoder
  51. 7 def initialize_body(params)
  52. 518 if (xml = params.delete(:xml))
  53. # @type var xml: Nokogiri::XML::Node | String
  54. 140 return Transcoder.encode(xml)
  55. end
  56. 378 super
  57. end
  58. end
  59. end
  60. 7 register_plugin(:xml, XML)
  61. end
  62. 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. 26 module HTTPX
  3. 26 module ResponsePatternMatchExtensions
  4. 26 def deconstruct
  5. 30 [@status, @headers, @body]
  6. end
  7. 26 def deconstruct_keys(_keys)
  8. 60 { status: @status, headers: @headers, body: @body }
  9. end
  10. end
  11. 26 module ErrorResponsePatternMatchExtensions
  12. 26 def deconstruct
  13. 6 [@error]
  14. end
  15. 26 def deconstruct_keys(_keys)
  16. 30 { error: @error }
  17. end
  18. end
  19. 26 module HeadersPatternMatchExtensions
  20. 26 def deconstruct
  21. 6 to_a
  22. end
  23. end
  24. 26 Headers.include HeadersPatternMatchExtensions
  25. 26 Response.include ResponsePatternMatchExtensions
  26. 26 ErrorResponse.include ErrorResponsePatternMatchExtensions
  27. end

lib/httpx/pool.rb

100.0% lines covered

90 relevant lines. 90 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "httpx/selector"
  3. 26 require "httpx/connection"
  4. 26 require "httpx/connection/http2"
  5. 26 require "httpx/connection/http1"
  6. 26 require "httpx/resolver"
  7. 26 module HTTPX
  8. 26 class Pool
  9. 26 using ArrayExtensions::FilterMap
  10. 26 using URIExtensions
  11. 26 POOL_TIMEOUT = 5
  12. # Sets up the connection pool with the given +options+, which can be the following:
  13. #
  14. # :max_connections:: the maximum number of connections held in the pool.
  15. # :max_connections_per_origin :: the maximum number of connections held in the pool pointing to a given origin.
  16. # :pool_timeout :: the number of seconds to wait for a connection to a given origin (before raising HTTPX::PoolTimeoutError)
  17. #
  18. 26 def initialize(options)
  19. 10275 @max_connections = options.fetch(:max_connections, Float::INFINITY)
  20. 10275 @max_connections_per_origin = options.fetch(:max_connections_per_origin, Float::INFINITY)
  21. 10275 @pool_timeout = options.fetch(:pool_timeout, POOL_TIMEOUT)
  22. 16588 @resolvers = Hash.new { |hs, resolver_type| hs[resolver_type] = [] }
  23. 10275 @resolver_mtx = Thread::Mutex.new
  24. 10275 @connections = []
  25. 10275 @connection_mtx = Thread::Mutex.new
  26. 10275 @connections_counter = 0
  27. 10275 @max_connections_cond = ConditionVariable.new
  28. 10275 @origin_counters = Hash.new(0)
  29. 15821 @origin_conds = Hash.new { |hs, orig| hs[orig] = ConditionVariable.new }
  30. end
  31. # connections returned by this function are not expected to return to the connection pool.
  32. 26 def pop_connection
  33. 10542 @connection_mtx.synchronize do
  34. 10542 drop_connection
  35. end
  36. end
  37. # opens a connection to the IP reachable through +uri+.
  38. # Many hostnames are reachable through the same IP, so we try to
  39. # maximize pipelining by opening as few connections as possible.
  40. #
  41. 26 def checkout_connection(uri, options)
  42. 7353 return checkout_new_connection(uri, options) if options.io
  43. 7294 @connection_mtx.synchronize do
  44. 7294 acquire_connection(uri, options) || begin
  45. 6710 if @connections_counter == @max_connections
  46. # this takes precedence over per-origin
  47. 14 @max_connections_cond.wait(@connection_mtx, @pool_timeout)
  48. 14 if (conn = acquire_connection(uri, options))
  49. 2 return conn
  50. end
  51. 12 if @connections_counter == @max_connections
  52. # if no matching usable connection was found, the pool will make room and drop a closed connection. if none is found,
  53. # this means that all of them are persistent or being used, so raise a timeout error.
  54. 9 conn = @connections.find { |c| c.state == :closed }
  55. raise PoolTimeoutError.new(@pool_timeout,
  56. 8 "Timed out after #{@pool_timeout} seconds while waiting for a connection") unless conn
  57. 1 drop_connection(conn)
  58. end
  59. end
  60. 6701 if @origin_counters[uri.origin] == @max_connections_per_origin
  61. 14 @origin_conds[uri.origin].wait(@connection_mtx, @pool_timeout)
  62. 14 return acquire_connection(uri, options) ||
  63. raise(PoolTimeoutError.new(@pool_timeout,
  64. "Timed out after #{@pool_timeout} seconds while waiting for a connection to #{uri.origin}"))
  65. end
  66. 6687 @connections_counter += 1
  67. 6687 @origin_counters[uri.origin] += 1
  68. 6687 checkout_new_connection(uri, options)
  69. end
  70. end
  71. end
  72. 26 def checkin_connection(connection)
  73. 7227 return if connection.options.io
  74. 7168 @connection_mtx.synchronize do
  75. 7168 @connections << connection
  76. 7168 @max_connections_cond.signal
  77. 7168 @origin_conds[connection.origin.to_s].signal
  78. end
  79. end
  80. 26 def checkout_mergeable_connection(connection)
  81. 6706 return if connection.options.io
  82. 6706 @connection_mtx.synchronize do
  83. 6706 idx = @connections.find_index do |ch|
  84. 211 ch != connection && ch.mergeable?(connection)
  85. end
  86. 6706 @connections.delete_at(idx) if idx
  87. end
  88. end
  89. 26 def reset_resolvers
  90. 13084 @resolver_mtx.synchronize { @resolvers.clear }
  91. end
  92. 26 def checkout_resolver(options)
  93. 6531 resolver_type = options.resolver_class
  94. 6531 resolver_type = Resolver.resolver_for(resolver_type, options)
  95. 6531 @resolver_mtx.synchronize do
  96. 6531 resolvers = @resolvers[resolver_type]
  97. 6531 idx = resolvers.find_index do |res|
  98. 29 res.options == options
  99. end
  100. 6531 resolvers.delete_at(idx) if idx
  101. end || checkout_new_resolver(resolver_type, options)
  102. end
  103. 26 def checkin_resolver(resolver)
  104. 333 @resolver_mtx.synchronize do
  105. 333 resolvers = @resolvers[resolver.class]
  106. 333 resolver = resolver.multi
  107. 333 resolvers << resolver unless resolvers.include?(resolver)
  108. end
  109. end
  110. skipped # :nocov:
  111. skipped def inspect
  112. skipped "#<#{self.class}:#{object_id} " \
  113. skipped "@max_connections_per_origin=#{@max_connections_per_origin} " \
  114. skipped "@pool_timeout=#{@pool_timeout} " \
  115. skipped "@connections=#{@connections.size}>"
  116. skipped end
  117. skipped # :nocov:
  118. 26 private
  119. 26 def acquire_connection(uri, options)
  120. 7322 idx = @connections.find_index do |connection|
  121. 785 connection.match?(uri, options)
  122. end
  123. 7322 return unless idx
  124. 593 @connections.delete_at(idx)
  125. end
  126. 26 def checkout_new_connection(uri, options)
  127. 6753 options.connection_class.new(uri, options)
  128. end
  129. 26 def checkout_new_resolver(resolver_type, options)
  130. 6506 if resolver_type.multi?
  131. 6474 Resolver::Multi.new(resolver_type, options)
  132. else
  133. 32 resolver_type.new(options)
  134. end
  135. end
  136. # drops and returns the +connection+ from the connection pool; if +connection+ is <tt>nil</tt> (default),
  137. # the first available connection from the pool will be dropped.
  138. 26 def drop_connection(connection = nil)
  139. 10543 if connection
  140. 1 @connections.delete(connection)
  141. else
  142. 10542 connection = @connections.shift
  143. 10542 return unless connection
  144. end
  145. 4001 @connections_counter -= 1
  146. 4001 @origin_conds.delete(connection.origin) if (@origin_counters[connection.origin.to_s] -= 1).zero?
  147. 4001 connection
  148. end
  149. end
  150. 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. 26 module HTTPX
  3. 26 module Punycode
  4. 26 module_function
  5. begin
  6. 26 require "idnx"
  7. 25 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

133 relevant lines. 133 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "delegate"
  3. 26 require "forwardable"
  4. 26 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. 26 class Request
  8. 26 extend Forwardable
  9. 26 include Loggable
  10. 26 include Callbacks
  11. 26 using URIExtensions
  12. 26 ALLOWED_URI_SCHEMES = %w[https http].freeze
  13. # the upcased string HTTP verb for this request.
  14. 26 attr_reader :verb
  15. # the absolute URI object for this request.
  16. 26 attr_reader :uri
  17. # an HTTPX::Headers object containing the request HTTP headers.
  18. 26 attr_reader :headers
  19. # an HTTPX::Request::Body object containing the request body payload (or +nil+, whenn there is none).
  20. 26 attr_reader :body
  21. # a symbol describing which frame is currently being flushed.
  22. 26 attr_reader :state
  23. # an HTTPX::Options object containing request options.
  24. 26 attr_reader :options
  25. # the corresponding HTTPX::Response object, when there is one.
  26. 26 attr_reader :response
  27. # Exception raised during enumerable body writes.
  28. 26 attr_reader :drain_error
  29. # The IP address from the peer server.
  30. 26 attr_accessor :peer_address
  31. 26 attr_writer :persistent
  32. 26 attr_reader :active_timeouts
  33. # will be +true+ when request body has been completely flushed.
  34. 26 def_delegator :@body, :empty?
  35. # closes the body
  36. 26 def_delegator :@body, :close
  37. # initializes the instance with the given +verb+ (an upppercase String, ex. 'GEt'),
  38. # an absolute or relative +uri+ (either as String or URI::HTTP object), the
  39. # request +options+ (instance of HTTPX::Options) and an optional Hash of +params+.
  40. #
  41. # Besides any of the options documented in HTTPX::Options (which would override or merge with what
  42. # +options+ sets), it accepts also the following:
  43. #
  44. # :params :: hash or array of key-values which will be encoded and set in the query string of request uris.
  45. # :body :: to be encoded in the request body payload. can be a String, an IO object (i.e. a File), or an Enumerable.
  46. # :form :: hash of array of key-values which will be form-urlencoded- or multipart-encoded in requests body payload.
  47. # :json :: hash of array of key-values which will be JSON-encoded in requests body payload.
  48. # :xml :: Nokogiri XML nodes which will be encoded in requests body payload.
  49. #
  50. # :body, :form, :json and :xml are all mutually exclusive, i.e. only one of them gets picked up.
  51. 26 def initialize(verb, uri, options, params = EMPTY_HASH)
  52. 9377 @verb = verb.to_s.upcase
  53. 9377 @uri = Utils.to_uri(uri)
  54. 9376 @headers = options.headers.dup
  55. 9376 merge_headers(params.delete(:headers)) if params.key?(:headers)
  56. 9376 @query_params = params.delete(:params) if params.key?(:params)
  57. 9376 @body = options.request_body_class.new(@headers, options, **params)
  58. 9369 @options = @body.options
  59. 9369 if @uri.relative? || @uri.host.nil?
  60. 528 origin = @options.origin
  61. 528 raise(Error, "invalid URI: #{@uri}") unless origin
  62. 504 base_path = @options.base_path
  63. 504 @uri = origin.merge("#{base_path}#{@uri}")
  64. end
  65. 9345 raise UnsupportedSchemeError, "#{@uri}: #{@uri.scheme}: unsupported URI scheme" unless ALLOWED_URI_SCHEMES.include?(@uri.scheme)
  66. 9333 @state = :idle
  67. 9333 @response = @peer_address = @context = @informational_status = nil
  68. 9333 @ping = false
  69. 9333 @persistent = @options.persistent
  70. 9333 @active_timeouts = []
  71. end
  72. 26 def complete!(response = @response)
  73. 7568 emit(:complete, response)
  74. end
  75. # whether request has been buffered with a ping
  76. 26 def ping?
  77. 440 @ping
  78. end
  79. # marks the request as having been buffered with a ping
  80. 26 def ping!
  81. 32 @ping = true
  82. end
  83. # the read timeout defined for this request.
  84. 26 def read_timeout
  85. 18452 @options.timeout[:read_timeout]
  86. end
  87. # the write timeout defined for this request.
  88. 26 def write_timeout
  89. 18452 @options.timeout[:write_timeout]
  90. end
  91. # the request timeout defined for this request.
  92. 26 def request_timeout
  93. 18203 @options.timeout[:request_timeout]
  94. end
  95. 26 def persistent?
  96. 4549 @persistent
  97. end
  98. # if the request contains trailer headers
  99. 26 def trailers?
  100. 2846 defined?(@trailers)
  101. end
  102. # returns an instance of HTTPX::Headers containing the trailer headers
  103. 26 def trailers
  104. 77 @trailers ||= @options.headers_class.new
  105. end
  106. # returns +:r+ or +:w+, depending on whether the request is waiting for a response or flushing.
  107. 26 def interests
  108. 40043 return :r if @state == :done || @state == :expect
  109. 4864 :w
  110. end
  111. 26 def can_buffer?
  112. 24900 @state != :done
  113. end
  114. # merges +h+ into the instance of HTTPX::Headers of the request.
  115. 26 def merge_headers(h)
  116. 1027 @headers = @headers.merge(h)
  117. 1027 return unless @headers.key?("range")
  118. 14 @headers.delete("accept-encoding")
  119. end
  120. # the URI scheme of the request +uri+.
  121. 26 def scheme
  122. 3368 @uri.scheme
  123. end
  124. # sets the +response+ on this request.
  125. 26 def response=(response)
  126. 8771 return unless response
  127. 8771 case response
  128. when Response
  129. 7779 if response.status < 200
  130. # deal with informational responses
  131. 140 if response.status == 100 && @headers.key?("expect")
  132. 119 @informational_status = response.status
  133. 119 return
  134. end
  135. # 103 Early Hints advertises resources in document to browsers.
  136. # not very relevant for an HTTP client, discard.
  137. 21 return if response.status >= 103
  138. end
  139. when ErrorResponse
  140. 992 response.error.connection = nil if response.error.respond_to?(:connection=)
  141. end
  142. 8652 @response = response
  143. 8652 emit(:response_started, response)
  144. end
  145. # returnns the URI path of the request +uri+.
  146. 26 def path
  147. 8474 path = uri.path.dup
  148. 8474 path = +"" if path.nil?
  149. 8474 path << "/" if path.empty?
  150. 8474 path << "?#{query}" unless query.empty?
  151. 8474 path
  152. end
  153. # returs the URI authority of the request.
  154. #
  155. # session.build_request("GET", "https://google.com/query").authority #=> "google.com"
  156. # session.build_request("GET", "http://internal:3182/a").authority #=> "internal:3182"
  157. 26 def authority
  158. 8127 @uri.authority
  159. end
  160. # returs the URI origin of the request.
  161. #
  162. # session.build_request("GET", "https://google.com/query").authority #=> "https://google.com"
  163. # session.build_request("GET", "http://internal:3182/a").authority #=> "http://internal:3182"
  164. 26 def origin
  165. 3661 @uri.origin
  166. end
  167. # returs the URI query string of the request (when available).
  168. #
  169. # session.build_request("GET", "https://search.com").query #=> ""
  170. # session.build_request("GET", "https://search.com?q=a").query #=> "q=a"
  171. # session.build_request("GET", "https://search.com", params: { q: "a"}).query #=> "q=a"
  172. # session.build_request("GET", "https://search.com?q=a", params: { foo: "bar"}).query #=> "q=a&foo&bar"
  173. 26 def query
  174. 9362 return @query if defined?(@query)
  175. 7772 query = []
  176. 7772 if (q = @query_params) && !q.empty?
  177. 150 query << Transcoder::Form.encode(q)
  178. end
  179. 7772 query << @uri.query if @uri.query
  180. 7772 @query = query.join("&")
  181. end
  182. # consumes and returns the next available chunk of request body that can be sent
  183. 26 def drain_body
  184. 8481 return nil if @body.nil?
  185. 8481 @drainer ||= @body.each
  186. 8481 chunk = @drainer.next.dup
  187. 5581 emit(:body_chunk, chunk)
  188. 5581 chunk
  189. rescue StopIteration
  190. 2876 nil
  191. rescue StandardError => e
  192. 24 @drain_error = e
  193. 24 nil
  194. end
  195. skipped # :nocov:
  196. skipped def inspect
  197. skipped "#<#{self.class}:#{object_id} " \
  198. skipped "#{@verb} " \
  199. skipped "#{uri} " \
  200. skipped "@headers=#{@headers} " \
  201. skipped "@body=#{@body}>"
  202. skipped end
  203. skipped # :nocov:
  204. # moves on to the +nextstate+ of the request state machine (when all preconditions are met)
  205. 26 def transition(nextstate)
  206. 38467 case nextstate
  207. when :idle
  208. 714 @body.rewind
  209. 714 @ping = false
  210. 714 @response = nil
  211. 714 @drainer = nil
  212. 714 @active_timeouts.clear
  213. when :headers
  214. 10422 return unless @state == :idle
  215. when :body
  216. 10478 return unless @state == :headers ||
  217. @state == :expect
  218. 8469 if @headers.key?("expect")
  219. 455 if @informational_status && @informational_status == 100
  220. # check for 100 Continue response, and deallocate the var
  221. # if @informational_status == 100
  222. # @response = nil
  223. # end
  224. else
  225. 345 return if @state == :expect # do not re-set it
  226. 126 nextstate = :expect
  227. end
  228. end
  229. when :trailers
  230. 8381 return unless @state == :body
  231. when :done
  232. 8388 return if @state == :expect
  233. end
  234. 33409 log(level: 3) { "#{@state}] -> #{nextstate}" }
  235. 33185 @state = nextstate
  236. 33185 emit(@state, self)
  237. 11158 nil
  238. end
  239. # whether the request supports the 100-continue handshake and already processed the 100 response.
  240. 26 def expects?
  241. 7557 @headers["expect"] == "100-continue" && @informational_status == 100 && !@response
  242. end
  243. 26 def set_timeout_callback(event, &callback)
  244. 92596 clb = once(event, &callback)
  245. # reset timeout callbacks when requests get rerouted to a different connection
  246. 92596 once(:idle) do
  247. 3420 callbacks(event).delete(clb)
  248. end
  249. end
  250. end
  251. end
  252. 26 require_relative "request/body"

lib/httpx/request/body.rb

100.0% lines covered

68 relevant lines. 68 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 module HTTPX
  3. # Implementation of the HTTP Request body as a delegator which iterates (responds to +each+) payload chunks.
  4. 26 class Request::Body < SimpleDelegator
  5. 26 class << self
  6. 26 def new(_, options, body: nil, **params)
  7. 9383 if body.is_a?(self)
  8. # request derives its options from body
  9. 14 body.options = options.merge(params)
  10. 14 return body
  11. end
  12. 9369 super
  13. end
  14. end
  15. 26 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. 26 def initialize(h, options, **params)
  25. 9369 @headers = h
  26. 9369 @body = self.class.initialize_body(params)
  27. 9369 @options = options.merge(params)
  28. 9369 if @body
  29. 2914 if @options.compress_request_body && @headers.key?("content-encoding")
  30. 87 @headers.get("content-encoding").each do |encoding|
  31. 87 @body = self.class.initialize_deflater_body(@body, encoding)
  32. end
  33. end
  34. 2914 @headers["content-type"] ||= @body.content_type
  35. 2914 @headers["content-length"] = @body.bytesize unless unbounded_body?
  36. end
  37. 9362 super(@body)
  38. end
  39. # consumes and yields the request payload in chunks.
  40. 26 def each(&block)
  41. 6015 return enum_for(__method__) unless block
  42. 3011 return if @body.nil?
  43. 2948 body = stream(@body)
  44. 2948 if body.respond_to?(:read)
  45. 5135 while (chunk = body.read(16_384))
  46. 3135 block.call(chunk)
  47. end
  48. # TODO: use copy_stream once bug is resolved: https://bugs.ruby-lang.org/issues/21131
  49. # IO.copy_stream(body, ProcIO.new(block))
  50. 1654 elsif body.respond_to?(:each)
  51. 453 body.each(&block)
  52. else
  53. 1202 block[body.to_s]
  54. end
  55. end
  56. 26 def close
  57. 428 @body.close if @body.respond_to?(:close)
  58. end
  59. # if the +@body+ is rewindable, it rewinnds it.
  60. 26 def rewind
  61. 770 return if empty?
  62. 152 @body.rewind if @body.respond_to?(:rewind)
  63. end
  64. # return +true+ if the +body+ has been fully drained (or does nnot exist).
  65. 26 def empty?
  66. 17930 return true if @body.nil?
  67. 7981 return false if chunked?
  68. 7897 @body.bytesize.zero?
  69. end
  70. # returns the +@body+ payload size in bytes.
  71. 26 def bytesize
  72. 3246 return 0 if @body.nil?
  73. 112 @body.bytesize
  74. end
  75. # sets the body to yield using chunked trannsfer encoding format.
  76. 26 def stream(body)
  77. 2948 return body unless chunked?
  78. 84 Transcoder::Chunker.encode(body.enum_for(:each))
  79. end
  80. # returns whether the body yields infinitely.
  81. 26 def unbounded_body?
  82. 3377 return @unbounded_body if defined?(@unbounded_body)
  83. 2977 @unbounded_body = !@body.nil? && (chunked? || @body.bytesize == Float::INFINITY)
  84. end
  85. # returns whether the chunked transfer encoding header is set.
  86. 26 def chunked?
  87. 18595 @headers["transfer-encoding"] == "chunked"
  88. end
  89. # sets the chunked transfer encoding header.
  90. 26 def chunk!
  91. 28 @headers.add("transfer-encoding", "chunked")
  92. end
  93. skipped # :nocov:
  94. skipped def inspect
  95. skipped "#<#{self.class}:#{object_id} " \
  96. skipped "#{unbounded_body? ? "stream" : "@bytesize=#{bytesize}"}>"
  97. skipped end
  98. skipped # :nocov:
  99. 26 class << self
  100. 26 def initialize_body(params)
  101. 9229 if (body = params.delete(:body))
  102. # @type var body: bodyIO
  103. 1295 Transcoder::Body.encode(body)
  104. 7934 elsif (form = params.delete(:form))
  105. 1406 if Transcoder::Multipart.multipart?(form)
  106. # @type var form: Transcoder::multipart_input
  107. 891 Transcoder::Multipart.encode(form)
  108. else
  109. # @type var form: Transcoder::urlencoded_input
  110. 515 Transcoder::Form.encode(form)
  111. end
  112. 6528 elsif (json = params.delete(:json))
  113. # @type var body: _ToJson
  114. 73 Transcoder::JSON.encode(json)
  115. end
  116. end
  117. # returns the +body+ wrapped with the correct deflater accordinng to the given +encodisng+.
  118. 26 def initialize_deflater_body(body, encoding)
  119. 87 case encoding
  120. when "gzip"
  121. 45 Transcoder::GZIP.encode(body)
  122. when "deflate"
  123. 21 Transcoder::Deflate.encode(body)
  124. when "identity"
  125. 14 body
  126. else
  127. 7 body
  128. end
  129. end
  130. end
  131. end
  132. end

lib/httpx/resolver.rb

98.94% lines covered

94 relevant lines. 93 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "socket"
  3. 26 require "resolv"
  4. 26 module HTTPX
  5. 26 module Resolver
  6. 26 RESOLVE_TIMEOUT = [2, 3].freeze
  7. 26 require "httpx/resolver/entry"
  8. 26 require "httpx/resolver/resolver"
  9. 26 require "httpx/resolver/system"
  10. 26 require "httpx/resolver/native"
  11. 26 require "httpx/resolver/https"
  12. 26 require "httpx/resolver/multi"
  13. 26 @lookup_mutex = Thread::Mutex.new
  14. 194 @lookups = Hash.new { |h, k| h[k] = [] }
  15. 26 @identifier_mutex = Thread::Mutex.new
  16. 26 @identifier = 1
  17. 26 @hosts_resolver = Resolv::Hosts.new
  18. 26 module_function
  19. 26 def supported_ip_families
  20. 6793 @supported_ip_families ||= begin
  21. # https://github.com/ruby/resolv/blob/095f1c003f6073730500f02acbdbc55f83d70987/lib/resolv.rb#L408
  22. 24 list = Socket.ip_address_list
  23. 97 if list.any? { |a| a.ipv6? && !a.ipv6_loopback? && !a.ipv6_linklocal? }
  24. 1 [Socket::AF_INET6, Socket::AF_INET]
  25. else
  26. 23 [Socket::AF_INET]
  27. end
  28. rescue NotImplementedError
  29. [Socket::AF_INET]
  30. end.freeze
  31. end
  32. 26 def resolver_for(resolver_type, options)
  33. 6578 case resolver_type
  34. when Symbol
  35. 6505 meth = :"resolver_#{resolver_type}_class"
  36. 6505 return options.__send__(meth) if options.respond_to?(meth)
  37. when Class
  38. 73 return resolver_type if resolver_type < Resolver
  39. end
  40. 13 raise Error, "unsupported resolver type (#{resolver_type})"
  41. end
  42. 26 def nolookup_resolve(hostname)
  43. 6350 ip_resolve(hostname) || cached_lookup(hostname) || hosts_resolve(hostname)
  44. end
  45. # tries to convert +hostname+ into an IPAddr, returns <tt>nil</tt> otherwise.
  46. 26 def ip_resolve(hostname)
  47. 6350 [Entry.new(hostname)]
  48. rescue ArgumentError
  49. end
  50. # matches +hostname+ to entries in the hosts file, returns <tt>nil</nil> if none is
  51. # found, or there is no hosts file.
  52. 26 def hosts_resolve(hostname)
  53. 547 ips = @hosts_resolver.getaddresses(hostname)
  54. 547 return if ips.empty?
  55. 780 ips.map { |ip| Entry.new(ip) }
  56. rescue IOError
  57. end
  58. 26 def cached_lookup(hostname)
  59. 5845 now = Utils.now
  60. 5845 lookup_synchronize do |lookups|
  61. 5845 lookup(hostname, lookups, now)
  62. end
  63. end
  64. 26 def cached_lookup_set(hostname, family, entries)
  65. 196 lookup_synchronize do |lookups|
  66. 196 case family
  67. when Socket::AF_INET6
  68. 40 lookups[hostname].concat(entries)
  69. when Socket::AF_INET
  70. 156 lookups[hostname].unshift(*entries)
  71. end
  72. 196 entries.each do |entry|
  73. 263 next unless entry["name"] != hostname
  74. 38 case family
  75. when Socket::AF_INET6
  76. 15 lookups[entry["name"]] << entry
  77. when Socket::AF_INET
  78. 23 lookups[entry["name"]].unshift(entry)
  79. end
  80. end
  81. end
  82. end
  83. 26 def cached_lookup_evict(hostname, ip)
  84. 41 ip = ip.to_s
  85. 41 lookup_synchronize do |lookups|
  86. 41 entries = lookups[hostname]
  87. 41 return unless entries
  88. 372 lookups.delete_if { |entry| entry["data"] == ip }
  89. end
  90. end
  91. # do not use directly!
  92. 26 def lookup(hostname, lookups, ttl)
  93. 5852 return unless lookups.key?(hostname)
  94. 5470 entries = lookups[hostname] = lookups[hostname].select do |address|
  95. 9602 address["TTL"] > ttl
  96. end
  97. 5470 ips = entries.flat_map do |address|
  98. 9593 if (als = address["alias"])
  99. 7 lookup(als, lookups, ttl)
  100. else
  101. 9586 Entry.new(address["data"], address["TTL"])
  102. end
  103. end.compact
  104. 5470 ips unless ips.empty?
  105. end
  106. 26 def generate_id
  107. 1616 id_synchronize { @identifier = (@identifier + 1) & 0xFFFF }
  108. end
  109. 26 def encode_dns_query(hostname, type: Resolv::DNS::Resource::IN::A, message_id: generate_id)
  110. 748 Resolv::DNS::Message.new(message_id).tap do |query|
  111. 808 query.rd = 1
  112. 808 query.add_question(hostname, type)
  113. 119 end.encode
  114. end
  115. 26 def decode_dns_answer(payload)
  116. 59 begin
  117. 720 message = Resolv::DNS::Message.decode(payload)
  118. rescue Resolv::DNS::DecodeError => e
  119. 6 return :decode_error, e
  120. end
  121. # no domain was found
  122. 714 return :no_domain_found if message.rcode == Resolv::DNS::RCode::NXDomain
  123. 250 return :message_truncated if message.tc == 1
  124. 238 return :dns_error, message.rcode if message.rcode != Resolv::DNS::RCode::NoError
  125. 232 addresses = []
  126. 232 now = Utils.now
  127. 232 message.each_answer do |question, _, value|
  128. 1020 case value
  129. when Resolv::DNS::Resource::IN::CNAME
  130. 26 addresses << {
  131. "name" => question.to_s,
  132. 26 "TTL" => (now + value.ttl),
  133. "alias" => value.name.to_s,
  134. }
  135. when Resolv::DNS::Resource::IN::A,
  136. Resolv::DNS::Resource::IN::AAAA
  137. 994 addresses << {
  138. "name" => question.to_s,
  139. 994 "TTL" => (now + value.ttl),
  140. "data" => value.address.to_s,
  141. }
  142. end
  143. end
  144. 232 [:ok, addresses]
  145. end
  146. 26 def lookup_synchronize
  147. 12164 @lookup_mutex.synchronize { yield(@lookups) }
  148. end
  149. 26 def id_synchronize(&block)
  150. 808 @identifier_mutex.synchronize(&block)
  151. end
  152. end
  153. end

lib/httpx/resolver/entry.rb

100.0% lines covered

16 relevant lines. 16 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "ipaddr"
  3. 26 module HTTPX
  4. 26 module Resolver
  5. 26 class Entry < SimpleDelegator
  6. 26 attr_reader :address
  7. 26 def self.convert(address)
  8. 44 new(address, rescue_on_convert: true)
  9. end
  10. 26 def initialize(address, expires_in = Float::INFINITY, rescue_on_convert: false)
  11. 17690 @expires_in = expires_in
  12. 17690 @address = address.is_a?(IPAddr) ? address : IPAddr.new(address.to_s)
  13. 11897 super(@address)
  14. rescue IPAddr::InvalidAddressError
  15. 5793 raise unless rescue_on_convert
  16. 18 @address = address.to_s
  17. 18 super(@address)
  18. end
  19. 26 def expired?
  20. 1117 @expires_in < Utils.now
  21. end
  22. end
  23. end
  24. end

lib/httpx/resolver/https.rb

86.11% lines covered

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

lib/httpx/resolver/multi.rb

89.09% lines covered

55 relevant lines. 49 lines covered and 6 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "forwardable"
  3. 26 require "resolv"
  4. 26 module HTTPX
  5. 26 class Resolver::Multi
  6. 26 include Callbacks
  7. 26 using ArrayExtensions::FilterMap
  8. 26 attr_reader :resolvers, :options
  9. 26 def initialize(resolver_type, options)
  10. 6474 @current_selector = @current_session = nil
  11. 6474 @options = options
  12. 6474 @resolver_options = @options.resolver_options
  13. 6474 ip_families = options.ip_families || Resolver.supported_ip_families
  14. 6474 @resolvers = ip_families.map do |ip_family|
  15. 6500 resolver = resolver_type.new(ip_family, options)
  16. 6500 resolver.multi = self
  17. 6500 resolver
  18. end
  19. 6474 @errors = Hash.new { |hs, k| hs[k] = [] }
  20. end
  21. 26 def current_selector=(s)
  22. 6485 @current_selector = s
  23. 12997 @resolvers.each { |r| r.__send__(__method__, s) }
  24. end
  25. 26 def current_session=(s)
  26. 6485 @current_session = s
  27. 12997 @resolvers.each { |r| r.__send__(__method__, s) }
  28. end
  29. 26 def log(*args, **kwargs, &blk)
  30. 13012 @resolvers.each { |r| r.__send__(__method__, *args, **kwargs, &blk) }
  31. end
  32. 26 def closed?
  33. @resolvers.all?(&:closed?)
  34. end
  35. 26 def empty?
  36. @resolvers.all?(&:empty?)
  37. end
  38. 26 def inflight?
  39. @resolvers.any(&:inflight?)
  40. end
  41. 26 def timeout
  42. @resolvers.filter_map(&:timeout).min
  43. end
  44. 26 def close
  45. @resolvers.each(&:close)
  46. end
  47. 26 def connections
  48. @resolvers.filter_map { |r| r.resolver_connection if r.respond_to?(:resolver_connection) }
  49. end
  50. 26 def early_resolve(connection)
  51. 6490 hostname = connection.peer.host
  52. 6490 addresses = @resolver_options[:cache] && (connection.addresses || HTTPX::Resolver.nolookup_resolve(hostname))
  53. 6490 return false unless addresses
  54. 6061 ip_families = connection.options.ip_families
  55. 6061 resolved = false
  56. 6332 addresses.group_by(&:family).sort { |(f1, _), (f2, _)| f2 <=> f1 }.each do |family, addrs|
  57. 6318 next unless ip_families.nil? || ip_families.include?(family)
  58. # try to match the resolver by family. However, there are cases where that's not possible, as when
  59. # the system does not have IPv6 connectivity, but it does support IPv6 via loopback/link-local.
  60. 12660 resolver = @resolvers.find { |r| r.family == family } || @resolvers.first
  61. 6318 next unless resolver # this should ever happen
  62. # it does not matter which resolver it is, as early-resolve code is shared.
  63. 6318 resolver.emit_addresses(connection, family, addrs, true)
  64. 6284 resolved = true
  65. end
  66. 6027 resolved
  67. end
  68. 26 def lazy_resolve(connection)
  69. 429 @resolvers.each do |resolver|
  70. 437 resolver << @current_session.try_clone_connection(connection, @current_selector, resolver.family)
  71. 425 next if resolver.empty?
  72. 341 @current_session.select_resolver(resolver, @current_selector)
  73. end
  74. end
  75. end
  76. end

lib/httpx/resolver/native.rb

91.4% lines covered

314 relevant lines. 287 lines covered and 27 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "forwardable"
  3. 26 require "resolv"
  4. 26 module HTTPX
  5. # Implements a pure ruby name resolver, which abides by the Selectable API.
  6. # It delegates DNS payload encoding/decoding to the +resolv+ stlid gem.
  7. #
  8. 26 class Resolver::Native < Resolver::Resolver
  9. 26 extend Forwardable
  10. 26 using URIExtensions
  11. 16 DEFAULTS = {
  12. 10 nameserver: nil,
  13. **Resolv::DNS::Config.default_config_hash,
  14. packet_size: 512,
  15. timeouts: Resolver::RESOLVE_TIMEOUT,
  16. }.freeze
  17. 26 DNS_PORT = 53
  18. 26 def_delegator :@connections, :empty?
  19. 26 attr_reader :state
  20. 26 def initialize(family, options)
  21. 6403 super
  22. 6403 @ns_index = 0
  23. 6403 @resolver_options = DEFAULTS.merge(@options.resolver_options)
  24. 6403 @socket_type = @resolver_options.fetch(:socket_type, :udp)
  25. 6403 @nameserver = if (nameserver = @resolver_options[:nameserver])
  26. 6397 nameserver = nameserver[family] if nameserver.is_a?(Hash)
  27. 6397 Array(nameserver)
  28. end
  29. 6403 @ndots = @resolver_options.fetch(:ndots, 1)
  30. 19209 @search = Array(@resolver_options[:search]).map { |srch| srch.scan(/[^.]+/) }
  31. 6403 @_timeouts = Array(@resolver_options[:timeouts])
  32. 7843 @timeouts = Hash.new { |timeouts, host| timeouts[host] = @_timeouts.dup }
  33. 6403 @name = nil
  34. 6403 @queries = {}
  35. 6403 @read_buffer = "".b
  36. 6403 @write_buffer = Buffer.new(@resolver_options[:packet_size])
  37. 6403 @state = :idle
  38. 6403 @timer = nil
  39. end
  40. 26 def close
  41. 333 transition(:closed)
  42. end
  43. 26 def terminate
  44. 14 emit(:close, self)
  45. end
  46. 26 def closed?
  47. 701 @state == :closed
  48. end
  49. 26 def to_io
  50. 1339 @io.to_io
  51. end
  52. 26 def call
  53. 1018 case @state
  54. when :open
  55. 1002 consume
  56. end
  57. end
  58. 26 def interests
  59. 10805 case @state
  60. when :idle
  61. 9949 transition(:open)
  62. when :closed
  63. 13 transition(:idle)
  64. 13 transition(:open)
  65. end
  66. 10805 calculate_interests
  67. end
  68. 26 def <<(connection)
  69. 347 if @nameserver.nil?
  70. 6 ex = ResolveError.new("No available nameserver")
  71. 6 ex.set_backtrace(caller)
  72. 6 connection.force_reset
  73. 6 throw(:resolve_error, ex)
  74. else
  75. 341 @connections << connection
  76. 341 resolve
  77. end
  78. end
  79. 26 def timeout
  80. 10805 return if @connections.empty?
  81. 10805 @start_timeout = Utils.now
  82. 10805 hosts = @queries.keys
  83. 10805 @timeouts.values_at(*hosts).reject(&:empty?).map(&:first).min
  84. end
  85. 26 def handle_socket_timeout(interval); end
  86. 26 private
  87. 26 def calculate_interests
  88. 15026 return if @queries.empty?
  89. 5122 return :r if @write_buffer.empty?
  90. 1619 :w
  91. end
  92. 26 def consume
  93. 1015 loop do
  94. 1757 dread if calculate_interests == :r
  95. 1722 break unless calculate_interests == :w
  96. # do_retry
  97. 760 dwrite
  98. 742 break unless calculate_interests == :r
  99. end
  100. rescue Errno::EHOSTUNREACH => e
  101. 18 @ns_index += 1
  102. 18 nameserver = @nameserver
  103. 18 if nameserver && @ns_index < nameserver.size
  104. 12 log { "resolver #{FAMILY_TYPES[@record_type]}: failed resolving on nameserver #{@nameserver[@ns_index - 1]} (#{e.message})" }
  105. 12 transition(:idle)
  106. 12 @timeouts.clear
  107. 12 retry
  108. else
  109. 6 handle_error(e)
  110. 6 emit(:close, self)
  111. end
  112. rescue NativeResolveError => e
  113. 21 handle_error(e)
  114. 21 close_or_resolve
  115. 21 retry unless closed?
  116. end
  117. 26 def schedule_retry
  118. 742 h = @name
  119. 742 return unless h
  120. 742 connection = @queries[h]
  121. 742 timeouts = @timeouts[h]
  122. 742 timeout = timeouts.shift
  123. 742 @timer = @current_selector.after(timeout) do
  124. 76 next unless @connections.include?(connection)
  125. 76 @timer = nil
  126. 76 do_retry(h, connection, timeout)
  127. end
  128. end
  129. 26 def do_retry(h, connection, interval)
  130. 76 timeouts = @timeouts[h]
  131. 76 if !timeouts.empty?
  132. 46 log { "resolver #{FAMILY_TYPES[@record_type]}: timeout after #{interval}s, retry (with #{timeouts.first}s) #{h}..." }
  133. # must downgrade to tcp AND retry on same host as last
  134. 46 downgrade_socket
  135. 46 resolve(connection, h)
  136. 30 elsif @ns_index + 1 < @nameserver.size
  137. # try on the next nameserver
  138. 6 @ns_index += 1
  139. 6 log do
  140. "resolver #{FAMILY_TYPES[@record_type]}: failed resolving #{h} on nameserver #{@nameserver[@ns_index - 1]} (timeout error)"
  141. end
  142. 6 transition(:idle)
  143. 6 @timeouts.clear
  144. 6 resolve(connection, h)
  145. else
  146. 24 @timeouts.delete(h)
  147. 24 reset_hostname(h, reset_candidates: false)
  148. 24 unless @queries.empty?
  149. 18 resolve(connection)
  150. 18 return
  151. end
  152. 6 @connections.delete(connection)
  153. 6 host = connection.peer.host
  154. # This loop_time passed to the exception is bogus. Ideally we would pass the total
  155. # resolve timeout, including from the previous retries.
  156. 6 ex = ResolveTimeoutError.new(interval, "Timed out while resolving #{host}")
  157. 6 ex.set_backtrace(ex ? ex.backtrace : caller)
  158. 6 emit_resolve_error(connection, host, ex)
  159. 6 close_or_resolve
  160. end
  161. end
  162. 26 def dread(wsize = @resolver_options[:packet_size])
  163. 1329 loop do
  164. 1341 wsize = @large_packet.capacity if @large_packet
  165. 1341 siz = @io.read(wsize, @read_buffer)
  166. 1341 unless siz
  167. ex = EOFError.new("descriptor closed")
  168. ex.set_backtrace(caller)
  169. raise ex
  170. end
  171. 1341 return unless siz.positive?
  172. 678 if @socket_type == :tcp
  173. # packet may be incomplete, need to keep draining from the socket
  174. 30 if @large_packet
  175. # large packet buffer already exists, continue pumping
  176. 12 @large_packet << @read_buffer
  177. 12 next unless @large_packet.full?
  178. 12 parse(@large_packet.to_s)
  179. 12 @large_packet = nil
  180. # downgrade to udp again
  181. 12 downgrade_socket
  182. 12 return
  183. else
  184. 18 size = @read_buffer[0, 2].unpack1("n")
  185. 18 buffer = @read_buffer.byteslice(2..-1)
  186. 18 if size > @read_buffer.bytesize
  187. # only do buffer logic if it's worth it, and the whole packet isn't here already
  188. 12 @large_packet = Buffer.new(size)
  189. 12 @large_packet << buffer
  190. 12 next
  191. else
  192. 6 parse(buffer)
  193. end
  194. end
  195. else # udp
  196. 648 parse(@read_buffer)
  197. end
  198. 619 return if @state == :closed || !@write_buffer.empty?
  199. end
  200. end
  201. 26 def dwrite
  202. 742 loop do
  203. 1484 return if @write_buffer.empty?
  204. 742 siz = @io.write(@write_buffer)
  205. 742 unless siz
  206. ex = EOFError.new("descriptor closed")
  207. ex.set_backtrace(caller)
  208. raise ex
  209. end
  210. 742 return unless siz.positive?
  211. 742 schedule_retry if @write_buffer.empty?
  212. 742 return if @state == :closed
  213. end
  214. end
  215. 26 def parse(buffer)
  216. 666 @timer.cancel
  217. 666 @timer = nil
  218. 666 code, result = Resolver.decode_dns_answer(buffer)
  219. 666 case code
  220. when :ok
  221. 214 parse_addresses(result)
  222. when :no_domain_found
  223. # Indicates no such domain was found.
  224. 428 hostname, connection = @queries.first
  225. 428 reset_hostname(hostname, reset_candidates: false)
  226. 749 other_candidate, _ = @queries.find { |_, conn| conn == connection }
  227. 428 if other_candidate
  228. 321 resolve(connection, other_candidate)
  229. else
  230. 107 @connections.delete(connection)
  231. 107 ex = NativeResolveError.new(connection, connection.peer.host, "name or service not known")
  232. 107 ex.set_backtrace(ex ? ex.backtrace : caller)
  233. 107 emit_resolve_error(connection, connection.peer.host, ex)
  234. 93 close_or_resolve
  235. end
  236. when :message_truncated
  237. # TODO: what to do if it's already tcp??
  238. 12 return if @socket_type == :tcp
  239. 12 @socket_type = :tcp
  240. 12 hostname, _ = @queries.first
  241. 12 reset_hostname(hostname)
  242. 12 transition(:closed)
  243. when :dns_error
  244. 6 hostname, connection = @queries.first
  245. 6 reset_hostname(hostname)
  246. 6 @connections.delete(connection)
  247. 6 ex = NativeResolveError.new(connection, connection.peer.host, "unknown DNS error (error code #{result})")
  248. 6 raise ex
  249. when :decode_error
  250. 6 hostname, connection = @queries.first
  251. 6 reset_hostname(hostname)
  252. 6 @connections.delete(connection)
  253. 6 ex = NativeResolveError.new(connection, connection.peer.host, result.message)
  254. 6 ex.set_backtrace(result.backtrace)
  255. 6 raise ex
  256. end
  257. end
  258. 26 def parse_addresses(addresses)
  259. 214 if addresses.empty?
  260. # no address found, eliminate candidates
  261. 9 hostname, connection = @queries.first
  262. 9 reset_hostname(hostname)
  263. 9 @connections.delete(connection)
  264. 9 raise NativeResolveError.new(connection, connection.peer.host)
  265. else
  266. 205 address = addresses.first
  267. 205 name = address["name"]
  268. 205 connection = @queries.delete(name)
  269. 205 unless connection
  270. orig_name = name
  271. # absolute name
  272. name_labels = Resolv::DNS::Name.create(name).to_a
  273. name = @queries.each_key.first { |hname| name_labels == Resolv::DNS::Name.create(hname).to_a }
  274. # probably a retried query for which there's an answer
  275. unless name
  276. @timeouts.delete(orig_name)
  277. return
  278. end
  279. address["name"] = name
  280. connection = @queries.delete(name)
  281. end
  282. 1207 alias_addresses, addresses = addresses.partition { |addr| addr.key?("alias") }
  283. 205 if addresses.empty? && !alias_addresses.empty? # CNAME
  284. 4 hostname_alias = alias_addresses.first["alias"]
  285. # clean up intermediate queries
  286. 4 @timeouts.delete(name) unless connection.peer.host == name
  287. 4 if early_resolve(connection, hostname: hostname_alias)
  288. @connections.delete(connection)
  289. else
  290. 4 if @socket_type == :tcp
  291. # must downgrade to udp if tcp
  292. @socket_type = @resolver_options.fetch(:socket_type, :udp)
  293. transition(:idle)
  294. transition(:open)
  295. end
  296. 4 log { "resolver #{FAMILY_TYPES[@record_type]}: ALIAS #{hostname_alias} for #{name}" }
  297. 4 resolve(connection, hostname_alias)
  298. 4 return
  299. end
  300. else
  301. 201 reset_hostname(name, connection: connection)
  302. 201 @timeouts.delete(connection.peer.host)
  303. 201 @connections.delete(connection)
  304. 201 Resolver.cached_lookup_set(connection.peer.host, @family, addresses) if @resolver_options[:cache]
  305. 201 catch(:coalesced) do
  306. 1177 emit_addresses(connection, @family, addresses.map { |a| Resolver::Entry.new(a["data"], a["TTL"]) })
  307. end
  308. end
  309. end
  310. 201 close_or_resolve
  311. end
  312. 26 def resolve(connection = nil, hostname = nil)
  313. 756 @connections.shift until @connections.empty? || @connections.first.state != :closed
  314. 1125 connection ||= @connections.find { |c| !@queries.value?(c) }
  315. 756 raise Error, "no URI to resolve" unless connection
  316. # do not buffer query if previous is still in the buffer or awaiting reply/retry
  317. 756 return unless @write_buffer.empty? && @timer.nil?
  318. 748 hostname ||= @queries.key(connection)
  319. 748 if hostname.nil?
  320. 353 hostname = connection.peer.host
  321. 353 if connection.peer.non_ascii_hostname
  322. log { "resolver #{FAMILY_TYPES[@record_type]}: resolve IDN #{connection.peer.non_ascii_hostname} as #{hostname}" }
  323. end
  324. 353 hostname = generate_candidates(hostname).each do |name|
  325. 1412 @queries[name] = connection
  326. end.first
  327. else
  328. 395 @queries[hostname] = connection
  329. end
  330. 748 @name = hostname
  331. 748 log { "resolver #{FAMILY_TYPES[@record_type]}: query for #{hostname}" }
  332. 59 begin
  333. 748 @write_buffer << encode_dns_query(hostname)
  334. rescue Resolv::DNS::EncodeError => e
  335. reset_hostname(hostname, connection: connection)
  336. @connections.delete(connection)
  337. emit_resolve_error(connection, hostname, e)
  338. close_or_resolve
  339. end
  340. end
  341. 26 def encode_dns_query(hostname)
  342. 748 message_id = Resolver.generate_id
  343. 748 msg = Resolver.encode_dns_query(hostname, type: @record_type, message_id: message_id)
  344. 748 msg[0, 2] = [msg.size, message_id].pack("nn") if @socket_type == :tcp
  345. 748 msg
  346. end
  347. 26 def generate_candidates(name)
  348. 353 return [name] if name.end_with?(".")
  349. 353 candidates = []
  350. 353 name_parts = name.scan(/[^.]+/)
  351. 353 candidates = [name] if @ndots <= name_parts.size - 1
  352. 1059 candidates.concat(@search.map { |domain| [*name_parts, *domain].join(".") })
  353. 353 fname = "#{name}."
  354. 353 candidates << fname unless candidates.include?(fname)
  355. 353 candidates
  356. end
  357. 26 def build_socket
  358. 363 ip, port = @nameserver[@ns_index]
  359. 363 port ||= DNS_PORT
  360. 363 case @socket_type
  361. when :udp
  362. 345 log { "resolver #{FAMILY_TYPES[@record_type]}: server: udp://#{ip}:#{port}..." }
  363. 345 UDP.new(ip, port, @options)
  364. when :tcp
  365. 18 log { "resolver #{FAMILY_TYPES[@record_type]}: server: tcp://#{ip}:#{port}..." }
  366. 18 origin = URI("tcp://#{ip}:#{port}")
  367. 18 TCP.new(origin, [Resolver::Entry.new(ip)], @options)
  368. end
  369. end
  370. 26 def downgrade_socket
  371. 58 return unless @socket_type == :tcp
  372. 12 @socket_type = @resolver_options.fetch(:socket_type, :udp)
  373. 12 transition(:idle)
  374. 12 transition(:open)
  375. end
  376. 26 def transition(nextstate)
  377. 10362 case nextstate
  378. when :idle
  379. 43 if @io
  380. 37 @io.close
  381. 37 @io = nil
  382. end
  383. when :open
  384. 9974 return unless @state == :idle
  385. 9974 @io ||= build_socket
  386. 9974 @io.connect
  387. 9974 return unless @io.connected?
  388. 363 resolve if @queries.empty? && !@connections.empty?
  389. when :closed
  390. 345 return unless @state == :open
  391. 339 @io.close if @io
  392. 339 @start_timeout = nil
  393. 339 @write_buffer.clear
  394. 339 @read_buffer.clear
  395. end
  396. 745 log(level: 3) { "#{@state} -> #{nextstate}" }
  397. 745 @state = nextstate
  398. rescue Errno::ECONNREFUSED,
  399. Errno::EADDRNOTAVAIL,
  400. Errno::EHOSTUNREACH,
  401. SocketError,
  402. IOError,
  403. ConnectTimeoutError => e
  404. # these errors may happen during TCP handshake
  405. # treat them as resolve errors.
  406. handle_error(e)
  407. emit(:close, self)
  408. end
  409. 26 def handle_error(error)
  410. 27 if error.respond_to?(:connection) &&
  411. error.respond_to?(:host)
  412. 21 reset_hostname(error.host, connection: error.connection)
  413. 21 @connections.delete(error.connection)
  414. 21 emit_resolve_error(error.connection, error.host, error)
  415. else
  416. 6 @queries.each do |host, connection|
  417. 6 reset_hostname(host, connection: connection)
  418. 6 @connections.delete(connection)
  419. 6 emit_resolve_error(connection, host, error)
  420. end
  421. 12 while (connection = @connections.shift)
  422. emit_resolve_error(connection, connection.peer.host, error)
  423. end
  424. end
  425. end
  426. 26 def reset_hostname(hostname, connection: @queries.delete(hostname), reset_candidates: true)
  427. 713 @timeouts.delete(hostname)
  428. 713 return unless connection && reset_candidates
  429. # eliminate other candidates
  430. 987 candidates = @queries.select { |_, conn| connection == conn }.keys
  431. 987 @queries.delete_if { |h, _| candidates.include?(h) }
  432. # reset timeouts
  433. 965 @timeouts.delete_if { |h, _| candidates.include?(h) }
  434. end
  435. 26 def close_or_resolve
  436. # drop already closed connections
  437. 321 @connections.shift until @connections.empty? || @connections.first.state != :closed
  438. 321 if (@connections - @queries.values).empty?
  439. 313 emit(:close, self)
  440. else
  441. 8 resolve
  442. end
  443. end
  444. end
  445. end

lib/httpx/resolver/resolver.rb

93.98% lines covered

83 relevant lines. 78 lines covered and 5 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "resolv"
  3. 26 module HTTPX
  4. # Base class for all internal internet name resolvers. It handles basic blocks
  5. # from the Selectable API.
  6. #
  7. 26 class Resolver::Resolver
  8. 26 include Callbacks
  9. 26 include Loggable
  10. 26 using ArrayExtensions::Intersect
  11. 1 RECORD_TYPES = {
  12. 25 Socket::AF_INET6 => Resolv::DNS::Resource::IN::AAAA,
  13. Socket::AF_INET => Resolv::DNS::Resource::IN::A,
  14. }.freeze
  15. 1 FAMILY_TYPES = {
  16. 25 Resolv::DNS::Resource::IN::AAAA => "AAAA",
  17. Resolv::DNS::Resource::IN::A => "A",
  18. }.freeze
  19. 26 class << self
  20. 26 def multi?
  21. 6474 true
  22. end
  23. end
  24. 26 attr_reader :family, :options
  25. 26 attr_writer :current_selector, :current_session
  26. 26 attr_accessor :multi
  27. 26 def initialize(family, options)
  28. 6532 @family = family
  29. 6532 @record_type = RECORD_TYPES[family]
  30. 6532 @options = options
  31. 6532 @connections = []
  32. 6532 set_resolver_callbacks
  33. end
  34. 26 def each_connection(&block)
  35. 222 enum_for(__method__) unless block
  36. 222 return unless @connections
  37. 222 @connections.each(&block)
  38. end
  39. 26 def close; end
  40. 26 alias_method :terminate, :close
  41. 26 def closed?
  42. true
  43. end
  44. 26 def empty?
  45. true
  46. end
  47. 26 def inflight?
  48. 14 false
  49. end
  50. 26 def emit_addresses(connection, family, addresses, early_resolve = false)
  51. 18203 addresses.map! { |address| address.is_a?(Resolver::Entry) ? address : Resolver::Entry.new(address) }
  52. # double emission check, but allow early resolution to work
  53. 6591 conn_addrs = connection.addresses
  54. 6591 return if !early_resolve && conn_addrs && (!conn_addrs.empty? && !addresses.intersect?(!conn_addrs))
  55. 6591 log do
  56. 80 "resolver #{FAMILY_TYPES[RECORD_TYPES[family]]}: " \
  57. "answer #{connection.peer.host}: #{addresses.inspect} (early resolve: #{early_resolve})"
  58. end
  59. # do not apply resolution delay for non-dns name resolution
  60. 6591 if !early_resolve &&
  61. # just in case...
  62. @current_selector &&
  63. # resolution delay only applies to IPv4
  64. family == Socket::AF_INET &&
  65. # connection already has addresses and initiated/ended handshake
  66. !connection.io &&
  67. # no need to delay if not supporting dual stack / multi-homed IP
  68. 262 (connection.options.ip_families || Resolver.supported_ip_families).size > 1 &&
  69. # connection URL host is already the IP (early resolve included perhaps?)
  70. addresses.first.to_s != connection.peer.host.to_s
  71. 8 log { "resolver #{FAMILY_TYPES[RECORD_TYPES[family]]}: applying resolution delay..." }
  72. 8 @current_selector.after(0.05) do
  73. # double emission check
  74. 8 unless connection.addresses && addresses.intersect?(connection.addresses)
  75. 8 emit_resolved_connection(connection, addresses, early_resolve)
  76. end
  77. end
  78. else
  79. 6583 emit_resolved_connection(connection, addresses, early_resolve)
  80. end
  81. end
  82. 26 private
  83. 26 def emit_resolved_connection(connection, addresses, early_resolve)
  84. begin
  85. 6591 connection.addresses = addresses
  86. 6551 return if connection.state == :closed
  87. 6551 emit(:resolve, connection)
  88. 24 rescue StandardError => e
  89. 40 if early_resolve
  90. 34 connection.force_reset
  91. 34 throw(:resolve_error, e)
  92. else
  93. 6 emit(:error, connection, e)
  94. end
  95. end
  96. end
  97. 26 def early_resolve(connection, hostname: connection.peer.host)
  98. 4 addresses = @resolver_options[:cache] && (connection.addresses || HTTPX::Resolver.nolookup_resolve(hostname))
  99. 4 return false unless addresses
  100. 14 addresses = addresses.select { |addr| addr.family == @family }
  101. 2 return false if addresses.empty?
  102. emit_addresses(connection, @family, addresses, true)
  103. true
  104. end
  105. 26 def emit_resolve_error(connection, hostname = connection.peer.host, ex = nil)
  106. 177 emit_connection_error(connection, resolve_error(hostname, ex))
  107. end
  108. 26 def resolve_error(hostname, ex = nil)
  109. 177 return ex if ex.is_a?(ResolveError) || ex.is_a?(ResolveTimeoutError)
  110. 42 message = ex ? ex.message : "Can't resolve #{hostname}"
  111. 42 error = ResolveError.new(message)
  112. 42 error.set_backtrace(ex ? ex.backtrace : caller)
  113. 42 error
  114. end
  115. 26 def set_resolver_callbacks
  116. 6532 on(:resolve, &method(:resolve_connection))
  117. 6532 on(:error, &method(:emit_connection_error))
  118. 6532 on(:close, &method(:close_resolver))
  119. end
  120. 26 def resolve_connection(connection)
  121. 6551 @current_session.__send__(:on_resolver_connection, connection, @current_selector)
  122. end
  123. 26 def emit_connection_error(connection, error)
  124. 170 return connection.handle_connect_error(error) if connection.connecting?
  125. connection.emit(:error, error)
  126. end
  127. 26 def close_resolver(resolver)
  128. 333 @current_session.__send__(:on_resolver_close, resolver, @current_selector)
  129. end
  130. end
  131. end

lib/httpx/resolver/system.rb

79.14% lines covered

139 relevant lines. 110 lines covered and 29 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "resolv"
  3. 26 module HTTPX
  4. # Implementation of a synchronous name resolver which relies on the system resolver,
  5. # which is lib'c getaddrinfo function (abstracted in ruby via Addrinfo.getaddrinfo).
  6. #
  7. # Its main advantage is relying on the reference implementation for name resolution
  8. # across most/all OSs which deploy ruby (it's what TCPSocket also uses), its main
  9. # disadvantage is the inability to set timeouts / check socket for readiness events,
  10. # hence why it relies on using the Timeout module, which poses a lot of problems for
  11. # the selector loop, specially when network is unstable.
  12. #
  13. 26 class Resolver::System < Resolver::Resolver
  14. 26 using URIExtensions
  15. 26 RESOLV_ERRORS = [Resolv::ResolvError,
  16. Resolv::DNS::Requester::RequestError,
  17. Resolv::DNS::EncodeError,
  18. Resolv::DNS::DecodeError].freeze
  19. 26 DONE = 1
  20. 26 ERROR = 2
  21. 26 class << self
  22. 26 def multi?
  23. 32 false
  24. end
  25. end
  26. 26 attr_reader :state
  27. 26 def initialize(options)
  28. 32 super(0, options)
  29. 32 @resolver_options = @options.resolver_options
  30. 32 resolv_options = @resolver_options.dup
  31. 32 timeouts = resolv_options.delete(:timeouts) || Resolver::RESOLVE_TIMEOUT
  32. 32 @_timeouts = Array(timeouts)
  33. 57 @timeouts = Hash.new { |tims, host| tims[host] = @_timeouts.dup }
  34. 32 resolv_options.delete(:cache)
  35. 32 @queries = []
  36. 32 @ips = []
  37. 32 @pipe_mutex = Thread::Mutex.new
  38. 32 @state = :idle
  39. end
  40. 26 def resolvers
  41. return enum_for(__method__) unless block_given?
  42. yield self
  43. end
  44. 26 def multi
  45. self
  46. end
  47. 26 def empty?
  48. true
  49. end
  50. 26 def close
  51. transition(:closed)
  52. end
  53. 26 def closed?
  54. @state == :closed
  55. end
  56. 26 def to_io
  57. @pipe_read.to_io
  58. end
  59. 26 def call
  60. case @state
  61. when :open
  62. consume
  63. end
  64. nil
  65. end
  66. 26 def interests
  67. return if @queries.empty?
  68. :r
  69. end
  70. 26 def timeout
  71. return unless @queries.empty?
  72. _, connection = @queries.first
  73. return unless connection
  74. @timeouts[connection.peer.host].first
  75. end
  76. 26 def <<(connection)
  77. 25 @connections << connection
  78. 25 resolve
  79. end
  80. 26 def early_resolve(connection, **)
  81. 25 self << connection
  82. 12 true
  83. end
  84. 26 def handle_socket_timeout(interval)
  85. error = HTTPX::ResolveTimeoutError.new(interval, "timed out while waiting on select")
  86. error.set_backtrace(caller)
  87. @queries.each do |host, connection|
  88. @connections.delete(connection)
  89. emit_resolve_error(connection, host, error)
  90. end
  91. while (connection = @connections.shift)
  92. emit_resolve_error(connection, connection.peer.host, error)
  93. end
  94. end
  95. 26 private
  96. 26 def transition(nextstate)
  97. 25 case nextstate
  98. when :idle
  99. @timeouts.clear
  100. when :open
  101. 25 return unless @state == :idle
  102. 25 @pipe_read, @pipe_write = IO.pipe
  103. when :closed
  104. return unless @state == :open
  105. @pipe_write.close
  106. @pipe_read.close
  107. end
  108. 25 @state = nextstate
  109. end
  110. 26 def consume
  111. 25 return if @connections.empty?
  112. 25 if @pipe_read.wait_readable
  113. 25 event = @pipe_read.getbyte
  114. 25 case event
  115. when DONE
  116. 24 *pair, addrs = @pipe_mutex.synchronize { @ips.pop }
  117. 12 if pair
  118. 12 @queries.delete(pair)
  119. 12 family, connection = pair
  120. 12 @connections.delete(connection)
  121. 24 catch(:coalesced) { emit_addresses(connection, family, addrs) }
  122. end
  123. when ERROR
  124. 26 *pair, error = @pipe_mutex.synchronize { @ips.pop }
  125. 13 if pair && error
  126. 13 @queries.delete(pair)
  127. 13 @connections.delete(connection)
  128. 13 _, connection = pair
  129. 13 emit_resolve_error(connection, connection.peer.host, error)
  130. end
  131. end
  132. end
  133. 12 return emit(:close, self) if @connections.empty?
  134. resolve
  135. end
  136. 26 def resolve(connection = nil, hostname = nil)
  137. 25 @connections.shift until @connections.empty? || @connections.first.state != :closed
  138. 25 connection ||= @connections.first
  139. 25 raise Error, "no URI to resolve" unless connection
  140. 25 return unless @queries.empty?
  141. 25 hostname ||= connection.peer.host
  142. 25 scheme = connection.origin.scheme
  143. log do
  144. "resolver: resolve IDN #{connection.peer.non_ascii_hostname} as #{hostname}"
  145. 25 end if connection.peer.non_ascii_hostname
  146. 25 transition(:open)
  147. 25 ip_families = connection.options.ip_families || Resolver.supported_ip_families
  148. 25 ip_families.each do |family|
  149. 25 @queries << [family, connection]
  150. end
  151. 25 async_resolve(connection, hostname, scheme)
  152. 25 consume
  153. end
  154. 26 def async_resolve(connection, hostname, scheme)
  155. 25 families = connection.options.ip_families || Resolver.supported_ip_families
  156. 25 log { "resolver: query for #{hostname}" }
  157. 25 timeouts = @timeouts[connection.peer.host]
  158. 25 resolve_timeout = timeouts.first
  159. 25 Thread.start do
  160. 25 Thread.current.report_on_exception = false
  161. begin
  162. 25 addrs = if resolve_timeout
  163. 25 Timeout.timeout(resolve_timeout) do
  164. 25 __addrinfo_resolve(hostname, scheme)
  165. end
  166. else
  167. __addrinfo_resolve(hostname, scheme)
  168. end
  169. 12 addrs = addrs.sort_by(&:afamily).group_by(&:afamily)
  170. 12 families.each do |family|
  171. 12 addresses = addrs[family]
  172. 12 next unless addresses
  173. 12 addresses.map!(&:ip_address)
  174. 12 addresses.uniq!
  175. 12 @pipe_mutex.synchronize do
  176. 12 @ips.unshift([family, connection, addresses])
  177. 12 @pipe_write.putc(DONE) unless @pipe_write.closed?
  178. end
  179. end
  180. rescue StandardError => e
  181. 13 if e.is_a?(Timeout::Error)
  182. 1 timeouts.shift
  183. 1 retry unless timeouts.empty?
  184. 1 e = ResolveTimeoutError.new(resolve_timeout, e.message)
  185. 1 e.set_backtrace(e.backtrace)
  186. end
  187. 13 @pipe_mutex.synchronize do
  188. 13 families.each do |family|
  189. 13 @ips.unshift([family, connection, e])
  190. 13 @pipe_write.putc(ERROR) unless @pipe_write.closed?
  191. end
  192. end
  193. end
  194. end
  195. end
  196. 26 def __addrinfo_resolve(host, scheme)
  197. 25 Addrinfo.getaddrinfo(host, scheme, Socket::AF_UNSPEC, Socket::SOCK_STREAM)
  198. end
  199. 26 def emit_connection_error(_, error)
  200. 13 throw(:resolve_error, error)
  201. end
  202. 26 def close_resolver(resolver); end
  203. end
  204. end

lib/httpx/response.rb

100.0% lines covered

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

lib/httpx/response/body.rb

100.0% lines covered

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

lib/httpx/response/buffer.rb

96.67% lines covered

60 relevant lines. 58 lines covered and 2 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "delegate"
  3. 26 require "stringio"
  4. 26 require "tempfile"
  5. 26 module HTTPX
  6. # wraps and delegates to an internal buffer, which can be a StringIO or a Tempfile.
  7. 26 class Response::Buffer < SimpleDelegator
  8. 26 attr_reader :buffer
  9. 26 protected :buffer
  10. # initializes buffer with the +threshold_size+ over which the payload gets buffer to a tempfile,
  11. # the initial +bytesize+, and the +encoding+.
  12. 26 def initialize(threshold_size:, bytesize: 0, encoding: Encoding::BINARY)
  13. 7024 @threshold_size = threshold_size
  14. 7024 @bytesize = bytesize
  15. 7024 @encoding = encoding
  16. 7024 @buffer = StringIO.new("".b)
  17. 7024 super(@buffer)
  18. end
  19. 26 def initialize_dup(other)
  20. 98 super
  21. # create new descriptor in READ-ONLY mode
  22. @buffer =
  23. 97 case other.buffer
  24. when StringIO
  25. 91 StringIO.new(other.buffer.string, mode: File::RDONLY)
  26. else
  27. 7 other.buffer.class.new(other.buffer.path, encoding: Encoding::BINARY, mode: File::RDONLY).tap do |temp|
  28. 7 FileUtils.copy_file(other.buffer.path, temp.path)
  29. end
  30. end
  31. end
  32. # size in bytes of the buffered content.
  33. 26 def size
  34. 300 @bytesize
  35. end
  36. # writes the +chunk+ into the buffer.
  37. 26 def write(chunk)
  38. 11457 @bytesize += chunk.bytesize
  39. 11457 try_upgrade_buffer
  40. 11457 @buffer.write(chunk)
  41. end
  42. # returns the buffered content as a string.
  43. 26 def to_s
  44. 3972 case @buffer
  45. when StringIO
  46. 507 begin
  47. 3909 @buffer.string.force_encoding(@encoding)
  48. rescue ArgumentError
  49. @buffer.string
  50. end
  51. when Tempfile
  52. 63 rewind
  53. 63 content = @buffer.read
  54. 8 begin
  55. 63 content.force_encoding(@encoding)
  56. rescue ArgumentError # ex: unknown encoding name - utf
  57. content
  58. end
  59. end
  60. end
  61. # closes the buffer.
  62. 26 def close
  63. 581 @buffer.close
  64. 581 @buffer.unlink if @buffer.respond_to?(:unlink)
  65. end
  66. 26 def ==(other)
  67. 133 super || begin
  68. 133 return false unless other.is_a?(Response::Buffer)
  69. 133 buffer_pos = @buffer.pos
  70. 133 other_pos = other.buffer.pos
  71. 133 @buffer.rewind
  72. 133 other.buffer.rewind
  73. 18 begin
  74. 133 FileUtils.compare_stream(@buffer, other.buffer)
  75. ensure
  76. 133 @buffer.pos = buffer_pos
  77. 133 other.buffer.pos = other_pos
  78. end
  79. end
  80. end
  81. 26 private
  82. # initializes the buffer into a StringIO, or turns it into a Tempfile when the threshold
  83. # has been reached.
  84. 26 def try_upgrade_buffer
  85. 11457 return unless @bytesize > @threshold_size
  86. 504 return if @buffer.is_a?(Tempfile)
  87. 138 aux = @buffer
  88. 138 @buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
  89. 138 if aux
  90. 138 aux.rewind
  91. 138 IO.copy_stream(aux, @buffer)
  92. 138 aux.close
  93. end
  94. 138 __setobj__(@buffer)
  95. end
  96. end
  97. end

lib/httpx/selector.rb

95.45% lines covered

132 relevant lines. 126 lines covered and 6 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "io/wait"
  3. 26 module HTTPX
  4. #
  5. # Implements the selector loop, where it registers and monitors "Selectable" objects.
  6. #
  7. # A Selectable object is an object which can calculate the **interests** (<tt>:r</tt>, <tt>:w</tt> or <tt>:rw</tt>,
  8. # respectively "read", "write" or "read-write") it wants to monitor for, and returns (via <tt>to_io</tt> method) an
  9. # IO object which can be passed to functions such as IO.select . More exhaustively, a Selectable **must** implement
  10. # the following methods:
  11. #
  12. # state :: returns the state as a Symbol, must return <tt>:closed</tt> when disposed of resources.
  13. # to_io :: returns the IO object.
  14. # call :: gets called when the IO is ready.
  15. # interests :: returns the current interests to monitor for, as described above.
  16. # timeout :: returns nil or an integer, representing how long to wait for interests.
  17. # handle_socket_timeout(Numeric) :: called when waiting for interest times out.
  18. #
  19. 26 class Selector
  20. 26 extend Forwardable
  21. 26 READABLE = %i[rw r].freeze
  22. 26 WRITABLE = %i[rw w].freeze
  23. 26 private_constant :READABLE
  24. 26 private_constant :WRITABLE
  25. 26 def_delegator :@timers, :after
  26. 26 def_delegator :@selectables, :empty?
  27. 26 def initialize
  28. 7008 @timers = Timers.new
  29. 7008 @selectables = []
  30. 7008 @is_timer_interval = false
  31. end
  32. 26 def each(&blk)
  33. @selectables.each(&blk)
  34. end
  35. 26 def next_tick
  36. 8583498 catch(:jump_tick) do
  37. 8583498 timeout = next_timeout
  38. 8583498 if timeout && timeout.negative?
  39. @timers.fire
  40. throw(:jump_tick)
  41. end
  42. 69504 begin
  43. 8583498 select(timeout) do |c|
  44. 24680 c.log(level: 2) { "[#{c.state}] selected#{" after #{timeout} secs" unless timeout.nil?}..." }
  45. 24533 c.call
  46. end
  47. 8583363 @timers.fire
  48. rescue TimeoutError => e
  49. @timers.fire(e)
  50. end
  51. end
  52. rescue StandardError => e
  53. 16 each_connection do |c|
  54. c.emit(:error, e)
  55. end
  56. rescue Exception # rubocop:disable Lint/RescueException
  57. 105 each_connection do |conn|
  58. 84 conn.force_reset
  59. 84 conn.disconnect
  60. end
  61. 105 raise
  62. end
  63. 26 def terminate
  64. # array may change during iteration
  65. 6800 selectables = @selectables.reject(&:inflight?)
  66. 6800 selectables.delete_if do |sel|
  67. 2662 sel.terminate
  68. 2655 sel.state == :closed
  69. end
  70. 6793 until selectables.empty?
  71. 7 next_tick
  72. 7 selectables &= @selectables
  73. end
  74. end
  75. 26 def find_resolver(options)
  76. 6515 res = @selectables.find do |c|
  77. 57 c.is_a?(Resolver::Resolver) && options == c.options
  78. end
  79. 6515 res.multi if res
  80. end
  81. 26 def each_connection(&block)
  82. 31571 return enum_for(__method__) unless block
  83. 15846 @selectables.each do |c|
  84. 2287 case c
  85. when Resolver::Resolver
  86. 222 c.each_connection(&block)
  87. when Connection
  88. 2051 yield c
  89. end
  90. end
  91. end
  92. 26 def find_connection(request_uri, options)
  93. 8496 each_connection.find do |connection|
  94. 1221 connection.match?(request_uri, options)
  95. end
  96. end
  97. 26 def find_mergeable_connection(connection)
  98. 6739 each_connection.find do |ch|
  99. 406 ch != connection && ch.mergeable?(connection)
  100. end
  101. end
  102. # deregisters +io+ from selectables.
  103. 26 def deregister(io)
  104. 7617 @selectables.delete(io)
  105. end
  106. # register +io+.
  107. 26 def register(io)
  108. 8096 return if @selectables.include?(io)
  109. 7654 @selectables << io
  110. end
  111. 26 private
  112. 26 def select(interval, &block)
  113. 8583498 has_no_selectables = @selectables.empty?
  114. # do not cause an infinite loop here.
  115. #
  116. # this may happen if timeout calculation actually triggered an error which causes
  117. # the connections to be reaped (such as the total timeout error) before #select
  118. # gets called.
  119. 8583498 return if interval.nil? && has_no_selectables
  120. # @type var r: (selectable | Array[selectable])?
  121. # @type var w: (selectable | Array[selectable])?
  122. 8583491 r, w = nil
  123. 8583491 @selectables.delete_if do |io|
  124. 8584546 interests = io.interests
  125. 8584546 is_closed = io.state == :closed
  126. 8584546 next(is_closed) if is_closed
  127. 8584615 io.log(level: 2) { "[#{io.state}] registering for select (#{interests})#{" for #{interval} seconds" unless interval.nil?}" }
  128. 8584468 if READABLE.include?(interests)
  129. 16435 r = r.nil? ? io : (Array(r) << io)
  130. end
  131. 8584468 if WRITABLE.include?(interests)
  132. 9322 w = w.nil? ? io : (Array(w) << io)
  133. end
  134. 8584468 is_closed
  135. end
  136. 8583491 case r
  137. when Array
  138. 252 w = Array(w) unless w.nil?
  139. 252 select_many(r, w, interval, &block)
  140. when nil
  141. 8567308 case w
  142. when Array
  143. 22 select_many(r, w, interval, &block)
  144. when nil
  145. 8558481 return unless interval && has_no_selectables
  146. # no selectables
  147. # TODO: replace with sleep?
  148. 96 select_many(r, w, interval, &block)
  149. else
  150. 8805 select_one(w, :w, interval, &block)
  151. end
  152. else
  153. 15931 case w
  154. when Array
  155. 8 select_many(Array(r), w, interval, &block)
  156. when nil
  157. 15515 select_one(r, :r, interval, &block)
  158. else
  159. 408 if r == w
  160. 353 select_one(r, :rw, interval, &block)
  161. else
  162. 55 select_many(Array(r), Array(w), interval, &block)
  163. end
  164. end
  165. end
  166. end
  167. 26 def select_many(r, w, interval, &block)
  168. 433 readers, writers = ::IO.select(r, w, nil, interval)
  169. 433 if readers.nil? && writers.nil? && interval
  170. 152 [*r, *w].each { |io| io.handle_socket_timeout(interval) }
  171. 112 return
  172. end
  173. 321 if writers
  174. readers.each do |io|
  175. 254 yield io
  176. # so that we don't yield 2 times
  177. 254 writers.delete(io)
  178. 320 end if readers
  179. 321 writers.each(&block)
  180. else
  181. readers.each(&block) if readers
  182. end
  183. end
  184. 26 def select_one(io, interests, interval)
  185. 2335 result =
  186. 22338 case interests
  187. 15515 when :r then io.to_io.wait_readable(interval)
  188. 8805 when :w then io.to_io.wait_writable(interval)
  189. 353 when :rw then rw_wait(io, interval)
  190. end
  191. 24673 unless result || interval.nil?
  192. 489 io.handle_socket_timeout(interval) unless @is_timer_interval
  193. 489 return
  194. end
  195. 24184 yield io
  196. end
  197. 26 def next_timeout
  198. 8583498 @is_timer_interval = false
  199. 8583498 timer_interval = @timers.wait_interval
  200. 8583498 connection_interval = @selectables.filter_map(&:timeout).min
  201. 8583498 return connection_interval unless timer_interval
  202. 8558810 if connection_interval.nil? || timer_interval <= connection_interval
  203. 8558749 @is_timer_interval = true
  204. 8558749 return timer_interval
  205. end
  206. 61 connection_interval
  207. end
  208. 26 if RUBY_ENGINE == "jruby"
  209. 1 def rw_wait(io, interval)
  210. 58 io.to_io.wait(interval, :read_write)
  211. end
  212. 25 elsif IO.const_defined?(:READABLE)
  213. 23 def rw_wait(io, interval)
  214. 251 io.to_io.wait(IO::READABLE | IO::WRITABLE, interval)
  215. end
  216. else
  217. 2 def rw_wait(io, interval)
  218. 44 if interval
  219. 42 io.to_io.wait(interval, :read_write)
  220. else
  221. 2 io.to_io.wait(:read_write)
  222. end
  223. end
  224. end
  225. end
  226. end

lib/httpx/session.rb

94.33% lines covered

300 relevant lines. 283 lines covered and 17 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 module HTTPX
  3. # Class implementing the APIs being used publicly.
  4. #
  5. # HTTPX.get(..) #=> delegating to an internal HTTPX::Session object.
  6. # HTTPX.plugin(..).get(..) #=> creating an intermediate HTTPX::Session with plugin, then sending the GET request
  7. 26 class Session
  8. 26 include Loggable
  9. 26 include Chainable
  10. # initializes the session with a set of +options+, which will be shared by all
  11. # requests sent from it.
  12. #
  13. # When pass a block, it'll yield itself to it, then closes after the block is evaluated.
  14. 26 def initialize(options = EMPTY_HASH, &blk)
  15. 10247 @options = self.class.default_options.merge(options)
  16. 10247 @persistent = @options.persistent
  17. 10247 @pool = @options.pool_class.new(@options.pool_options)
  18. 10247 @wrapped = false
  19. 10247 @closing = false
  20. 10247 INSTANCES[self] = self if @persistent && @options.close_on_fork && INSTANCES
  21. 10247 wrap(&blk) if blk
  22. end
  23. # Yields itself the block, then closes it after the block is evaluated.
  24. #
  25. # session.wrap do |http|
  26. # http.get("https://wikipedia.com")
  27. # end # wikipedia connection closes here
  28. 26 def wrap
  29. 516 prev_wrapped = @wrapped
  30. 516 @wrapped = true
  31. 516 was_initialized = false
  32. 516 current_selector = get_current_selector do
  33. 516 selector = Selector.new
  34. 516 set_current_selector(selector)
  35. 516 was_initialized = true
  36. 516 selector
  37. end
  38. 57 begin
  39. 516 yield self
  40. ensure
  41. 516 unless prev_wrapped
  42. 516 if @persistent
  43. 1 deactivate(current_selector)
  44. else
  45. 515 close(current_selector)
  46. end
  47. end
  48. 516 @wrapped = prev_wrapped
  49. 516 set_current_selector(nil) if was_initialized
  50. end
  51. end
  52. # closes all the active connections from the session.
  53. #
  54. # when called directly without specifying +selector+, all available connections
  55. # will be picked up from the connection pool and closed. Connections in use
  56. # by other sessions, or same session in a different thread, will not be reaped.
  57. 26 def close(selector = Selector.new)
  58. # throw resolvers away from the pool
  59. 6542 @pool.reset_resolvers
  60. # preparing to throw away connections
  61. 15728 while (connection = @pool.pop_connection)
  62. 4000 next if connection.state == :closed
  63. 192 select_connection(connection, selector)
  64. end
  65. 6542 selector_close(selector)
  66. end
  67. # performs one, or multple requests; it accepts:
  68. #
  69. # 1. one or multiple HTTPX::Request objects;
  70. # 2. an HTTP verb, then a sequence of URIs or URI/options tuples;
  71. # 3. one or multiple HTTP verb / uri / (optional) options tuples;
  72. #
  73. # when present, the set of +options+ kwargs is applied to all of the
  74. # sent requests.
  75. #
  76. # respectively returns a single HTTPX::Response response, or all of them in an Array, in the same order.
  77. #
  78. # resp1 = session.request(req1)
  79. # resp1, resp2 = session.request(req1, req2)
  80. # resp1 = session.request("GET", "https://server.org/a")
  81. # resp1, resp2 = session.request("GET", ["https://server.org/a", "https://server.org/b"])
  82. # resp1, resp2 = session.request(["GET", "https://server.org/a"], ["GET", "https://server.org/b"])
  83. # resp1 = session.request("POST", "https://server.org/a", form: { "foo" => "bar" })
  84. # resp1, resp2 = session.request(["POST", "https://server.org/a", form: { "foo" => "bar" }], ["GET", "https://server.org/b"])
  85. # resp1, resp2 = session.request("GET", ["https://server.org/a", "https://server.org/b"], headers: { "x-api-token" => "TOKEN" })
  86. #
  87. 26 def request(*args, **params)
  88. 6848 raise ArgumentError, "must perform at least one request" if args.empty?
  89. 6848 requests = args.first.is_a?(Request) ? args : build_requests(*args, params)
  90. 6811 responses = send_requests(*requests)
  91. 6679 return responses.first if responses.size == 1
  92. 177 responses
  93. end
  94. # returns a HTTP::Request instance built from the HTTP +verb+, the request +uri+, and
  95. # the optional set of request-specific +options+. This request **must** be sent through
  96. # the same session it was built from.
  97. #
  98. # req = session.build_request("GET", "https://server.com")
  99. # resp = session.request(req)
  100. 26 def build_request(verb, uri, params = EMPTY_HASH, options = @options)
  101. 8406 rklass = options.request_class
  102. 8406 request = rklass.new(verb, uri, options, params)
  103. 8369 request.persistent = @persistent
  104. 8369 set_request_callbacks(request)
  105. 8369 request
  106. end
  107. 26 def select_connection(connection, selector)
  108. 8068 pin_connection(connection, selector)
  109. 8068 selector.register(connection)
  110. end
  111. 26 def pin_connection(connection, selector)
  112. 8093 connection.current_session = self
  113. 8093 connection.current_selector = selector
  114. end
  115. 26 alias_method :select_resolver, :select_connection
  116. 26 def deselect_connection(connection, selector, cloned = false)
  117. 7270 connection.log(level: 2) do
  118. 68 "deregistering connection##{connection.object_id}(#{connection.state}) from selector##{selector.object_id}"
  119. end
  120. 7270 selector.deregister(connection)
  121. # when connections coalesce
  122. 7270 return if connection.state == :idle
  123. 7246 return if cloned
  124. 7234 return if @closing && connection.state == :closed
  125. 7295 connection.log(level: 2) { "check-in connection##{connection.object_id}(#{connection.state}) in pool##{@pool.object_id}" }
  126. 7227 @pool.checkin_connection(connection)
  127. end
  128. 26 def deselect_resolver(resolver, selector)
  129. 333 resolver.log(level: 2) do
  130. "deregistering resolver##{resolver.object_id}(#{resolver.state}) from selector##{selector.object_id}"
  131. end
  132. 333 selector.deregister(resolver)
  133. 333 return if @closing && resolver.closed?
  134. 333 resolver.log(level: 2) { "check-in resolver##{resolver.object_id}(#{resolver.state}) in pool##{@pool.object_id}" }
  135. 333 @pool.checkin_resolver(resolver)
  136. end
  137. 26 def try_clone_connection(connection, selector, family)
  138. 437 connection.family ||= family
  139. 437 return connection if connection.family == family
  140. 8 new_connection = connection.class.new(connection.origin, connection.options)
  141. 8 new_connection.family = family
  142. 8 connection.sibling = new_connection
  143. 8 do_init_connection(new_connection, selector)
  144. 8 new_connection
  145. end
  146. # returns the HTTPX::Connection through which the +request+ should be sent through.
  147. 26 def find_connection(request_uri, selector, options)
  148. 8496 if (connection = selector.find_connection(request_uri, options))
  149. 1143 connection.idling if connection.state == :closed
  150. 1143 connection.log(level: 2) { "found connection##{connection.object_id}(#{connection.state}) in selector##{selector.object_id}" }
  151. 1143 return connection
  152. end
  153. 7353 connection = @pool.checkout_connection(request_uri, options)
  154. 7393 connection.log(level: 2) { "found connection##{connection.object_id}(#{connection.state}) in pool##{@pool.object_id}" }
  155. 7325 case connection.state
  156. when :idle
  157. 6673 do_init_connection(connection, selector)
  158. when :open
  159. 59 if options.io
  160. 59 select_connection(connection, selector)
  161. else
  162. pin_connection(connection, selector)
  163. end
  164. when :closing, :closed
  165. 568 connection.idling
  166. 568 if connection.addresses?
  167. 562 select_connection(connection, selector)
  168. else
  169. # if addresses expired, resolve again
  170. 6 resolve_connection(connection, selector)
  171. end
  172. else
  173. 25 pin_connection(connection, selector)
  174. end
  175. 7266 connection
  176. end
  177. 26 private
  178. 26 def selector_close(selector)
  179. begin
  180. 6800 @closing = true
  181. 6800 selector.terminate
  182. ensure
  183. 6800 @closing = false
  184. end
  185. end
  186. # tries deactivating connections in the +selector+, deregistering the ones that have been deactivated.
  187. 26 def deactivate(selector)
  188. 490 selector.each_connection.select do |c|
  189. 401 c.deactivate
  190. 401 c.state == :inactive
  191. end.each do |c| # rubocop:disable Style/MultilineBlockChain
  192. 357 deselect_connection(c, selector)
  193. end
  194. end
  195. # callback executed when an HTTP/2 promise frame has been received.
  196. 26 def on_promise(_, stream)
  197. 7 log(level: 2) { "#{stream.id}: refusing stream!" }
  198. 7 stream.refuse
  199. end
  200. # returns the corresponding HTTP::Response to the given +request+ if it has been received.
  201. 26 def fetch_response(request, _selector, _options)
  202. 8591059 response = request.response
  203. 8591059 return unless response && response.finished?
  204. 8342 log(level: 2) { "response fetched" }
  205. 8342 response
  206. end
  207. # sends the +request+ to the corresponding HTTPX::Connection
  208. 26 def send_request(request, selector, options = request.options)
  209. 969 error = begin
  210. 8409 catch(:resolve_error) do
  211. 8409 connection = find_connection(request.uri, selector, options)
  212. 8301 connection.send(request)
  213. end
  214. rescue StandardError => e
  215. 35 e
  216. end
  217. 8403 return unless error && error.is_a?(Exception)
  218. 108 raise error unless error.is_a?(Error)
  219. 108 response = ErrorResponse.new(request, error)
  220. 108 request.response = response
  221. 108 request.emit(:response, response)
  222. end
  223. # returns a set of HTTPX::Request objects built from the given +args+ and +options+.
  224. 26 def build_requests(*args, params)
  225. 6274 requests = if args.size == 1
  226. 69 reqs = args.first
  227. 69 reqs.map do |verb, uri, ps = EMPTY_HASH|
  228. 138 request_params = params
  229. 138 request_params = request_params.merge(ps) unless ps.empty?
  230. 138 build_request(verb, uri, request_params)
  231. end
  232. else
  233. 6205 verb, uris = args
  234. 6205 if uris.respond_to?(:each)
  235. 5995 uris.enum_for(:each).map do |uri, ps = EMPTY_HASH|
  236. 6735 request_params = params
  237. 6735 request_params = request_params.merge(ps) unless ps.empty?
  238. 6735 build_request(verb, uri, request_params)
  239. end
  240. else
  241. 210 [build_request(verb, uris, params)]
  242. end
  243. end
  244. 6237 raise ArgumentError, "wrong number of URIs (given 0, expect 1..+1)" if requests.empty?
  245. 6237 requests
  246. end
  247. 26 def set_request_callbacks(request)
  248. 8259 request.on(:promise, &method(:on_promise))
  249. end
  250. 26 def do_init_connection(connection, selector)
  251. 6681 resolve_connection(connection, selector) unless connection.family
  252. end
  253. # sends an array of HTTPX::Request +requests+, returns the respective array of HTTPX::Response objects.
  254. 26 def send_requests(*requests)
  255. 13128 selector = get_current_selector { Selector.new }
  256. 851 begin
  257. 6897 _send_requests(requests, selector)
  258. 6891 receive_requests(requests, selector)
  259. ensure
  260. 6883 unless @wrapped
  261. 6255 if @persistent
  262. 489 deactivate(selector)
  263. else
  264. 5766 close(selector)
  265. end
  266. end
  267. end
  268. end
  269. # sends an array of HTTPX::Request objects
  270. 26 def _send_requests(requests, selector)
  271. 6897 requests.each do |request|
  272. 7693 send_request(request, selector)
  273. end
  274. end
  275. # returns the array of HTTPX::Response objects corresponding to the array of HTTPX::Request +requests+.
  276. 26 def receive_requests(requests, selector)
  277. 6891 responses = [] # : Array[response]
  278. # guarantee ordered responses
  279. 6891 loop do
  280. 7694 request = requests.first
  281. 7694 return responses unless request
  282. 8590150 catch(:coalesced) { selector.next_tick } until (response = fetch_response(request, selector, request.options))
  283. 7568 request.complete!(response)
  284. 7568 responses << response
  285. 7568 requests.shift
  286. 7568 break if requests.empty?
  287. 803 next unless selector.empty?
  288. # in some cases, the pool of connections might have been drained because there was some
  289. # handshake error, and the error responses have already been emitted, but there was no
  290. # opportunity to traverse the requests, hence we're returning only a fraction of the errors
  291. # we were supposed to. This effectively fetches the existing responses and return them.
  292. exit_from_loop = true
  293. requests_to_remove = [] # : Array[Request]
  294. requests.each do |req|
  295. response = fetch_response(req, selector, request.options)
  296. if exit_from_loop && response
  297. req.complete!(response)
  298. responses << response
  299. requests_to_remove << req
  300. else
  301. # fetch_response may resend requests. when that happens, we need to go back to the initial
  302. # loop and process the selector. we still do a pass-through on the remainder of requests, so
  303. # that every request that need to be resent, is resent.
  304. exit_from_loop = false
  305. raise Error, "something went wrong, responses not found and requests not resent" if selector.empty?
  306. end
  307. end
  308. break if exit_from_loop
  309. requests -= requests_to_remove
  310. end
  311. 6765 responses
  312. end
  313. 26 def resolve_connection(connection, selector)
  314. 6703 if connection.addresses? || connection.open?
  315. #
  316. # there are two cases in which we want to activate initialization of
  317. # connection immediately:
  318. #
  319. # 1. when the connection already has addresses, i.e. it doesn't need to
  320. # resolve a name (not the same as name being an IP, yet)
  321. # 2. when the connection is initialized with an external already open IO.
  322. #
  323. 188 on_resolver_connection(connection, selector)
  324. 188 return
  325. end
  326. 6515 resolver = find_resolver_for(connection, selector)
  327. 6515 resolver.early_resolve(connection) || resolver.lazy_resolve(connection)
  328. end
  329. 26 def on_resolver_connection(connection, selector)
  330. 6739 from_pool = false
  331. 6739 found_connection = selector.find_mergeable_connection(connection) || begin
  332. 6706 from_pool = true
  333. 6706 @pool.checkout_mergeable_connection(connection)
  334. end
  335. 6739 return select_connection(connection, selector) unless found_connection
  336. 33 connection.log(level: 2) do
  337. "try coalescing from #{from_pool ? "pool##{@pool.object_id}" : "selector##{selector.object_id}"} " \
  338. "(conn##{found_connection.object_id}[#{found_connection.origin}])"
  339. end
  340. 33 coalesce_connections(found_connection, connection, selector, from_pool)
  341. end
  342. 26 def on_resolver_close(resolver, selector)
  343. 333 return if resolver.closed?
  344. 333 deselect_resolver(resolver, selector)
  345. 333 resolver.close unless resolver.closed?
  346. end
  347. 26 def find_resolver_for(connection, selector)
  348. 6515 if (resolver = selector.find_resolver(connection.options))
  349. 5 resolver.log(level: 2) { "found resolver##{connection.object_id}(#{connection.state}) in selector##{selector.object_id}" }
  350. 5 return resolver
  351. end
  352. 6510 resolver = @pool.checkout_resolver(connection.options)
  353. 6578 resolver.log(level: 2) { "found resolver##{connection.object_id}(#{connection.state}) in pool##{@pool.object_id}" }
  354. 6510 resolver.current_session = self
  355. 6510 resolver.current_selector = selector
  356. 6510 resolver
  357. end
  358. # coalesces +conn2+ into +conn1+. if +conn1+ was loaded from the connection pool
  359. # (it is known via +from_pool+), then it adds its to the +selector+.
  360. 26 def coalesce_connections(conn1, conn2, selector, from_pool)
  361. 33 unless conn1.coalescable?(conn2)
  362. 20 conn2.log(level: 2) { "not coalescing with conn##{conn1.object_id}[#{conn1.origin}])" }
  363. 20 select_connection(conn2, selector)
  364. 20 if from_pool
  365. conn1.log(level: 2) { "check-in connection##{conn1.object_id}(#{conn1.state}) in pool##{@pool.object_id}" }
  366. @pool.checkin_connection(conn1)
  367. end
  368. 20 return false
  369. end
  370. 13 conn2.log(level: 2) { "coalescing with conn##{conn1.object_id}[#{conn1.origin}])" }
  371. 13 conn2.coalesce!(conn1)
  372. 13 select_connection(conn1, selector) if from_pool
  373. 13 conn2.disconnect
  374. 13 true
  375. end
  376. 26 def get_current_selector
  377. 7413 selector_store[self] || (yield if block_given?)
  378. end
  379. 26 def set_current_selector(selector)
  380. 1482 if selector
  381. 966 selector_store[self] = selector
  382. else
  383. 516 selector_store.delete(self)
  384. end
  385. end
  386. 26 def selector_store
  387. 8895 th_current = Thread.current
  388. 8895 thread_selector_store(th_current) || begin
  389. 149 {}.compare_by_identity.tap do |store|
  390. 149 th_current.thread_variable_set(:httpx_persistent_selector_store, store)
  391. end
  392. end
  393. end
  394. 26 def thread_selector_store(th)
  395. 12719 th.thread_variable_get(:httpx_persistent_selector_store)
  396. end
  397. 26 @default_options = Options.new
  398. 26 @default_options.freeze
  399. 26 @plugins = []
  400. 26 class << self
  401. 26 attr_reader :default_options
  402. 26 def inherited(klass)
  403. 5170 super
  404. 5170 klass.instance_variable_set(:@default_options, @default_options)
  405. 5170 klass.instance_variable_set(:@plugins, @plugins.dup)
  406. 5170 klass.instance_variable_set(:@callbacks, @callbacks.dup)
  407. end
  408. # returns a new HTTPX::Session instance, with the plugin pointed by +pl+ loaded.
  409. #
  410. # session_with_retries = session.plugin(:retries)
  411. # session_with_custom = session.plugin(CustomPlugin)
  412. #
  413. 26 def plugin(pl, options = nil, &block)
  414. 7502 label = pl
  415. # raise Error, "Cannot add a plugin to a frozen config" if frozen?
  416. 7502 pl = Plugins.load_plugin(pl) if pl.is_a?(Symbol)
  417. 7502 raise ArgumentError, "Invalid plugin type: #{pl.class.inspect}" unless pl.is_a?(Module)
  418. 7496 if !@plugins.include?(pl)
  419. 7263 @plugins << pl
  420. 7263 pl.load_dependencies(self, &block) if pl.respond_to?(:load_dependencies)
  421. 7263 @default_options = @default_options.dup
  422. 7263 include(pl::InstanceMethods) if defined?(pl::InstanceMethods)
  423. 7263 extend(pl::ClassMethods) if defined?(pl::ClassMethods)
  424. 7263 opts = @default_options
  425. 7263 opts.extend_with_plugin_classes(pl)
  426. 7263 if defined?(pl::OptionsMethods)
  427. # when a class gets dup'ed, the #initialize_dup callbacks isn't triggered.
  428. # moreover, and because #method_added does not get triggered on mixin include,
  429. # the callback is also forcefully manually called here.
  430. 2733 opts.options_class.instance_variable_set(:@options_names, opts.options_class.options_names.dup)
  431. 2733 (pl::OptionsMethods.instance_methods + pl::OptionsMethods.private_instance_methods - Object.instance_methods).each do |meth|
  432. 8256 opts.options_class.method_added(meth)
  433. end
  434. 2733 @default_options = opts.options_class.new(opts)
  435. end
  436. 7263 @default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
  437. 7263 @default_options = @default_options.merge(options) if options
  438. 7263 if pl.respond_to?(:subplugins)
  439. 800 pl.subplugins.transform_keys(&Plugins.method(:load_plugin)).each do |main_pl, sub_pl|
  440. # in case the main plugin has already been loaded, then apply subplugin functionality
  441. # immediately
  442. 800 next unless @plugins.include?(main_pl)
  443. 20 plugin(sub_pl, options, &block)
  444. end
  445. end
  446. 7263 pl.configure(self, &block) if pl.respond_to?(:configure)
  447. 7263 if label.is_a?(Symbol)
  448. # in case an already-loaded plugin complements functionality of
  449. # the plugin currently being loaded, loaded it now
  450. 5599 @plugins.each do |registered_pl|
  451. 15092 next if registered_pl == pl
  452. 9493 next unless registered_pl.respond_to?(:subplugins)
  453. 2198 sub_pl = registered_pl.subplugins[label]
  454. 2198 next unless sub_pl
  455. 29 plugin(sub_pl, options, &block)
  456. end
  457. end
  458. 7263 @default_options.freeze
  459. 7263 set_temporary_name("#{superclass}/#{pl}") if respond_to?(:set_temporary_name) # ruby 3.4 only
  460. 232 elsif options
  461. # this can happen when two plugins are loaded, an one of them calls the other under the hood,
  462. # albeit changing some default.
  463. 20 @default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
  464. 20 @default_options = @default_options.merge(options) if options
  465. 14 @default_options.freeze
  466. end
  467. 7490 self
  468. end
  469. end
  470. # setup of the support for close_on_fork sessions.
  471. # adapted from https://github.com/mperham/connection_pool/blob/main/lib/connection_pool.rb#L48
  472. 26 if Process.respond_to?(:fork)
  473. 25 INSTANCES = ObjectSpace::WeakMap.new
  474. 25 private_constant :INSTANCES
  475. 25 def self.after_fork
  476. 1 INSTANCES.each_value(&:close)
  477. 1 nil
  478. end
  479. 25 if ::Process.respond_to?(:_fork)
  480. 21 module ForkTracker
  481. 21 def _fork
  482. 1 pid = super
  483. 1 Session.after_fork if pid.zero?
  484. 1 pid
  485. end
  486. end
  487. 21 Process.singleton_class.prepend(ForkTracker)
  488. end
  489. else
  490. 1 INSTANCES = nil
  491. 1 private_constant :INSTANCES
  492. 1 def self.after_fork
  493. # noop
  494. end
  495. end
  496. end
  497. # session may be overridden by certain adapters.
  498. 26 S = Session
  499. end

lib/httpx/session_extensions.rb

100.0% lines covered

15 relevant lines. 15 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 module HTTPX
  3. 26 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 new_options_class = proxy_session.class.default_options.options_class.dup
  13. 1 const_set(:Options, new_options_class)
  14. 1 options[:options_class] = Class.new(new_options_class).freeze
  15. 1 options.freeze
  16. 1 Options.send(:const_set, :DEFAULT_OPTIONS, options)
  17. 1 Session.instance_variable_set(:@default_options, Options.new(options))
  18. 1 $VERBOSE = original_verbosity
  19. end
  20. skipped # :nocov:
  21. skipped if Session.default_options.debug_level > 2
  22. skipped proxy_session = plugin(:internal_telemetry)
  23. skipped remove_const(:Session)
  24. skipped const_set(:Session, proxy_session.class)
  25. skipped end
  26. skipped # :nocov:
  27. end

lib/httpx/timers.rb

93.94% lines covered

66 relevant lines. 62 lines covered and 4 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 module HTTPX
  3. 26 class Timers
  4. 26 def initialize
  5. 7008 @intervals = []
  6. end
  7. 26 def after(interval_in_secs, cb = nil, &blk)
  8. 37848 callback = cb || blk
  9. 37848 raise Error, "timer must have a callback" unless callback
  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. 68579 unless (interval = @intervals.bsearch { |t| t.interval == interval_in_secs })
  15. 8613 interval = Interval.new(interval_in_secs)
  16. 8613 @intervals << interval
  17. 8613 @intervals.sort!
  18. end
  19. 37848 interval << callback
  20. 37848 @next_interval_at = nil
  21. 37848 Timer.new(interval, callback)
  22. end
  23. 26 def wait_interval
  24. 8583498 drop_elapsed!
  25. 8583498 return if @intervals.empty?
  26. 8558810 @next_interval_at = Utils.now
  27. 8558810 @intervals.first.interval
  28. end
  29. 26 def fire(error = nil)
  30. 8583363 raise error if error && error.timeout != @intervals.first
  31. 8583363 return if @intervals.empty? || !@next_interval_at
  32. 8558169 elapsed_time = Utils.elapsed_time(@next_interval_at)
  33. 8558169 drop_elapsed!(elapsed_time)
  34. 17109398 @intervals = @intervals.drop_while { |interval| interval.elapse(elapsed_time) <= 0 }
  35. 8558169 @next_interval_at = nil if @intervals.empty?
  36. end
  37. 26 private
  38. 26 def drop_elapsed!(elapsed_time = 0)
  39. # check first, if not elapsed, then return
  40. 17141667 first_interval = @intervals.first
  41. 17141667 return unless first_interval && first_interval.elapsed?(elapsed_time)
  42. # TODO: would be nice to have a drop_while!
  43. 15377 @intervals = @intervals.drop_while { |interval| interval.elapse(elapsed_time) <= 0 }
  44. end
  45. 26 class Timer
  46. 26 def initialize(interval, callback)
  47. 37848 @interval = interval
  48. 37848 @callback = callback
  49. end
  50. 26 def cancel
  51. 55596 @interval.delete(@callback)
  52. end
  53. end
  54. 26 class Interval
  55. 26 include Comparable
  56. 26 attr_reader :interval
  57. 26 def initialize(interval)
  58. 8613 @interval = interval
  59. 8613 @callbacks = []
  60. end
  61. 26 def <=>(other)
  62. 736 @interval <=> other.interval
  63. end
  64. 26 def ==(other)
  65. return @interval == other if other.is_a?(Numeric)
  66. @interval == other.to_f # rubocop:disable Lint/FloatComparison
  67. end
  68. 26 def to_f
  69. Float(@interval)
  70. end
  71. 26 def <<(callback)
  72. 37848 @callbacks << callback
  73. end
  74. 26 def delete(callback)
  75. 55596 @callbacks.delete(callback)
  76. end
  77. 26 def no_callbacks?
  78. @callbacks.empty?
  79. end
  80. 26 def elapsed?(elapsed = 0)
  81. 17117352 (@interval - elapsed) <= 0 || @callbacks.empty?
  82. end
  83. 26 def elapse(elapsed)
  84. # same as elapsing
  85. 8559168 return 0 if @callbacks.empty?
  86. 8551918 @interval -= elapsed
  87. 8551918 if @interval <= 0
  88. 570 cb = @callbacks.dup
  89. 570 cb.each(&:call)
  90. end
  91. 8551918 @interval
  92. end
  93. end
  94. 26 private_constant :Interval
  95. end
  96. end

lib/httpx/transcoder.rb

100.0% lines covered

52 relevant lines. 52 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 module HTTPX
  3. 26 module Transcoder
  4. 26 module_function
  5. 26 def normalize_keys(key, value, cond = nil, &block)
  6. 3196 if cond && cond.call(value)
  7. 993 block.call(key.to_s, value)
  8. 2202 elsif value.respond_to?(:to_ary)
  9. 398 if value.empty?
  10. 112 block.call("#{key}[]")
  11. else
  12. 286 value.to_ary.each do |element|
  13. 460 normalize_keys("#{key}[]", element, cond, &block)
  14. end
  15. end
  16. 1804 elsif value.respond_to?(:to_hash)
  17. 504 value.to_hash.each do |child_key, child_value|
  18. 504 normalize_keys("#{key}[#{child_key}]", child_value, cond, &block)
  19. end
  20. else
  21. 1301 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. 26 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. 7 return
  33. end
  34. 147 case after
  35. when ""
  36. 49 params[k] = v
  37. when "["
  38. 7 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. 49 params[k] = normalize_query(params[k], after, v, depth - 1)
  56. end
  57. 147 params
  58. end
  59. 26 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. 26 require "httpx/transcoder/body"
  71. 26 require "httpx/transcoder/form"
  72. 26 require "httpx/transcoder/json"
  73. 26 require "httpx/transcoder/chunker"
  74. 26 require "httpx/transcoder/deflate"
  75. 26 require "httpx/transcoder/gzip"

lib/httpx/transcoder/body.rb

100.0% lines covered

26 relevant lines. 26 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "delegate"
  3. 26 module HTTPX::Transcoder
  4. 26 module Body
  5. 26 class Error < HTTPX::Error; end
  6. 26 module_function
  7. 26 class Encoder < SimpleDelegator
  8. 26 def initialize(body)
  9. 1295 body = body.open(File::RDONLY, encoding: Encoding::BINARY) if Object.const_defined?(:Pathname) && body.is_a?(Pathname)
  10. 1295 @body = body
  11. 1295 super(body)
  12. end
  13. 26 def bytesize
  14. 5059 if @body.respond_to?(:bytesize)
  15. 2261 @body.bytesize
  16. 2797 elsif @body.respond_to?(:to_ary)
  17. 907 @body.sum(&:bytesize)
  18. 1890 elsif @body.respond_to?(:size)
  19. 1317 @body.size || Float::INFINITY
  20. 573 elsif @body.respond_to?(:length)
  21. 315 @body.length || Float::INFINITY
  22. 258 elsif @body.respond_to?(:each)
  23. 252 Float::INFINITY
  24. else
  25. 7 raise Error, "cannot determine size of body: #{@body.inspect}"
  26. end
  27. end
  28. 26 def content_type
  29. 1226 "application/octet-stream"
  30. end
  31. end
  32. 26 def encode(body)
  33. 1295 Encoder.new(body)
  34. end
  35. end
  36. 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. 26 require "forwardable"
  3. 26 module HTTPX::Transcoder
  4. 26 module Chunker
  5. 26 class Error < HTTPX::Error; end
  6. 26 CRLF = "\r\n".b
  7. 26 class Encoder
  8. 26 extend Forwardable
  9. 26 def initialize(body)
  10. 84 @raw = body
  11. end
  12. 26 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. 26 def respond_to_missing?(meth, *args)
  20. 96 @raw.respond_to?(meth, *args) || super
  21. end
  22. end
  23. 26 class Decoder
  24. 26 extend Forwardable
  25. 26 def_delegator :@buffer, :empty?
  26. 26 def_delegator :@buffer, :<<
  27. 26 def_delegator :@buffer, :clear
  28. 26 def initialize(buffer, trailers = false)
  29. 101 @buffer = buffer
  30. 101 @chunk_buffer = "".b
  31. 101 @finished = false
  32. 101 @state = :length
  33. 101 @trailers = trailers
  34. end
  35. 26 def to_s
  36. 94 @buffer
  37. end
  38. 26 def each
  39. 136 loop do
  40. 1005 case @state
  41. when :length
  42. 293 index = @buffer.index(CRLF)
  43. 293 return unless index && index.positive?
  44. # Read hex-length
  45. 293 hexlen = @buffer.byteslice(0, index)
  46. 293 @buffer = @buffer.byteslice(index..-1) || "".b
  47. 293 hexlen[/\h/] || raise(Error, "wrong chunk size line: #{hexlen}")
  48. 293 @chunk_length = hexlen.hex
  49. # check if is last chunk
  50. 293 @finished = @chunk_length.zero?
  51. 293 nextstate(:crlf)
  52. when :crlf
  53. 485 crlf_size = @finished && !@trailers ? 4 : 2
  54. # consume CRLF
  55. 485 return if @buffer.bytesize < crlf_size
  56. 485 raise Error, "wrong chunked encoding format" unless @buffer.start_with?(CRLF * (crlf_size / 2))
  57. 485 @buffer = @buffer.byteslice(crlf_size..-1)
  58. 485 if @chunk_length.nil?
  59. 192 nextstate(:length)
  60. else
  61. 293 return if @finished
  62. 199 nextstate(:data)
  63. end
  64. when :data
  65. 227 chunk = @buffer.byteslice(0, @chunk_length)
  66. 227 @buffer = @buffer.byteslice(@chunk_length..-1) || "".b
  67. 227 @chunk_buffer << chunk
  68. 227 @chunk_length -= chunk.bytesize
  69. 227 if @chunk_length.zero?
  70. 199 yield @chunk_buffer unless @chunk_buffer.empty?
  71. 192 @chunk_buffer.clear
  72. 192 @chunk_length = nil
  73. 192 nextstate(:crlf)
  74. end
  75. end
  76. 904 break if @buffer.empty?
  77. end
  78. end
  79. 26 def finished?
  80. 129 @finished
  81. end
  82. 26 private
  83. 26 def nextstate(state)
  84. 876 @state = state
  85. end
  86. end
  87. 26 module_function
  88. 26 def encode(chunks)
  89. 84 Encoder.new(chunks)
  90. end
  91. end
  92. end

lib/httpx/transcoder/deflate.rb

100.0% lines covered

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

lib/httpx/transcoder/form.rb

100.0% lines covered

35 relevant lines. 35 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "forwardable"
  3. 26 require "uri"
  4. 26 require_relative "multipart"
  5. 26 module HTTPX
  6. 26 module Transcoder
  7. 26 module Form
  8. 26 module_function
  9. 26 PARAM_DEPTH_LIMIT = 32
  10. 26 class Encoder
  11. 26 extend Forwardable
  12. 26 def_delegator :@raw, :to_s
  13. 26 def_delegator :@raw, :to_str
  14. 26 def_delegator :@raw, :bytesize
  15. 26 def_delegator :@raw, :==
  16. 26 def initialize(form)
  17. 665 @raw = form.each_with_object("".b) do |(key, val), buf|
  18. 1127 HTTPX::Transcoder.normalize_keys(key, val) do |k, v|
  19. 1301 buf << "&" unless buf.empty?
  20. 1301 buf << URI.encode_www_form_component(k)
  21. 1301 buf << "=#{URI.encode_www_form_component(v.to_s)}" unless v.nil?
  22. end
  23. end
  24. end
  25. 26 def content_type
  26. 515 "application/x-www-form-urlencoded"
  27. end
  28. end
  29. 26 module Decoder
  30. 26 module_function
  31. 26 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. 26 def encode(form)
  38. 665 Encoder.new(form)
  39. end
  40. 26 def decode(response)
  41. 56 content_type = response.content_type.mime_type
  42. 56 case content_type
  43. when "application/x-www-form-urlencoded"
  44. 35 Decoder
  45. when "multipart/form-data"
  46. 14 Multipart::Decoder.new(response)
  47. else
  48. 7 raise Error, "invalid form mime type (#{content_type})"
  49. end
  50. end
  51. end
  52. end
  53. end

lib/httpx/transcoder/gzip.rb

100.0% lines covered

40 relevant lines. 40 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "zlib"
  3. 26 module HTTPX
  4. 26 module Transcoder
  5. 26 module GZIP
  6. 26 class Deflater < Transcoder::Deflater
  7. 26 def initialize(body)
  8. 45 @compressed_chunk = "".b
  9. 45 super
  10. end
  11. 26 def deflate(chunk)
  12. 90 @deflater ||= Zlib::GzipWriter.new(self)
  13. 90 if chunk.nil?
  14. 45 unless @deflater.closed?
  15. 45 @deflater.flush
  16. 45 @deflater.close
  17. 45 compressed_chunk
  18. end
  19. else
  20. 45 @deflater.write(chunk)
  21. 45 compressed_chunk
  22. end
  23. end
  24. 26 private
  25. 26 def write(chunk)
  26. 135 @compressed_chunk << chunk
  27. end
  28. 26 def compressed_chunk
  29. 90 @compressed_chunk.dup
  30. ensure
  31. 90 @compressed_chunk.clear
  32. end
  33. end
  34. 26 class Inflater
  35. 26 def initialize(bytesize)
  36. 137 @inflater = Zlib::Inflate.new(Zlib::MAX_WBITS + 32)
  37. 137 @bytesize = bytesize
  38. end
  39. 26 def call(chunk)
  40. 564 buffer = @inflater.inflate(chunk)
  41. 564 @bytesize -= chunk.bytesize
  42. 564 if @bytesize <= 0
  43. 94 buffer << @inflater.finish
  44. 94 @inflater.close
  45. end
  46. 564 buffer
  47. end
  48. end
  49. 26 module_function
  50. 26 def encode(body)
  51. 45 Deflater.new(body)
  52. end
  53. 26 def decode(response, bytesize: nil)
  54. 123 bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
  55. 123 Inflater.new(bytesize)
  56. end
  57. end
  58. end
  59. 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. 26 require "forwardable"
  3. 26 module HTTPX::Transcoder
  4. 26 module JSON
  5. 26 module_function
  6. 26 JSON_REGEX = %r{
  7. \b
  8. application/
  9. # optional vendor specific type
  10. (?:
  11. # token as per https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.6
  12. [!#$%&'*+\-.^_`|~0-9a-z]+
  13. # literal plus sign
  14. \+
  15. )?
  16. json
  17. \b
  18. }ix.freeze
  19. 26 class Encoder
  20. 26 extend Forwardable
  21. 26 def_delegator :@raw, :to_s
  22. 26 def_delegator :@raw, :bytesize
  23. 26 def_delegator :@raw, :==
  24. 26 def initialize(json)
  25. 73 @raw = JSON.json_dump(json)
  26. 73 @charset = @raw.encoding.name.downcase
  27. end
  28. 26 def content_type
  29. 73 "application/json; charset=#{@charset}"
  30. end
  31. end
  32. 26 def encode(json)
  33. 73 Encoder.new(json)
  34. end
  35. 26 def decode(response)
  36. 142 content_type = response.content_type.mime_type
  37. 142 raise HTTPX::Error, "invalid json mime type (#{content_type})" unless JSON_REGEX.match?(content_type)
  38. 128 method(:json_load)
  39. end
  40. # rubocop:disable Style/SingleLineMethods
  41. 26 if defined?(MultiJson)
  42. 4 def json_load(*args); MultiJson.load(*args); end
  43. 2 def json_dump(*args); MultiJson.dump(*args); end
  44. 24 elsif defined?(Oj)
  45. 5 def json_load(response, *args); Oj.load(response.to_s, *args); end
  46. 3 def json_dump(obj, options = {}); Oj.dump(obj, { mode: :compat }.merge(options)); end
  47. 22 elsif defined?(Yajl)
  48. 4 def json_load(response, *args); Yajl::Parser.new(*args).parse(response.to_s); end
  49. 2 def json_dump(*args); Yajl::Encoder.encode(*args); end
  50. else
  51. 22 require "json"
  52. 141 def json_load(*args); ::JSON.parse(*args); end
  53. 92 def json_dump(*args); ::JSON.dump(*args); end
  54. end
  55. # rubocop:enable Style/SingleLineMethods
  56. end
  57. end

lib/httpx/transcoder/multipart.rb

100.0% lines covered

18 relevant lines. 18 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require_relative "multipart/encoder"
  3. 26 require_relative "multipart/decoder"
  4. 26 require_relative "multipart/part"
  5. 26 require_relative "multipart/mime_type_detector"
  6. 26 module HTTPX::Transcoder
  7. 26 module Multipart
  8. 26 MULTIPART_VALUE_COND = lambda do |value|
  9. 4149 value.respond_to?(:read) ||
  10. 2941 (value.respond_to?(:to_hash) &&
  11. value.key?(:body) &&
  12. 676 (value.key?(:filename) || value.key?(:content_type)))
  13. end
  14. 26 module_function
  15. 26 def multipart?(form_data)
  16. 1406 form_data.any? do |_, v|
  17. 1812 Multipart::MULTIPART_VALUE_COND.call(v) ||
  18. 1369 (v.respond_to?(:to_ary) && v.to_ary.any?(&Multipart::MULTIPART_VALUE_COND)) ||
  19. 1705 (v.respond_to?(:to_hash) && v.to_hash.any? { |_, e| Multipart::MULTIPART_VALUE_COND.call(e) })
  20. end
  21. end
  22. 26 def encode(form_data)
  23. 891 Encoder.new(form_data)
  24. end
  25. end
  26. end

lib/httpx/transcoder/multipart/decoder.rb

93.9% lines covered

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

lib/httpx/transcoder/multipart/encoder.rb

100.0% lines covered

70 relevant lines. 70 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 module HTTPX
  3. 26 module Transcoder::Multipart
  4. 26 class Encoder
  5. 26 attr_reader :bytesize
  6. 26 def initialize(form)
  7. 891 @boundary = ("-" * 21) << SecureRandom.hex(21)
  8. 891 @part_index = 0
  9. 891 @buffer = "".b
  10. 891 @form = form
  11. 891 @bytesize = 0
  12. 891 @parts = to_parts(form)
  13. end
  14. 26 def content_type
  15. 891 "multipart/form-data; boundary=#{@boundary}"
  16. end
  17. 26 def to_s
  18. 18 read || ""
  19. ensure
  20. 18 rewind
  21. end
  22. 26 def read(length = nil, outbuf = nil)
  23. 3310 data = String(outbuf).clear.force_encoding(Encoding::BINARY) if outbuf
  24. 3310 data ||= "".b
  25. 3310 read_chunks(data, length)
  26. 3310 data unless length && data.empty?
  27. end
  28. 26 def rewind
  29. 46 form = @form.each_with_object([]) do |(key, val), aux|
  30. 46 if val.respond_to?(:path) && val.respond_to?(:reopen) && val.respond_to?(:closed?) && val.closed?
  31. # @type var val: File
  32. 46 val = val.reopen(val.path, File::RDONLY)
  33. end
  34. 46 val.rewind if val.respond_to?(:rewind)
  35. 46 aux << [key, val]
  36. end
  37. 46 @form = form
  38. 46 @bytesize = 0
  39. 46 @parts = to_parts(form)
  40. 46 @part_index = 0
  41. end
  42. 26 private
  43. 26 def to_parts(form)
  44. 937 params = form.each_with_object([]) do |(key, val), aux|
  45. 1105 Transcoder.normalize_keys(key, val, MULTIPART_VALUE_COND) do |k, v|
  46. 1105 next if v.nil?
  47. 1105 value, content_type, filename = Part.call(v)
  48. 1105 header = header_part(k, content_type, filename)
  49. 1105 @bytesize += header.size
  50. 1105 aux << header
  51. 1105 @bytesize += value.size
  52. 1105 aux << value
  53. 1105 delimiter = StringIO.new("\r\n")
  54. 1105 @bytesize += delimiter.size
  55. 1105 aux << delimiter
  56. end
  57. end
  58. 937 final_delimiter = StringIO.new("--#{@boundary}--\r\n")
  59. 937 @bytesize += final_delimiter.size
  60. 937 params << final_delimiter
  61. 937 params
  62. end
  63. 26 def header_part(key, content_type, filename)
  64. 1105 header = "--#{@boundary}\r\n".b
  65. 1105 header << "Content-Disposition: form-data; name=#{key.inspect}".b
  66. 1105 header << "; filename=#{filename.inspect}" if filename
  67. 1105 header << "\r\nContent-Type: #{content_type}\r\n\r\n"
  68. 1105 StringIO.new(header)
  69. end
  70. 26 def read_chunks(buffer, length = nil)
  71. 3310 while @part_index < @parts.size
  72. 9852 chunk = read_from_part(length)
  73. 9852 next unless chunk
  74. 5648 buffer << chunk.force_encoding(Encoding::BINARY)
  75. 5648 next unless length
  76. 5582 length -= chunk.bytesize
  77. 5582 break if length.zero?
  78. end
  79. end
  80. # if there's a current part to read from, tries to read a chunk.
  81. 26 def read_from_part(max_length = nil)
  82. 9852 part = @parts[@part_index]
  83. 9852 chunk = part.read(max_length, @buffer)
  84. 9852 return chunk if chunk && !chunk.empty?
  85. 4204 part.close if part.respond_to?(:close)
  86. 4204 @part_index += 1
  87. 1204 nil
  88. end
  89. end
  90. end
  91. 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. 26 module HTTPX
  3. 26 module Transcoder::Multipart
  4. 26 module MimeTypeDetector
  5. 26 module_function
  6. 26 DEFAULT_MIMETYPE = "application/octet-stream"
  7. # inspired by https://github.com/shrinerb/shrine/blob/master/lib/shrine/plugins/determine_mime_type.rb
  8. 26 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. 24 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. 23 elsif defined?(MimeMagic)
  24. 1 def call(file, _)
  25. 1 mime = MimeMagic.by_magic(file)
  26. 1 mime.type if mime
  27. end
  28. 22 elsif system("which file", out: File::NULL)
  29. 23 require "open3"
  30. 23 def call(file, _)
  31. 653 return if file.eof? # file command returns "application/x-empty" for empty files
  32. 613 Open3.popen3(*%w[file --mime-type --brief -]) do |stdin, stdout, stderr, thread|
  33. 83 begin
  34. 613 IO.copy_stream(file, stdin.binmode)
  35. rescue Errno::EPIPE
  36. end
  37. 613 file.rewind
  38. 613 stdin.close
  39. 613 status = thread.value
  40. # call to file command failed
  41. 613 if status.nil? || !status.success?
  42. $stderr.print(stderr.read)
  43. else
  44. 613 output = stdout.read.strip
  45. 613 if output.include?("cannot open")
  46. $stderr.print(output)
  47. else
  48. 613 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. 26 module HTTPX
  3. 26 module Transcoder::Multipart
  4. 26 module Part
  5. 26 module_function
  6. 26 def call(value)
  7. # take out specialized objects of the way
  8. 1105 if value.respond_to?(:filename) && value.respond_to?(:content_type) && value.respond_to?(:read)
  9. 112 return value, value.content_type, value.filename
  10. end
  11. 993 content_type = filename = nil
  12. 993 if value.is_a?(Hash)
  13. 338 content_type = value[:content_type]
  14. 338 filename = value[:filename]
  15. 338 value = value[:body]
  16. end
  17. 993 value = value.open(File::RDONLY, encoding: Encoding::BINARY) if Object.const_defined?(:Pathname) && value.is_a?(Pathname)
  18. 993 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. 657 filename ||= File.basename(value.path)
  21. 657 content_type ||= MimeTypeDetector.call(value, filename) || "application/octet-stream"
  22. 657 [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

95.83% lines covered

24 relevant lines. 23 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 26 require "stringio"
  3. 26 module HTTPX
  4. 26 module Transcoder
  5. 26 class BodyReader
  6. 26 def initialize(body)
  7. 204 @body = if body.respond_to?(:read)
  8. 19 body.rewind if body.respond_to?(:rewind)
  9. 19 body
  10. 184 elsif body.respond_to?(:each)
  11. 36 body.enum_for(:each)
  12. else
  13. 149 StringIO.new(body.to_s)
  14. end
  15. end
  16. 26 def bytesize
  17. 450 return @body.bytesize if @body.respond_to?(:bytesize)
  18. 414 Float::INFINITY
  19. end
  20. 26 def read(length = nil, outbuf = nil)
  21. 450 return @body.read(length, outbuf) if @body.respond_to?(:read)
  22. begin
  23. 96 chunk = @body.next
  24. 48 if outbuf
  25. outbuf.replace(chunk)
  26. else
  27. 48 outbuf = chunk
  28. end
  29. 48 outbuf unless length && outbuf.empty?
  30. 32 rescue StopIteration
  31. end
  32. end
  33. 26 def close
  34. 45 @body.close if @body.respond_to?(:close)
  35. end
  36. end
  37. end
  38. 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. 26 require_relative "body_reader"
  3. 26 module HTTPX
  4. 26 module Transcoder
  5. 26 class Deflater
  6. 26 attr_reader :content_type
  7. 26 def initialize(body)
  8. 78 @content_type = body.content_type
  9. 78 @body = BodyReader.new(body)
  10. 78 @closed = false
  11. end
  12. 26 def bytesize
  13. 300 buffer_deflate!
  14. 300 @buffer.size
  15. end
  16. 26 def read(length = nil, outbuf = nil)
  17. 382 return @buffer.read(length, outbuf) if @buffer
  18. 219 return if @closed
  19. 174 chunk = @body.read(length)
  20. 174 compressed_chunk = deflate(chunk)
  21. 174 return unless compressed_chunk
  22. 141 if outbuf
  23. 132 outbuf.replace(compressed_chunk)
  24. else
  25. 9 compressed_chunk
  26. end
  27. end
  28. 26 def close
  29. 45 return if @closed
  30. 45 @buffer.close if @buffer
  31. 45 @body.close
  32. 45 @closed = true
  33. end
  34. 26 def rewind
  35. 26 return unless @buffer
  36. 14 @buffer.rewind
  37. end
  38. 26 private
  39. # rubocop:disable Naming/MemoizedInstanceVariableName
  40. 26 def buffer_deflate!
  41. 300 return @buffer if defined?(@buffer)
  42. 78 buffer = Response::Buffer.new(
  43. threshold_size: Options::MAX_BODY_THRESHOLD_SIZE
  44. )
  45. 78 IO.copy_stream(self, buffer)
  46. 78 buffer.rewind if buffer.respond_to?(:rewind)
  47. 78 @buffer = buffer
  48. end
  49. # rubocop:enable Naming/MemoizedInstanceVariableName
  50. end
  51. end
  52. 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. 26 module HTTPX
  3. 26 module Utils
  4. 26 using URIExtensions
  5. 26 TOKEN = %r{[^\s()<>,;:\\"/\[\]?=]+}.freeze
  6. 26 VALUE = /"(?:\\"|[^"])*"|#{TOKEN}/.freeze
  7. 26 FILENAME_REGEX = /\s*filename=(#{VALUE})/.freeze
  8. 26 FILENAME_EXTENSION_REGEX = /\s*filename\*=(#{VALUE})/.freeze
  9. 26 module_function
  10. 26 def now
  11. 8591287 Process.clock_gettime(Process::CLOCK_MONOTONIC)
  12. end
  13. 26 def elapsed_time(monotonic_timestamp)
  14. 8558603 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. 26 def parse_retry_after(retry_after)
  19. # first: bet on it being an integer
  20. 54 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. 26 def get_filename(header, _prefix_regex = nil)
  27. 77 filename = nil
  28. 77 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. 26 URIParser = URI::RFC2396_Parser.new
  44. 26 def to_uri(uri)
  45. 16412 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