loading
Generated 2026-01-19T10:02:52+00:00

All Files ( 96.42% covered at 3623.53 hits/line )

110 files in total.
8441 relevant lines, 8139 lines covered and 302 lines missed. ( 96.42% )
File % covered Lines Relevant Lines Lines covered Lines missed Avg. Hits / Line
lib/httpx.rb 100.00 % 66 39 39 0 1442.97
lib/httpx/adapters/datadog.rb 86.98 % 359 169 147 22 61.22
lib/httpx/adapters/faraday.rb 98.77 % 303 163 161 2 153.13
lib/httpx/adapters/sentry.rb 100.00 % 121 62 62 0 57.74
lib/httpx/adapters/webmock.rb 100.00 % 184 95 95 0 138.61
lib/httpx/altsvc.rb 96.43 % 165 84 81 3 299.33
lib/httpx/buffer.rb 100.00 % 61 27 27 0 6103.96
lib/httpx/callbacks.rb 100.00 % 35 19 19 0 168368.53
lib/httpx/chainable.rb 95.65 % 106 46 44 2 1373.70
lib/httpx/connection.rb 95.38 % 962 476 454 22 8872.02
lib/httpx/connection/http1.rb 89.59 % 398 221 198 23 4535.47
lib/httpx/connection/http2.rb 95.60 % 469 273 261 12 4947.22
lib/httpx/domain_name.rb 95.56 % 145 45 43 2 277.76
lib/httpx/errors.rb 97.67 % 111 43 42 1 111.63
lib/httpx/extensions.rb 95.24 % 45 21 20 1 630.33
lib/httpx/headers.rb 100.00 % 176 71 71 0 19580.21
lib/httpx/io.rb 100.00 % 11 5 5 0 30.00
lib/httpx/io/ssl.rb 97.67 % 163 86 84 2 3035.50
lib/httpx/io/tcp.rb 93.70 % 239 127 119 8 8996.01
lib/httpx/io/udp.rb 100.00 % 62 35 35 0 444.83
lib/httpx/io/unix.rb 97.14 % 71 35 34 1 23.60
lib/httpx/loggable.rb 100.00 % 68 29 29 0 54455.34
lib/httpx/options.rb 96.27 % 579 241 232 9 25203.73
lib/httpx/parser/http1.rb 100.00 % 187 110 110 0 9231.97
lib/httpx/plugins/auth.rb 100.00 % 115 52 52 0 326.12
lib/httpx/plugins/auth/basic.rb 100.00 % 20 10 10 0 113.50
lib/httpx/plugins/auth/digest.rb 98.80 % 142 83 82 1 208.59
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 26.64
lib/httpx/plugins/aws_sdk_authentication.rb 100.00 % 110 44 44 0 14.73
lib/httpx/plugins/aws_sigv4.rb 100.00 % 239 122 122 0 113.66
lib/httpx/plugins/basic_auth.rb 100.00 % 29 12 12 0 39.75
lib/httpx/plugins/brotli.rb 100.00 % 50 25 25 0 12.60
lib/httpx/plugins/callbacks.rb 92.65 % 141 68 63 5 142.43
lib/httpx/plugins/circuit_breaker.rb 100.00 % 147 67 67 0 83.16
lib/httpx/plugins/circuit_breaker/circuit.rb 100.00 % 100 47 47 0 66.23
lib/httpx/plugins/circuit_breaker/circuit_store.rb 100.00 % 53 23 23 0 110.83
lib/httpx/plugins/content_digest.rb 100.00 % 204 103 103 0 88.86
lib/httpx/plugins/cookies.rb 100.00 % 107 52 52 0 137.96
lib/httpx/plugins/cookies/cookie.rb 100.00 % 175 77 77 0 357.97
lib/httpx/plugins/cookies/jar.rb 100.00 % 95 46 46 0 293.13
lib/httpx/plugins/cookies/set_cookie_parser.rb 100.00 % 143 72 72 0 176.39
lib/httpx/plugins/digest_auth.rb 100.00 % 66 30 30 0 114.60
lib/httpx/plugins/expect.rb 100.00 % 120 57 57 0 86.63
lib/httpx/plugins/fiber_concurrency.rb 88.00 % 210 100 88 12 771.55
lib/httpx/plugins/follow_redirects.rb 100.00 % 233 109 109 0 255.40
lib/httpx/plugins/grpc.rb 100.00 % 282 134 134 0 142.46
lib/httpx/plugins/grpc/call.rb 90.91 % 63 33 30 3 46.88
lib/httpx/plugins/grpc/grpc_encoding.rb 97.87 % 90 47 46 1 89.66
lib/httpx/plugins/grpc/message.rb 95.83 % 55 24 23 1 46.08
lib/httpx/plugins/h2c.rb 95.24 % 127 63 60 3 19.51
lib/httpx/plugins/ntlm_auth.rb 100.00 % 64 33 33 0 3.82
lib/httpx/plugins/oauth.rb 90.65 % 293 139 126 13 82.75
lib/httpx/plugins/persistent.rb 100.00 % 82 31 31 0 504.94
lib/httpx/plugins/proxy.rb 94.77 % 349 172 163 9 386.78
lib/httpx/plugins/proxy/http.rb 94.74 % 208 114 108 6 166.21
lib/httpx/plugins/proxy/socks4.rb 97.47 % 135 79 77 2 212.47
lib/httpx/plugins/proxy/socks5.rb 99.12 % 194 113 112 1 347.41
lib/httpx/plugins/proxy/ssh.rb 92.45 % 94 53 49 4 9.51
lib/httpx/plugins/push_promise.rb 100.00 % 81 41 41 0 11.80
lib/httpx/plugins/query.rb 100.00 % 35 15 15 0 11.33
lib/httpx/plugins/rate_limiter.rb 100.00 % 55 18 18 0 46.89
lib/httpx/plugins/response_cache.rb 100.00 % 340 148 148 0 224.63
lib/httpx/plugins/response_cache/file_store.rb 100.00 % 141 73 73 0 208.30
lib/httpx/plugins/response_cache/store.rb 100.00 % 33 16 16 0 185.69
lib/httpx/plugins/retries.rb 97.35 % 269 113 110 3 507.07
lib/httpx/plugins/ssrf_filter.rb 100.00 % 145 61 61 0 141.08
lib/httpx/plugins/stream.rb 97.32 % 234 112 109 3 170.82
lib/httpx/plugins/stream_bidi.rb 94.25 % 392 174 164 10 191.80
lib/httpx/plugins/upgrade.rb 100.00 % 86 38 38 0 52.63
lib/httpx/plugins/upgrade/h2.rb 89.66 % 64 29 26 3 41.48
lib/httpx/plugins/webdav.rb 100.00 % 86 39 39 0 26.00
lib/httpx/plugins/xml.rb 100.00 % 76 34 34 0 94.97
lib/httpx/pmatch_extensions.rb 100.00 % 33 17 17 0 32.12
lib/httpx/pool.rb 100.00 % 233 109 109 0 5414.24
lib/httpx/punycode.rb 100.00 % 22 9 9 0 20.89
lib/httpx/request.rb 100.00 % 327 138 138 0 7843.93
lib/httpx/request/body.rb 100.00 % 158 68 68 0 3781.24
lib/httpx/resolver.rb 93.22 % 111 59 55 4 577.85
lib/httpx/resolver/cache.rb 100.00 % 18 4 4 0 30.00
lib/httpx/resolver/cache/base.rb 98.41 % 136 63 62 1 3341.70
lib/httpx/resolver/cache/memory.rb 100.00 % 42 22 22 0 3233.18
lib/httpx/resolver/entry.rb 100.00 % 30 16 16 0 5579.38
lib/httpx/resolver/https.rb 84.49 % 326 187 158 29 62.35
lib/httpx/resolver/multi.rb 100.00 % 91 49 49 0 5617.61
lib/httpx/resolver/native.rb 92.17 % 577 332 306 26 1164.01
lib/httpx/resolver/resolver.rb 96.74 % 190 92 89 3 1736.66
lib/httpx/resolver/system.rb 95.42 % 279 153 146 7 112.31
lib/httpx/response.rb 100.00 % 320 124 124 0 2811.06
lib/httpx/response/body.rb 100.00 % 244 109 109 0 3468.78
lib/httpx/response/buffer.rb 96.72 % 115 61 59 2 1985.79
lib/httpx/selector.rb 91.10 % 308 146 133 13 9877.27
lib/httpx/session.rb 95.27 % 602 296 282 14 5158.04
lib/httpx/session_extensions.rb 100.00 % 30 15 15 0 6.87
lib/httpx/timers.rb 93.75 % 127 64 60 4 14172.83
lib/httpx/transcoder.rb 100.00 % 89 50 50 0 242.46
lib/httpx/transcoder/body.rb 100.00 % 43 26 26 0 1142.38
lib/httpx/transcoder/chunker.rb 100.00 % 115 66 66 0 240.58
lib/httpx/transcoder/deflate.rb 100.00 % 42 21 21 0 33.71
lib/httpx/transcoder/form.rb 100.00 % 68 35 35 0 282.34
lib/httpx/transcoder/gzip.rb 100.00 % 76 44 44 0 134.41
lib/httpx/transcoder/json.rb 100.00 % 71 33 33 0 57.36
lib/httpx/transcoder/multipart.rb 100.00 % 39 22 22 0 1092.32
lib/httpx/transcoder/multipart/decoder.rb 94.05 % 141 84 79 5 32.54
lib/httpx/transcoder/multipart/encoder.rb 100.00 % 120 70 70 0 2330.80
lib/httpx/transcoder/multipart/mime_type_detector.rb 92.11 % 78 38 35 3 218.71
lib/httpx/transcoder/multipart/part.rb 100.00 % 35 18 18 0 612.67
lib/httpx/transcoder/utils/body_reader.rb 95.83 % 45 24 23 1 120.04
lib/httpx/transcoder/utils/deflater.rb 100.00 % 74 36 36 0 115.36
lib/httpx/utils.rb 100.00 % 88 44 44 0 2436.82

lib/httpx.rb

100.0% lines covered

39 relevant lines. 39 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "httpx/version"
  3. # Top-Level Namespace
  4. #
  5. 30 module HTTPX
  6. 30 EMPTY = [].freeze
  7. 30 EMPTY_HASH = {}.freeze
  8. # All plugins should be stored under this module/namespace. Can register and load
  9. # plugins.
  10. #
  11. 30 module Plugins
  12. 30 @plugins = {}
  13. 30 @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. 30 def self.load_plugin(name)
  18. 10536 h = @plugins
  19. 10536 m = @plugins_mutex
  20. 21072 unless (plugin = m.synchronize { h[name] })
  21. 363 require "httpx/plugins/#{name}"
  22. 726 raise "Plugin #{name} hasn't been registered" unless (plugin = m.synchronize { h[name] })
  23. end
  24. 10536 plugin
  25. end
  26. # Registers a plugin (+mod+) in the central store indexed by +name+.
  27. #
  28. 30 def self.register_plugin(name, mod)
  29. 410 h = @plugins
  30. 410 m = @plugins_mutex
  31. 787 m.synchronize { h[name] = mod }
  32. end
  33. end
  34. end
  35. 30 require "httpx/extensions"
  36. 30 require "httpx/errors"
  37. 30 require "httpx/utils"
  38. 30 require "httpx/punycode"
  39. 30 require "httpx/domain_name"
  40. 30 require "httpx/altsvc"
  41. 30 require "httpx/callbacks"
  42. 30 require "httpx/loggable"
  43. 30 require "httpx/transcoder"
  44. 30 require "httpx/timers"
  45. 30 require "httpx/pool"
  46. 30 require "httpx/headers"
  47. 30 require "httpx/request"
  48. 30 require "httpx/response"
  49. 30 require "httpx/options"
  50. 30 require "httpx/chainable"
  51. 30 require "httpx/session"
  52. 30 require "httpx/session_extensions"
  53. # load integrations when possible
  54. 30 require "httpx/adapters/datadog" if defined?(DDTrace) || defined?(Datadog::Tracing)
  55. 30 require "httpx/adapters/sentry" if defined?(Sentry)
  56. 30 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. 7 require "datadog/tracing/contrib/integration"
  3. 7 require "datadog/tracing/contrib/configuration/settings"
  4. 7 require "datadog/tracing/contrib/patcher"
  5. 7 module Datadog::Tracing
  6. 7 module Contrib
  7. 7 module HTTPX
  8. 7 DATADOG_VERSION = defined?(::DDTrace) ? ::DDTrace::VERSION : ::Datadog::VERSION
  9. 7 METADATA_MODULE = Datadog::Tracing::Metadata
  10. 7 TYPE_OUTBOUND = Datadog::Tracing::Metadata::Ext::HTTP::TYPE_OUTBOUND
  11. 7 TAG_BASE_SERVICE = if Gem::Version.new(DATADOG_VERSION::STRING) < Gem::Version.new("1.15.0")
  12. "_dd.base_service"
  13. else
  14. 7 Datadog::Tracing::Contrib::Ext::Metadata::TAG_BASE_SERVICE
  15. end
  16. 7 TAG_PEER_HOSTNAME = Datadog::Tracing::Metadata::Ext::TAG_PEER_HOSTNAME
  17. 7 TAG_KIND = Datadog::Tracing::Metadata::Ext::TAG_KIND
  18. 7 TAG_CLIENT = Datadog::Tracing::Metadata::Ext::SpanKind::TAG_CLIENT
  19. 7 TAG_COMPONENT = Datadog::Tracing::Metadata::Ext::TAG_COMPONENT
  20. 7 TAG_OPERATION = Datadog::Tracing::Metadata::Ext::TAG_OPERATION
  21. 7 TAG_URL = Datadog::Tracing::Metadata::Ext::HTTP::TAG_URL
  22. 7 TAG_METHOD = Datadog::Tracing::Metadata::Ext::HTTP::TAG_METHOD
  23. 7 TAG_TARGET_HOST = Datadog::Tracing::Metadata::Ext::NET::TAG_TARGET_HOST
  24. 7 TAG_TARGET_PORT = Datadog::Tracing::Metadata::Ext::NET::TAG_TARGET_PORT
  25. 7 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. 7 module Plugin
  34. 7 module RequestTracer
  35. 7 extend Contrib::HttpAnnotationHelper
  36. 7 module_function
  37. 7 SPAN_REQUEST = "httpx.request"
  38. # initializes tracing on the +request+.
  39. 7 def call(request)
  40. 425 return unless configuration(request).enabled
  41. 98 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. 98 request.on(:idle) do
  47. 21 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. 98 request.on(:headers) do
  52. 112 next if span
  53. 112 span = initialize_span(request, now)
  54. end
  55. 98 request.on(:response) do |response|
  56. 112 span = initialize_span(request, request.init_time) if !span && request.init_time
  57. 112 finish(response, span)
  58. end
  59. end
  60. 7 def finish(response, span)
  61. 112 if response.is_a?(::HTTPX::ErrorResponse)
  62. 7 span.set_error(response.error)
  63. else
  64. 105 span.set_tag(TAG_STATUS_CODE, response.status.to_s)
  65. 105 span.set_error(::HTTPX::HTTPError.new(response)) if response.status.between?(400, 599)
  66. span.set_tags(
  67. Datadog.configuration.tracing.header_tags.response_tags(response.headers.to_h)
  68. 105 ) if Datadog.configuration.tracing.respond_to?(:header_tags)
  69. end
  70. 112 span.finish
  71. end
  72. # return a span initialized with the +@request+ state.
  73. 7 def initialize_span(request, start_time)
  74. 119 verb = request.verb
  75. 119 uri = request.uri
  76. 119 config = configuration(request)
  77. 119 span = create_span(request, config, start_time)
  78. 119 span.resource = verb
  79. # Tag original global service name if not used
  80. 119 span.set_tag(TAG_BASE_SERVICE, Datadog.configuration.service) if span.service != Datadog.configuration.service
  81. 119 span.set_tag(TAG_KIND, TAG_CLIENT)
  82. 119 span.set_tag(TAG_COMPONENT, "httpx")
  83. 119 span.set_tag(TAG_OPERATION, "request")
  84. 119 span.set_tag(TAG_URL, request.path)
  85. 119 span.set_tag(TAG_METHOD, verb)
  86. 119 span.set_tag(TAG_TARGET_HOST, uri.host)
  87. 119 span.set_tag(TAG_TARGET_PORT, uri.port)
  88. 119 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. 119 if config[:distributed_tracing]
  92. 112 propagate_trace_http(
  93. Datadog::Tracing.active_trace,
  94. request.headers
  95. )
  96. end
  97. # Set analytics sample rate
  98. 119 if Contrib::Analytics.enabled?(config[:analytics_enabled])
  99. 14 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. 119 ) if Datadog.configuration.tracing.respond_to?(:header_tags)
  104. 119 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. 7 def now
  110. 112 ::Datadog::Core::Utils::Time.now.utc
  111. end
  112. 7 def configuration(request)
  113. 544 Datadog.configuration.tracing[:httpx, request.uri.host]
  114. end
  115. 7 if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("2.0.0")
  116. 4 def propagate_trace_http(trace, headers)
  117. 64 Datadog::Tracing::Contrib::HTTP.inject(trace, headers)
  118. end
  119. 4 def create_span(request, configuration, start_time)
  120. 68 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. 7 module RequestMethods
  142. 7 attr_accessor :init_time
  143. # intercepts request initialization to inject the tracing logic.
  144. 7 def initialize(*)
  145. 425 super
  146. 425 @init_time = nil
  147. 425 return unless Datadog::Tracing.enabled?
  148. 425 RequestTracer.call(self)
  149. end
  150. 7 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. 445 @init_time ||= ::Datadog::Core::Utils::Time.now.utc
  157. 445 super
  158. end
  159. end
  160. 7 module ConnectionMethods
  161. 7 def initialize(*)
  162. 393 super
  163. 393 @init_time = ::Datadog::Core::Utils::Time.now.utc
  164. end
  165. 7 def send(request)
  166. 229 request.init_time ||= @init_time
  167. 229 super
  168. end
  169. end
  170. end
  171. 7 module Configuration
  172. # Default settings for httpx
  173. #
  174. 7 class Settings < Datadog::Tracing::Contrib::Configuration::Settings
  175. 7 DEFAULT_ERROR_HANDLER = lambda do |response|
  176. Datadog::Ext::HTTP::ERROR_RANGE.cover?(response.status)
  177. end
  178. 7 option :service_name, default: "httpx"
  179. 7 option :distributed_tracing, default: true
  180. 7 option :split_by_domain, default: false
  181. 7 if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
  182. 7 option :enabled do |o|
  183. 7 o.type :bool
  184. 7 o.env "DD_TRACE_HTTPX_ENABLED"
  185. 7 o.default true
  186. end
  187. 7 option :analytics_enabled do |o|
  188. 7 o.type :bool
  189. 7 o.env "DD_TRACE_HTTPX_ANALYTICS_ENABLED"
  190. 7 o.default false
  191. end
  192. 7 option :analytics_sample_rate do |o|
  193. 7 o.type :float
  194. 7 o.env "DD_TRACE_HTTPX_ANALYTICS_SAMPLE_RATE"
  195. 7 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. 7 if defined?(Datadog::Tracing::Contrib::SpanAttributeSchema)
  212. 7 option :service_name do |o|
  213. 7 o.default do
  214. 77 Datadog::Tracing::Contrib::SpanAttributeSchema.fetch_service_name(
  215. "DD_TRACE_HTTPX_SERVICE_NAME",
  216. "httpx"
  217. )
  218. end
  219. 7 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. 7 option :distributed_tracing, default: true
  230. 7 if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.15.0")
  231. 7 option :error_handler do |o|
  232. 7 o.type :proc
  233. 7 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. 7 module Patcher
  248. 7 include Datadog::Tracing::Contrib::Patcher
  249. 7 module_function
  250. 7 def target_version
  251. 14 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. 7 def patch
  256. 7 datadog_session = ::HTTPX.plugin(Plugin)
  257. 7 ::HTTPX.send(:remove_const, :Session)
  258. 7 ::HTTPX.send(:const_set, :Session, datadog_session.class)
  259. end
  260. end
  261. # Datadog Integration for HTTPX.
  262. #
  263. 7 class Integration
  264. 7 include Contrib::Integration
  265. 7 MINIMUM_VERSION = Gem::Version.new("0.10.2")
  266. 7 register_as :httpx
  267. 7 def self.version
  268. 287 Gem.loaded_specs["httpx"] && Gem.loaded_specs["httpx"].version
  269. end
  270. 7 def self.loaded?
  271. 91 defined?(::HTTPX::Request)
  272. end
  273. 7 def self.compatible?
  274. 91 super && version >= MINIMUM_VERSION
  275. end
  276. 7 def new_configuration
  277. 182 Configuration::Settings.new
  278. end
  279. 7 def patcher
  280. 182 Patcher
  281. end
  282. end
  283. end
  284. end
  285. end

lib/httpx/adapters/faraday.rb

98.77% lines covered

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

lib/httpx/adapters/webmock.rb

100.0% lines covered

95 relevant lines. 95 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module WebMock
  3. 9 module HttpLibAdapters
  4. 9 require "net/http/status"
  5. 9 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. 9 module Plugin
  12. 9 class << self
  13. 9 def build_webmock_request_signature(request)
  14. 291 uri = WebMock::Util::URI.heuristic_parse(request.uri)
  15. 291 uri.query = request.query
  16. 291 uri.path = uri.normalized_path.gsub("[^:]//", "/")
  17. 291 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. 9 def build_webmock_response(_request, response)
  25. 7 webmock_response = WebMock::Response.new
  26. 7 webmock_response.status = [response.status, HTTP_REASONS[response.status]]
  27. 7 webmock_response.body = response.body.to_s
  28. 7 webmock_response.headers = response.headers.to_h
  29. 7 webmock_response
  30. end
  31. 9 def build_from_webmock_response(request, webmock_response)
  32. 256 return build_error_response(request, HTTPX::TimeoutError.new(1, "Timed out")) if webmock_response.should_timeout
  33. 235 return build_error_response(request, webmock_response.exception) if webmock_response.exception
  34. 227 request
  35. .options
  36. .response_class
  37. .new(
  38. request,
  39. webmock_response.status[0],
  40. "2.0",
  41. webmock_response.headers
  42. ).tap(&:mock!)
  43. end
  44. 9 def build_error_response(request, exception)
  45. 29 HTTPX::ErrorResponse.new(request, exception)
  46. end
  47. end
  48. 9 module InstanceMethods
  49. 9 private
  50. 9 def do_init_connection(connection, selector)
  51. 256 super
  52. 256 connection.once(:unmock_connection) do
  53. 28 next unless connection.current_session == self
  54. 28 unless connection.addresses?
  55. # reset Happy Eyeballs, fail early
  56. 28 connection.sibling = nil
  57. 28 deselect_connection(connection, selector)
  58. end
  59. 28 resolve_connection(connection, selector)
  60. end
  61. end
  62. end
  63. 9 module ResponseMethods
  64. 9 def initialize(*)
  65. 255 super
  66. 255 @mocked = false
  67. end
  68. 9 def mock!
  69. 227 @mocked = true
  70. end
  71. 9 def mocked?
  72. 112 @mocked
  73. end
  74. end
  75. 9 module ResponseBodyMethods
  76. 9 def decode_chunk(chunk)
  77. 112 return chunk if @response.mocked?
  78. 49 super
  79. end
  80. end
  81. 9 module ConnectionMethods
  82. 9 def initialize(*)
  83. 256 super
  84. 256 @mocked = true
  85. end
  86. 9 def open?
  87. 284 return true if @mocked
  88. 28 super
  89. end
  90. 9 def interests
  91. 322 return if @mocked
  92. 287 super
  93. end
  94. 9 def terminate
  95. 227 force_reset
  96. end
  97. 9 def send(request)
  98. 291 request_signature = Plugin.build_webmock_request_signature(request)
  99. 291 WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
  100. 291 if (mock_response = WebMock::StubRegistry.instance.response_for_request(request_signature))
  101. 256 response = Plugin.build_from_webmock_response(request, mock_response)
  102. 256 WebMock::CallbackRegistry.invoke_callbacks({ lib: :httpx }, request_signature, mock_response)
  103. 256 log { "mocking #{request.uri} with #{mock_response.inspect}" }
  104. 256 request.transition(:headers)
  105. 256 request.transition(:body)
  106. 256 request.transition(:trailers)
  107. 256 request.transition(:done)
  108. 256 response.finish!
  109. 256 request.response = response
  110. 256 request.emit(:response, response)
  111. 256 request_signature.headers = request.headers.to_h
  112. 256 response << mock_response.body.dup unless response.is_a?(HTTPX::ErrorResponse)
  113. 35 elsif WebMock.net_connect_allowed?(request_signature.uri)
  114. 28 if WebMock::CallbackRegistry.any_callbacks?
  115. 7 request.on(:response) do |resp|
  116. 7 unless resp.is_a?(HTTPX::ErrorResponse)
  117. 7 webmock_response = Plugin.build_webmock_response(request, resp)
  118. 7 WebMock::CallbackRegistry.invoke_callbacks(
  119. { lib: :httpx, real_request: true }, request_signature,
  120. webmock_response
  121. )
  122. end
  123. end
  124. end
  125. 28 @mocked = false
  126. 28 emit(:unmock_connection, self)
  127. 28 super
  128. else
  129. 7 raise WebMock::NetConnectNotAllowedError, request_signature
  130. end
  131. end
  132. end
  133. end
  134. 9 class HttpxAdapter < HttpLibAdapter
  135. 9 adapter_for :httpx
  136. 9 class << self
  137. 9 def enable!
  138. 503 @original_session ||= HTTPX::Session
  139. 503 webmock_session = HTTPX.plugin(Plugin)
  140. 503 HTTPX.send(:remove_const, :Session)
  141. 503 HTTPX.send(:const_set, :Session, webmock_session.class)
  142. end
  143. 9 def disable!
  144. 503 return unless @original_session
  145. 494 HTTPX.send(:remove_const, :Session)
  146. 494 HTTPX.send(:const_set, :Session, @original_session)
  147. end
  148. end
  149. end
  150. end
  151. end

lib/httpx/altsvc.rb

96.43% lines covered

84 relevant lines. 81 lines covered and 3 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "strscan"
  3. 30 module HTTPX
  4. 30 module AltSvc
  5. # makes connections able to accept requests destined to primary service.
  6. 30 module ConnectionMixin
  7. 30 using URIExtensions
  8. 30 H2_ALTSVC_SCHEMES = %w[https h2].freeze
  9. 30 def send(request)
  10. 9 request.headers["alt-used"] = @origin.authority if @parser && !@write_buffer.full? && match_altsvcs?(request.uri)
  11. 9 super
  12. end
  13. 30 def match?(uri, options)
  14. 9 return false if !used? && (@state == :closing || @state == :closed)
  15. 9 match_altsvcs?(uri) && match_altsvc_options?(uri, options)
  16. end
  17. 30 private
  18. # checks if this is connection is an alternative service of
  19. # +uri+
  20. 30 def match_altsvcs?(uri)
  21. 42 @origins.any? { |origin| altsvc_match?(uri, origin) } ||
  22. AltSvc.cached_altsvc(@origin).any? do |altsvc|
  23. origin = altsvc["origin"]
  24. altsvc_match?(origin, uri.origin)
  25. end
  26. end
  27. 30 def match_altsvc_options?(uri, options)
  28. 9 return @options == options unless @options.ssl.all? do |k, v|
  29. 9 v == (k == :hostname ? uri.host : options.ssl[k])
  30. end
  31. 9 @options.options_equals?(options, Options::REQUEST_BODY_IVARS + %i[@ssl])
  32. end
  33. 30 def altsvc_match?(uri, other_uri)
  34. 28 other_uri = URI(other_uri)
  35. 28 uri.origin == other_uri.origin || begin
  36. 13 case uri.scheme
  37. when "h2"
  38. H2_ALTSVC_SCHEMES.include?(other_uri.scheme) &&
  39. uri.host == other_uri.host &&
  40. uri.port == other_uri.port
  41. else
  42. 14 false
  43. end
  44. end
  45. end
  46. end
  47. 30 @altsvc_mutex = Thread::Mutex.new
  48. 54 @altsvcs = Hash.new { |h, k| h[k] = [] }
  49. 30 module_function
  50. 30 def cached_altsvc(origin)
  51. 45 now = Utils.now
  52. 45 @altsvc_mutex.synchronize do
  53. 45 lookup(origin, now)
  54. end
  55. end
  56. 30 def cached_altsvc_set(origin, entry)
  57. 27 now = Utils.now
  58. 27 @altsvc_mutex.synchronize do
  59. 27 return if @altsvcs[origin].any? { |altsvc| altsvc["origin"] == entry["origin"] }
  60. 27 entry["TTL"] = Integer(entry["ma"]) + now if entry.key?("ma")
  61. 27 @altsvcs[origin] << entry
  62. 27 entry
  63. end
  64. end
  65. 30 def lookup(origin, ttl)
  66. 45 return [] unless @altsvcs.key?(origin)
  67. 32 @altsvcs[origin] = @altsvcs[origin].select do |entry|
  68. 27 !entry.key?("TTL") || entry["TTL"] > ttl
  69. end
  70. 54 @altsvcs[origin].reject { |entry| entry["noop"] }
  71. end
  72. 30 def emit(request, response)
  73. 9493 return unless response.respond_to?(:headers)
  74. # Alt-Svc
  75. 9449 return unless response.headers.key?("alt-svc")
  76. 148 origin = request.origin
  77. 148 host = request.uri.host
  78. 148 altsvc = response.headers["alt-svc"]
  79. # https://datatracker.ietf.org/doc/html/rfc7838#section-3
  80. # A field value containing the special value "clear" indicates that the
  81. # origin requests all alternatives for that origin to be invalidated
  82. # (including those specified in the same response, in case of an
  83. # invalid reply containing both "clear" and alternative services).
  84. 148 if altsvc == "clear"
  85. 9 @altsvc_mutex.synchronize do
  86. 9 @altsvcs[origin].clear
  87. end
  88. 8 return
  89. end
  90. 139 parse(altsvc) do |alt_origin, alt_params|
  91. 18 alt_origin.host ||= host
  92. 18 yield(alt_origin, origin, alt_params)
  93. end
  94. end
  95. 30 def parse(altsvc)
  96. 265 return enum_for(__method__, altsvc) unless block_given?
  97. 202 scanner = StringScanner.new(altsvc)
  98. 209 until scanner.eos?
  99. 202 alt_service = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
  100. 202 alt_params = []
  101. 202 loop do
  102. 229 alt_param = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
  103. 229 alt_params << alt_param.strip if alt_param
  104. 229 scanner.skip(/;/)
  105. 229 break if scanner.eos? || scanner.scan(/ *, */)
  106. end
  107. 395 alt_params = Hash[alt_params.map { |field| field.split("=", 2) }]
  108. 202 alt_proto, alt_authority = alt_service.split("=", 2)
  109. 202 alt_origin = parse_altsvc_origin(alt_proto, alt_authority)
  110. 202 return unless alt_origin
  111. 63 yield(alt_origin, alt_params.merge("proto" => alt_proto))
  112. end
  113. end
  114. 30 def parse_altsvc_scheme(alt_proto)
  115. 209 case alt_proto
  116. when "h2c"
  117. 9 "http"
  118. when "h2"
  119. 72 "https"
  120. end
  121. end
  122. 30 def parse_altsvc_origin(alt_proto, alt_origin)
  123. 202 alt_scheme = parse_altsvc_scheme(alt_proto)
  124. 202 return unless alt_scheme
  125. 63 alt_origin = alt_origin[1..-2] if alt_origin.start_with?("\"") && alt_origin.end_with?("\"")
  126. 63 URI.parse("#{alt_scheme}://#{alt_origin}")
  127. end
  128. end
  129. 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. 30 require "forwardable"
  3. 30 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. 30 class Buffer
  13. 30 extend Forwardable
  14. 30 def_delegator :@buffer, :to_s
  15. 30 def_delegator :@buffer, :to_str
  16. 30 def_delegator :@buffer, :empty?
  17. 30 def_delegator :@buffer, :bytesize
  18. 30 def_delegator :@buffer, :clear
  19. 30 def_delegator :@buffer, :replace
  20. 30 attr_reader :limit
  21. 30 if RUBY_VERSION >= "3.4.0"
  22. 18 def initialize(limit)
  23. 6324 @buffer = String.new("", encoding: Encoding::BINARY, capacity: limit)
  24. 6324 @limit = limit
  25. end
  26. 18 def <<(chunk)
  27. 21572 @buffer.append_as_bytes(chunk)
  28. end
  29. else
  30. 12 def initialize(limit)
  31. 20517 @buffer = "".b
  32. 20517 @limit = limit
  33. end
  34. 12 def_delegator :@buffer, :<<
  35. end
  36. 30 def full?
  37. 65604 @buffer.bytesize >= @limit
  38. end
  39. 30 def capacity
  40. 14 @limit - @buffer.bytesize
  41. end
  42. 30 def shift!(fin)
  43. 23425 @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. 30 module HTTPX
  3. 30 module Callbacks
  4. 30 def on(type, &action)
  5. 345337 callbacks(type) << action
  6. 345337 action
  7. end
  8. 30 def once(type, &block)
  9. 210503 on(type) do |*args, &callback|
  10. 109101 block.call(*args, &callback)
  11. 109029 :delete
  12. end
  13. end
  14. 30 def emit(type, *args)
  15. 135908 log { "emit #{type.inspect} callbacks" } if respond_to?(:log)
  16. 274365 callbacks(type).delete_if { |pr| :delete == pr.call(*args) } # rubocop:disable Style/YodaCondition
  17. end
  18. 30 def callbacks_for?(type)
  19. 3911 @callbacks && @callbacks.key?(type) && @callbacks[type].any?
  20. end
  21. 30 protected
  22. 30 def callbacks(type = nil)
  23. 485483 return @callbacks unless type
  24. 694403 @callbacks ||= Hash.new { |h, k| h[k] = [] }
  25. 485385 @callbacks[type]
  26. end
  27. end
  28. end

lib/httpx/chainable.rb

95.65% lines covered

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

lib/httpx/connection.rb

95.38% lines covered

476 relevant lines. 454 lines covered and 22 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "resolv"
  3. 30 require "forwardable"
  4. 30 require "httpx/io"
  5. 30 require "httpx/buffer"
  6. 30 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. 30 class Connection
  29. 30 extend Forwardable
  30. 30 include Loggable
  31. 30 include Callbacks
  32. 30 using URIExtensions
  33. 30 def_delegator :@write_buffer, :empty?
  34. 30 attr_reader :type, :io, :origin, :origins, :state, :pending, :options, :ssl_session, :sibling
  35. 30 attr_writer :current_selector
  36. 30 attr_accessor :current_session, :family
  37. 30 protected :ssl_session, :sibling
  38. 30 def initialize(uri, options)
  39. 1719 @current_session = @current_selector =
  40. @parser = @sibling = @coalesced_connection = @altsvc_connection =
  41. @family = @io = @ssl_session = @timeout =
  42. 7428 @connected_at = @response_received_at = nil
  43. 9147 @exhausted = @cloned = @main_sibling = false
  44. 9147 @options = Options.new(options)
  45. 9147 @type = initialize_type(uri, @options)
  46. 9147 @origins = [uri.origin]
  47. 9147 @origin = Utils.to_uri(uri.origin)
  48. 9147 @window_size = @options.window_size
  49. 9147 @read_buffer = Buffer.new(@options.buffer_size)
  50. 9147 @write_buffer = Buffer.new(@options.buffer_size)
  51. 9147 @pending = []
  52. 9147 @inflight = 0
  53. 9147 @keep_alive_timeout = @options.timeout[:keep_alive_timeout]
  54. 9147 if @options.io
  55. # if there's an already open IO, get its
  56. # peer address, and force-initiate the parser
  57. 75 transition(:already_open)
  58. 75 @io = build_socket
  59. 75 parser
  60. else
  61. 9072 transition(:idle)
  62. end
  63. 9147 self.addresses = @options.addresses if @options.addresses
  64. end
  65. 30 def peer
  66. 19306 @origin
  67. end
  68. # this is a semi-private method, to be used by the resolver
  69. # to initiate the io object.
  70. 30 def addresses=(addrs)
  71. 8757 if @io
  72. 398 @io.add_addresses(addrs)
  73. else
  74. 8359 @io = build_socket(addrs)
  75. end
  76. end
  77. 30 def addresses
  78. 17459 @io && @io.addresses
  79. end
  80. 30 def addresses?
  81. 9916 @io && @io.addresses?
  82. end
  83. 30 def match?(uri, options)
  84. 2606 return false if !used? && (@state == :closing || @state == :closed)
  85. 2438 @origins.include?(uri.origin) &&
  86. # if there is more than one origin to match, it means that this connection
  87. # was the result of coalescing. To prevent blind trust in the case where the
  88. # origin came from an ORIGIN frame, we're going to verify the hostname with the
  89. # SSL certificate
  90. 2287 (@origins.size == 1 || @origin == uri.origin || (@io.is_a?(SSL) && @io.verify_hostname(uri.host))) &&
  91. @options == options
  92. end
  93. 30 def mergeable?(connection)
  94. 492 return false if @state == :closing || @state == :closed || !@io
  95. 128 return false unless connection.addresses
  96. 2 (
  97. 128 (open? && @origin == connection.origin) ||
  98. 128 !(@io.addresses & (connection.addresses || [])).empty?
  99. ) && @options == connection.options
  100. end
  101. # coalesces +self+ into +connection+.
  102. 30 def coalesce!(connection)
  103. 29 @coalesced_connection = connection
  104. 29 close_sibling
  105. 29 connection.merge(self)
  106. end
  107. 30 def coalesced?
  108. 10096 @coalesced_connection
  109. end
  110. # coalescable connections need to be mergeable!
  111. # but internally, #mergeable? is called before #coalescable?
  112. 30 def coalescable?(connection)
  113. 55 if @io.protocol == "h2" &&
  114. @origin.scheme == "https" &&
  115. connection.origin.scheme == "https" &&
  116. @io.can_verify_peer?
  117. 29 @io.verify_hostname(connection.origin.host)
  118. else
  119. 26 @origin == connection.origin
  120. end
  121. end
  122. 30 def merge(connection)
  123. 71 @origins |= connection.instance_variable_get(:@origins)
  124. 74 if @ssl_session.nil? && connection.ssl_session
  125. 16 @ssl_session = connection.ssl_session
  126. 2 @io.session_new_cb do |sess|
  127. 24 @ssl_session = sess
  128. 16 end if @io
  129. end
  130. 74 connection.purge_pending do |req|
  131. 25 send(req)
  132. end
  133. end
  134. 30 def purge_pending(&block)
  135. 74 pendings = []
  136. 74 if @parser
  137. 24 @inflight -= @parser.pending.size
  138. 27 pendings << @parser.pending
  139. end
  140. 74 pendings << @pending
  141. 74 pendings.each do |pending|
  142. 101 pending.reject!(&block)
  143. end
  144. end
  145. 30 def io_connected?
  146. 24 return @coalesced_connection.io_connected? if @coalesced_connection
  147. 24 @io && @io.state == :connected
  148. end
  149. 30 def connecting?
  150. 211500 @state == :idle
  151. end
  152. 30 def inflight?
  153. 3603 @parser && (
  154. # parser may be dealing with other requests (possibly started from a different fiber)
  155. 3040 !@parser.empty? ||
  156. # connection may be doing connection termination handshake
  157. !@write_buffer.empty?
  158. )
  159. end
  160. 30 def interests
  161. # connecting
  162. 174285 if connecting?
  163. 14125 connect
  164. 14125 return @io.interests if connecting?
  165. end
  166. 160911 return @parser.interests if @parser
  167. 34 nil
  168. rescue StandardError => e
  169. on_error(e)
  170. nil
  171. end
  172. 30 def to_io
  173. 32234 @io.to_io
  174. end
  175. 30 def call
  176. 28174 case @state
  177. when :idle
  178. 13092 connect
  179. # when opening the tcp or ssl socket fails
  180. 13074 return if @state == :closed
  181. 13046 consume
  182. when :closed
  183. return
  184. when :closing
  185. consume
  186. transition(:closed)
  187. when :open
  188. 16972 consume
  189. end
  190. 13532 nil
  191. rescue StandardError => e
  192. 19 @write_buffer.clear
  193. 19 on_error(e)
  194. rescue Exception => e # rubocop:disable Lint/RescueException
  195. 117 force_close(true)
  196. 108 raise e
  197. end
  198. 30 def close
  199. 3329 transition(:active) if @state == :inactive
  200. 3329 @parser.close if @parser
  201. end
  202. 30 def terminate
  203. 2945 case @state
  204. when :idle
  205. purge_after_closed
  206. disconnect
  207. when :closed
  208. 18 @connected_at = nil
  209. end
  210. 3283 close
  211. end
  212. # bypasses state machine rules while setting the connection in the
  213. # :closed state.
  214. 30 def force_close(delete_pending = false)
  215. 457 if delete_pending
  216. 285 @pending.clear
  217. 172 elsif (parser = @parser)
  218. enqueue_pending_requests_from_parser(parser)
  219. end
  220. 457 return if @state == :closed
  221. 307 @state = :closed
  222. 307 @write_buffer.clear
  223. 307 purge_after_closed
  224. 307 disconnect
  225. 298 emit(:force_closed, delete_pending)
  226. end
  227. # bypasses the state machine to force closing of connections still connecting.
  228. # **only** used for Happy Eyeballs v2.
  229. 30 def force_reset(cloned = false)
  230. 251 @state = :closing
  231. 251 @cloned = cloned
  232. 251 transition(:closed)
  233. end
  234. 30 def reset
  235. 9430 return if @state == :closing || @state == :closed
  236. 9378 transition(:closing)
  237. 9378 transition(:closed)
  238. end
  239. 30 def send(request)
  240. 10997 return @coalesced_connection.send(request) if @coalesced_connection
  241. 10976 if @parser && !@write_buffer.full?
  242. 527 if @response_received_at && @keep_alive_timeout &&
  243. Utils.elapsed_time(@response_received_at) > @keep_alive_timeout
  244. # when pushing a request into an existing connection, we have to check whether there
  245. # is the possibility that the connection might have extended the keep alive timeout.
  246. # for such cases, we want to ping for availability before deciding to shovel requests.
  247. 22 log(level: 3) { "keep alive timeout expired, pinging connection..." }
  248. 22 @pending << request
  249. 22 transition(:active) if @state == :inactive
  250. 22 parser.ping
  251. 22 request.ping!
  252. 20 return
  253. end
  254. 505 send_request_to_parser(request)
  255. else
  256. 10449 @pending << request
  257. end
  258. end
  259. 30 def timeout
  260. 31896 return if @state == :closed || @state == :inactive
  261. 31896 return @timeout if @timeout
  262. 12202 return @options.timeout[:connect_timeout] if @state == :idle
  263. 12202 @options.timeout[:operation_timeout]
  264. end
  265. 30 def idling
  266. 1089 purge_after_closed
  267. 1089 @write_buffer.clear
  268. 1089 transition(:idle)
  269. 1089 @parser = nil if @parser
  270. end
  271. 30 def used?
  272. 2871 @connected_at
  273. end
  274. 30 def deactivate
  275. 527 transition(:inactive)
  276. end
  277. 30 def open?
  278. 8899 @state == :open || @state == :inactive
  279. end
  280. 30 def handle_socket_timeout(interval)
  281. 54 error = OperationTimeoutError.new(interval, "timed out while waiting on select")
  282. 54 error.set_backtrace(caller)
  283. 54 on_error(error)
  284. end
  285. 30 def sibling=(connection)
  286. 132 @sibling = connection
  287. 132 return unless connection
  288. 104 @main_sibling = connection.sibling.nil?
  289. 104 return unless @main_sibling
  290. 52 connection.sibling = self
  291. end
  292. 30 def handle_connect_error(error)
  293. 404 return on_error(error) unless @sibling && @sibling.connecting?
  294. 14 @sibling.merge(self)
  295. 14 force_reset(true)
  296. end
  297. # disconnects from the current session it's attached to
  298. 30 def disconnect
  299. 13531 return if @exhausted # it'll reset
  300. 13522 return unless (current_session = @current_session) && (current_selector = @current_selector)
  301. 10177 @current_session = @current_selector = nil
  302. 10177 current_session.deselect_connection(self, current_selector, @cloned)
  303. end
  304. 30 def on_error(error, request = nil)
  305. 1199 if error.is_a?(OperationTimeoutError)
  306. # inactive connections do not contribute to the select loop, therefore
  307. # they should not fail due to such errors.
  308. 54 return if @state == :inactive
  309. 54 if @timeout
  310. 43 @timeout -= error.timeout
  311. 47 return unless @timeout <= 0
  312. end
  313. 48 error = error.to_connection_error if connecting?
  314. end
  315. 1193 handle_error(error, request)
  316. 1175 reset
  317. end
  318. skipped # :nocov:
  319. skipped def inspect
  320. skipped "#<#{self.class}:#{object_id} " \
  321. skipped "@origin=#{@origin} " \
  322. skipped "@state=#{@state} " \
  323. skipped "@pending=#{@pending.size} " \
  324. skipped "@io=#{@io}>"
  325. skipped end
  326. skipped # :nocov:
  327. 30 private
  328. 30 def connect
  329. 25998 transition(:open)
  330. end
  331. 30 def consume
  332. 33951 return unless @io
  333. 33951 catch(:called) do
  334. 33951 epiped = false
  335. 33951 loop do
  336. # connection may have
  337. 51300 return if @state == :idle
  338. 47067 parser.consume
  339. # we exit if there's no more requests to process
  340. #
  341. # this condition takes into account:
  342. #
  343. # * the number of inflight requests
  344. # * the number of pending requests
  345. # * whether the write buffer has bytes (i.e. for close handshake)
  346. 47049 if @pending.empty? && @inflight.zero? && @write_buffer.empty?
  347. 3400 log(level: 3) { "NO MORE REQUESTS..." } if @parser && @parser.pending.any?
  348. # terminate if an altsvc connection has been established
  349. 3400 terminate if @altsvc_connection
  350. 3400 return
  351. end
  352. 43649 @timeout = @current_timeout
  353. 43649 read_drained = false
  354. 43649 write_drained = nil
  355. #
  356. # tight read loop.
  357. #
  358. # read as much of the socket as possible.
  359. #
  360. # this tight loop reads all the data it can from the socket and pipes it to
  361. # its parser.
  362. #
  363. 11539 loop do
  364. 66739 siz = @io.read(@window_size, @read_buffer)
  365. 66937 log(level: 3, color: :cyan) { "IO READ: #{siz} bytes... (wsize: #{@window_size}, rbuffer: #{@read_buffer.bytesize})" }
  366. 66737 unless siz
  367. 18 @write_buffer.clear
  368. 18 ex = EOFError.new("descriptor closed")
  369. 18 ex.set_backtrace(caller)
  370. 18 on_error(ex)
  371. 18 return
  372. end
  373. # socket has been drained. mark and exit the read loop.
  374. 66719 if siz.zero?
  375. 16502 read_drained = @read_buffer.empty?
  376. 16502 epiped = false
  377. 16502 break
  378. end
  379. 50217 parser << @read_buffer.to_s
  380. # continue reading if possible.
  381. 44946 break if interests == :w && !epiped
  382. # exit the read loop if connection is preparing to be closed
  383. 39244 break if @state == :closing || @state == :closed
  384. # exit #consume altogether if all outstanding requests have been dealt with
  385. 39133 if @pending.empty? && @inflight.zero? && @write_buffer.empty? # rubocop:disable Style/Next
  386. 3738 log(level: 3) { "NO MORE REQUESTS..." } if @parser && @parser.pending.any?
  387. # terminate if an altsvc connection has been established
  388. 3738 terminate if @altsvc_connection
  389. 3738 return
  390. end
  391. 43649 end unless ((ints = interests).nil? || ints == :w || @state == :closing) && !epiped
  392. #
  393. # tight write loop.
  394. #
  395. # flush as many bytes as the sockets allow.
  396. #
  397. 8189 loop do
  398. # buffer has been drainned, mark and exit the write loop.
  399. 25923 if @write_buffer.empty?
  400. # we only mark as drained on the first loop
  401. 3328 write_drained = write_drained.nil? && @inflight.positive?
  402. 3328 break
  403. end
  404. 2203 begin
  405. 22595 siz = @io.write(@write_buffer)
  406. rescue Errno::EPIPE
  407. # this can happen if we still have bytes in the buffer to send to the server, but
  408. # the server wants to respond immediately with some message, or an error. An example is
  409. # when one's uploading a big file to an unintended endpoint, and the server stops the
  410. # consumption, and responds immediately with an authorization of even method not allowed error.
  411. # at this point, we have to let the connection switch to read-mode.
  412. 8 log(level: 2) { "pipe broken, could not flush buffer..." }
  413. 8 epiped = true
  414. 8 read_drained = false
  415. 8 break
  416. end
  417. 22695 log(level: 3, color: :cyan) { "IO WRITE: #{siz} bytes..." }
  418. 22586 unless siz
  419. @write_buffer.clear
  420. ex = EOFError.new("descriptor closed")
  421. ex.set_backtrace(caller)
  422. on_error(ex)
  423. return
  424. end
  425. # socket closed for writing. mark and exit the write loop.
  426. 22586 if siz.zero?
  427. 18 write_drained = !@write_buffer.empty?
  428. 18 break
  429. end
  430. # exit write loop if marked to consume from peer, or is closing.
  431. 22568 break if interests == :r || @state == :closing || @state == :closed
  432. 3681 write_drained = false
  433. 34620 end unless (ints = interests) == :r
  434. 34619 send_pending if @state == :open
  435. # return if socket is drained
  436. 34619 next unless (ints != :r || read_drained) && (ints != :w || write_drained)
  437. # gotta go back to the event loop. It happens when:
  438. #
  439. # * the socket is drained of bytes or it's not the interest of the conn to read;
  440. # * theres nothing more to write, or it's not in the interest of the conn to write;
  441. 17351 log(level: 3) { "(#{ints}): WAITING FOR EVENTS..." }
  442. 17270 return
  443. end
  444. end
  445. end
  446. 30 def send_pending
  447. 91342 while !@write_buffer.full? && (request = @pending.shift)
  448. 20414 send_request_to_parser(request)
  449. end
  450. end
  451. 30 def parser
  452. 128053 @parser ||= build_parser
  453. end
  454. 30 def send_request_to_parser(request)
  455. 19930 @inflight += 1
  456. 20919 request.peer_address = @io.ip && @io.ip.address
  457. 20919 set_request_timeouts(request)
  458. 20919 parser.send(request)
  459. 20919 return unless @state == :inactive
  460. 32 transition(:active)
  461. # mark request as ping, as this inactive connection may have been
  462. # closed by the server, and we don't want that to influence retry
  463. # bookkeeping.
  464. 32 request.ping!
  465. end
  466. 30 def enqueue_pending_requests_from_parser(parser)
  467. 4834 parser_pending_requests = parser.pending
  468. 4834 return if parser_pending_requests.empty?
  469. # the connection will be reused, so parser requests must come
  470. # back to the pending list before the parser is reset.
  471. 218 @inflight -= parser_pending_requests.size
  472. 230 @pending.unshift(*parser_pending_requests)
  473. end
  474. 30 def build_parser(protocol = @io.protocol)
  475. 9054 parser = parser_type(protocol).new(@write_buffer, @options)
  476. 9054 set_parser_callbacks(parser)
  477. 9054 parser
  478. end
  479. 30 def set_parser_callbacks(parser)
  480. 9178 parser.on(:response) do |request, response|
  481. 9484 AltSvc.emit(request, response) do |alt_origin, origin, alt_params|
  482. 18 build_altsvc_connection(alt_origin, origin, alt_params)
  483. end
  484. 9484 @response_received_at = Utils.now
  485. 8590 @inflight -= 1
  486. 9484 response.finish!
  487. 9484 request.emit(:response, response)
  488. end
  489. 9178 parser.on(:altsvc) do |alt_origin, origin, alt_params|
  490. build_altsvc_connection(alt_origin, origin, alt_params)
  491. end
  492. 9178 parser.on(:pong, &method(:send_pending))
  493. 9178 parser.on(:promise) do |request, stream|
  494. 27 request.emit(:promise, parser, stream)
  495. end
  496. 9178 parser.on(:exhausted) do
  497. 9 enqueue_pending_requests_from_parser(parser)
  498. 9 @exhausted = true
  499. 9 parser.close
  500. 9 idling
  501. 9 @exhausted = false
  502. end
  503. 9178 parser.on(:origin) do |origin|
  504. @origins |= [origin]
  505. end
  506. 9178 parser.on(:close) do
  507. 3403 reset
  508. 3394 disconnect
  509. end
  510. 9178 parser.on(:close_handshake) do
  511. 21 consume unless @state == :closed
  512. end
  513. 9178 parser.on(:reset) do
  514. 4816 enqueue_pending_requests_from_parser(parser)
  515. 4816 reset
  516. # :reset event only fired in http/1.1, so this guarantees
  517. # that the connection will be closed here.
  518. 4807 idling unless @pending.empty?
  519. end
  520. 9178 parser.on(:current_timeout) do
  521. 3935 @current_timeout = @timeout = parser.timeout
  522. end
  523. 9178 parser.on(:timeout) do |tout|
  524. 3320 @timeout = tout
  525. end
  526. 9178 parser.on(:error) do |request, error|
  527. 96 case error
  528. when :http_1_1_required
  529. 18 current_session = @current_session
  530. 18 current_selector = @current_selector
  531. 18 parser.close
  532. 18 other_connection = current_session.find_connection(@origin, current_selector,
  533. @options.merge(ssl: { alpn_protocols: %w[http/1.1] }))
  534. 18 other_connection.merge(self)
  535. 18 request.transition(:idle)
  536. 18 other_connection.send(request)
  537. 18 next
  538. when OperationTimeoutError
  539. # request level timeouts should take precedence
  540. next unless request.active_timeouts.empty?
  541. end
  542. 80 @inflight -= 1
  543. 87 response = ErrorResponse.new(request, error)
  544. 87 request.response = response
  545. 87 request.emit(:response, response)
  546. end
  547. end
  548. 30 def transition(nextstate)
  549. 57742 handle_transition(nextstate)
  550. rescue Errno::ECONNABORTED,
  551. Errno::ECONNREFUSED,
  552. Errno::ECONNRESET,
  553. Errno::EADDRNOTAVAIL,
  554. Errno::EHOSTUNREACH,
  555. Errno::EINVAL,
  556. Errno::ENETUNREACH,
  557. Errno::EPIPE,
  558. Errno::ENOENT,
  559. SocketError,
  560. IOError => e
  561. # connect errors, exit gracefully
  562. 95 error = ConnectionError.new(e.message)
  563. 95 error.set_backtrace(e.backtrace)
  564. 95 handle_connect_error(error) if connecting?
  565. 95 force_close
  566. rescue TLSError, ::HTTP2::Error::ProtocolError, ::HTTP2::Error::HandshakeError => e
  567. # connect errors, exit gracefully
  568. 27 handle_error(e)
  569. 27 handle_connect_error(e) if connecting?
  570. 27 force_close
  571. end
  572. 30 def handle_transition(nextstate)
  573. 51996 case nextstate
  574. when :idle
  575. 10169 @timeout = @current_timeout = @options.timeout[:connect_timeout]
  576. 10169 @connected_at = @response_received_at = nil
  577. when :open
  578. 26399 return if @state == :closed
  579. 26399 @io.connect
  580. 26277 close_sibling if @io.state == :connected
  581. 26277 return unless @io.connected?
  582. 9085 @connected_at = Utils.now
  583. 9085 send_pending
  584. 9085 @timeout = @current_timeout = parser.timeout
  585. 9085 emit(:open)
  586. when :inactive
  587. 527 return unless @state == :open
  588. # do not deactivate connection in use
  589. 495 return if @inflight.positive? || @parser.waiting_for_ping?
  590. 492 disconnect
  591. when :closing
  592. 9378 return unless connecting? || @state == :open
  593. 9378 unless @write_buffer.empty?
  594. # preset state before handshake, as error callbacks
  595. # may take it back here.
  596. 3330 @state = nextstate
  597. # handshakes, try sending
  598. 3330 consume
  599. 3330 @write_buffer.clear
  600. 3330 return
  601. end
  602. when :closed
  603. 9629 return unless @state == :closing
  604. 9629 return unless @write_buffer.empty?
  605. 9629 purge_after_closed
  606. 9629 disconnect if @pending.empty?
  607. when :already_open
  608. 75 nextstate = :open
  609. # the first check for given io readiness must still use a timeout.
  610. # connect is the reasonable choice in such a case.
  611. 75 @timeout = @options.timeout[:connect_timeout]
  612. 75 send_pending
  613. when :active
  614. 292 return unless @state == :inactive
  615. 292 nextstate = :open
  616. # activate
  617. 292 @current_session.select_connection(self, @current_selector)
  618. end
  619. 36726 log(level: 3) { "#{@state} -> #{nextstate}" }
  620. 36444 @state = nextstate
  621. end
  622. 30 def close_sibling
  623. 12283 return unless @sibling
  624. 24 if @sibling.io_connected?
  625. reset
  626. # TODO: transition connection to closed
  627. end
  628. 24 unless @sibling.state == :closed
  629. 10 merge(@sibling) unless @main_sibling
  630. 10 @sibling.force_reset(true)
  631. end
  632. 24 @sibling = nil
  633. end
  634. 30 def purge_after_closed
  635. 11033 @io.close if @io
  636. 11033 @read_buffer.clear
  637. 11033 @timeout = nil
  638. end
  639. 30 def initialize_type(uri, options)
  640. 8727 options.transport || begin
  641. 7878 case uri.scheme
  642. when "http"
  643. 4911 "tcp"
  644. when "https"
  645. 3784 "ssl"
  646. else
  647. raise UnsupportedSchemeError, "#{uri}: #{uri.scheme}: unsupported URI scheme"
  648. end
  649. end
  650. end
  651. # returns an HTTPX::Connection for the negotiated Alternative Service (or none).
  652. 30 def build_altsvc_connection(alt_origin, origin, alt_params)
  653. 18 return if @altsvc_connection
  654. # do not allow security downgrades on altsvc negotiation
  655. 9 return if @origin.scheme == "https" && alt_origin.scheme != "https"
  656. 9 altsvc = AltSvc.cached_altsvc_set(origin, alt_params.merge("origin" => alt_origin))
  657. # altsvc already exists, somehow it wasn't advertised, probably noop
  658. 9 return unless altsvc
  659. 9 alt_options = @options.merge(ssl: @options.ssl.merge(hostname: URI(origin).host))
  660. 9 connection = @current_session.find_connection(alt_origin, @current_selector, alt_options)
  661. # advertised altsvc is the same origin being used, ignore
  662. 9 return if connection == self
  663. 9 connection.extend(AltSvc::ConnectionMixin) unless connection.is_a?(AltSvc::ConnectionMixin)
  664. 9 @altsvc_connection = connection
  665. 9 log(level: 1) { "#{origin}: alt-svc connection##{connection.object_id} established to #{alt_origin}" }
  666. 9 connection.merge(self)
  667. rescue UnsupportedSchemeError
  668. altsvc["noop"] = true
  669. nil
  670. end
  671. 30 def build_socket(addrs = nil)
  672. 7589 case @type
  673. when "tcp"
  674. 4850 TCP.new(peer, addrs, @options)
  675. when "ssl"
  676. 3552 SSL.new(peer, addrs, @options) do |sock|
  677. 3527 sock.ssl_session = @ssl_session
  678. 3527 sock.session_new_cb do |sess|
  679. 6255 @ssl_session = sess
  680. 6255 sock.ssl_session = sess
  681. end
  682. end
  683. when "unix"
  684. 32 path = Array(addrs).first
  685. 32 path = String(path) if path
  686. 32 UNIX.new(peer, path, @options)
  687. else
  688. raise Error, "unsupported transport (#{@type})"
  689. end
  690. end
  691. 30 def handle_error(error, request = nil)
  692. 1220 parser.handle_error(error, request) if @parser && @parser.respond_to?(:handle_error)
  693. 2731 while (req = @pending.shift)
  694. 561 next if request && req == request
  695. 561 response = ErrorResponse.new(req, error)
  696. 561 req.response = response
  697. 543 req.emit(:response, response)
  698. end
  699. 1202 return unless request
  700. 504 @inflight -= 1
  701. 567 response = ErrorResponse.new(request, error)
  702. 567 request.response = response
  703. 567 request.emit(:response, response)
  704. end
  705. 30 def set_request_timeouts(request)
  706. 20919 set_request_write_timeout(request)
  707. 20919 set_request_read_timeout(request)
  708. 20919 set_request_request_timeout(request)
  709. end
  710. 30 def set_request_read_timeout(request)
  711. 20919 read_timeout = request.read_timeout
  712. 20919 return if read_timeout.nil? || read_timeout.infinite?
  713. 20510 set_request_timeout(:read_timeout, request, read_timeout, :done, :response) do
  714. 18 read_timeout_callback(request, read_timeout)
  715. end
  716. end
  717. 30 def set_request_write_timeout(request)
  718. 20919 write_timeout = request.write_timeout
  719. 20919 return if write_timeout.nil? || write_timeout.infinite?
  720. 20919 set_request_timeout(:write_timeout, request, write_timeout, :headers, %i[done response]) do
  721. 18 write_timeout_callback(request, write_timeout)
  722. end
  723. end
  724. 30 def set_request_request_timeout(request)
  725. 20600 request_timeout = request.request_timeout
  726. 20600 return if request_timeout.nil? || request_timeout.infinite?
  727. 732 set_request_timeout(:request_timeout, request, request_timeout, :headers, :complete) do
  728. 531 read_timeout_callback(request, request_timeout, RequestTimeoutError)
  729. end
  730. end
  731. 30 def write_timeout_callback(request, write_timeout)
  732. 18 return if request.state == :done
  733. 18 @write_buffer.clear
  734. 18 error = WriteTimeoutError.new(request, nil, write_timeout)
  735. 18 on_error(error, request)
  736. end
  737. 30 def read_timeout_callback(request, read_timeout, error_type = ReadTimeoutError)
  738. 549 response = request.response
  739. 549 return if response && response.finished?
  740. 549 @write_buffer.clear
  741. 549 error = error_type.new(request, request.response, read_timeout)
  742. 549 on_error(error, request)
  743. end
  744. 30 def set_request_timeout(label, request, timeout, start_event, finish_events, &callback)
  745. 42235 request.set_timeout_callback(start_event) do
  746. 41975 unless @current_selector
  747. raise Error, "request has been resend to an out-of-session connection, and this " \
  748. "should never happen!!! Please report this error! " \
  749. "(state:#{@state}, " \
  750. "parser?:#{!!@parser}, " \
  751. "bytes in write buffer?:#{!@write_buffer.empty?}, " \
  752. "cloned?:#{@cloned}, " \
  753. "sibling?:#{!!@sibling}, " \
  754. "coalesced?:#{coalesced?})"
  755. end
  756. 41975 timer = @current_selector.after(timeout, callback)
  757. 41975 request.active_timeouts << label
  758. 41975 Array(finish_events).each do |event|
  759. # clean up request timeouts if the connection errors out
  760. 62848 request.set_timeout_callback(event) do
  761. 62088 timer.cancel
  762. 62088 request.active_timeouts.delete(label)
  763. end
  764. end
  765. end
  766. end
  767. 30 def parser_type(protocol)
  768. 8304 case protocol
  769. 3957 when "h2" then @options.http2_class
  770. 5275 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. 30 require "httpx/parser/http1"
  3. 30 module HTTPX
  4. 30 class Connection::HTTP1
  5. 30 include Callbacks
  6. 30 include Loggable
  7. 30 MAX_REQUESTS = 200
  8. 30 CRLF = "\r\n"
  9. 30 UPCASED = {
  10. "www-authenticate" => "WWW-Authenticate",
  11. "http2-settings" => "HTTP2-Settings",
  12. "content-md5" => "Content-MD5",
  13. }.freeze
  14. 30 attr_reader :pending, :requests
  15. 30 attr_accessor :max_concurrent_requests
  16. 30 def initialize(buffer, options)
  17. 5284 @options = options
  18. 5284 @max_concurrent_requests = @options.max_concurrent_requests || MAX_REQUESTS
  19. 5284 @max_requests = @options.max_requests
  20. 5284 @parser = Parser::HTTP1.new(self)
  21. 5284 @buffer = buffer
  22. 5284 @version = [1, 1]
  23. 5284 @pending = []
  24. 5284 @requests = []
  25. 5284 @handshake_completed = false
  26. end
  27. 30 def timeout
  28. 5145 @options.timeout[:operation_timeout]
  29. end
  30. 30 def interests
  31. 50029 request = @request || @requests.first
  32. 50029 return unless request
  33. 50023 return :w if request.interests == :w || !@buffer.empty?
  34. 32740 :r
  35. end
  36. 30 def reset
  37. 4967 @max_requests = @options.max_requests || MAX_REQUESTS
  38. 4967 @parser.reset!
  39. 4967 @handshake_completed = false
  40. 4967 @pending.unshift(*@requests)
  41. end
  42. 30 def close
  43. 98 reset
  44. 98 emit(:close)
  45. end
  46. 30 def exhausted?
  47. 534 !@max_requests.positive?
  48. end
  49. 30 def empty?
  50. # this means that for every request there's an available
  51. # partial response, so there are no in-flight requests waiting.
  52. 45 @requests.empty? || (
  53. # checking all responses can be time-consuming. Alas, as in HTTP/1, responses
  54. # do not come out of order, we can get away with checking first and last.
  55. 8 !@requests.first.response.nil? &&
  56. (@requests.size == 1 || !@requests.last.response.nil?)
  57. )
  58. end
  59. 30 def <<(data)
  60. 8322 @parser << data
  61. end
  62. 30 def send(request)
  63. 16462 unless @max_requests.positive?
  64. @pending << request
  65. return
  66. end
  67. 16462 return if @requests.include?(request)
  68. 16462 @requests << request
  69. 16462 @pipelining = true if @requests.size > 1
  70. end
  71. 30 def consume
  72. 19117 requests_limit = [@max_requests, @requests.size].min
  73. 19117 concurrent_requests_limit = [@max_concurrent_requests, requests_limit].min
  74. 19117 @requests.each_with_index do |request, idx|
  75. 22368 break if idx >= concurrent_requests_limit
  76. 19730 next unless request.can_buffer?
  77. 7303 handle(request)
  78. end
  79. end
  80. # HTTP Parser callbacks
  81. #
  82. # must be public methods, or else they won't be reachable
  83. 30 def on_start
  84. 5637 log(level: 2) { "parsing begins" }
  85. end
  86. 30 def on_headers(h)
  87. 5583 @request = @requests.first
  88. 5583 return if @request.response
  89. 5637 log(level: 2) { "headers received" }
  90. 5583 headers = @request.options.headers_class.new(h)
  91. 5583 response = @request.options.response_class.new(@request,
  92. @parser.status_code,
  93. @parser.http_version.join("."),
  94. headers)
  95. 5637 log(color: :yellow) { "-> HEADLINE: #{response.status} HTTP/#{@parser.http_version.join(".")}" }
  96. 6069 log(color: :yellow) { response.headers.each.map { |f, v| "-> HEADER: #{f}: #{log_redact_headers(v)}" }.join("\n") }
  97. 5583 @request.response = response
  98. 5574 on_complete if response.finished?
  99. end
  100. 30 def on_trailers(h)
  101. 9 return unless @request
  102. 9 response = @request.response
  103. 9 log(level: 2) { "trailer headers received" }
  104. 9 log(color: :yellow) { h.each.map { |f, v| "-> HEADER: #{f}: #{log_redact_headers(v.join(", "))}" }.join("\n") }
  105. 9 response.merge_headers(h)
  106. end
  107. 30 def on_data(chunk)
  108. 6537 request = @request
  109. 6537 return unless request
  110. 6592 log(color: :green) { "-> DATA: #{chunk.bytesize} bytes..." }
  111. 6592 log(level: 2, color: :green) { "-> #{log_redact_body(chunk.inspect)}" }
  112. 6537 response = request.response
  113. 6537 response << chunk
  114. rescue StandardError => e
  115. 16 error_response = ErrorResponse.new(request, e)
  116. 16 request.response = error_response
  117. 16 dispatch
  118. end
  119. 30 def on_complete
  120. 5540 request = @request
  121. 5540 return unless request
  122. 5594 log(level: 2) { "parsing complete" }
  123. 5540 dispatch
  124. end
  125. 30 def dispatch
  126. 5556 request = @request
  127. 5556 if request.expects?
  128. 73 @parser.reset!
  129. 65 return handle(request)
  130. end
  131. 5483 @request = nil
  132. 5483 @requests.shift
  133. 5483 response = request.response
  134. 5483 emit(:response, request, response)
  135. 5403 if @parser.upgrade?
  136. 35 response << @parser.upgrade_data
  137. 35 throw(:called)
  138. end
  139. 5368 @parser.reset!
  140. 4872 @max_requests -= 1
  141. 5368 if response.is_a?(ErrorResponse)
  142. 16 disable
  143. else
  144. 5352 manage_connection(request, response)
  145. end
  146. 534 if exhausted?
  147. @pending.unshift(*@requests)
  148. @requests.clear
  149. emit(:exhausted)
  150. else
  151. 534 send(@pending.shift) unless @pending.empty?
  152. end
  153. end
  154. 30 def handle_error(ex, request = nil)
  155. 288 if (ex.is_a?(EOFError) || ex.is_a?(TimeoutError)) && @request && @request.response &&
  156. !@request.response.headers.key?("content-length") &&
  157. !@request.response.headers.key?("transfer-encoding")
  158. # if the response does not contain a content-length header, the server closing the
  159. # connnection is the indicator of response consumed.
  160. # https://greenbytes.de/tech/webdav/rfc2616.html#rfc.section.4.4
  161. 36 catch(:called) { on_complete }
  162. 16 return
  163. end
  164. 270 if @pipelining
  165. catch(:called) { disable }
  166. else
  167. 270 @requests.each do |req|
  168. 261 next if request && request == req
  169. emit(:error, req, ex)
  170. end
  171. 270 @pending.each do |req|
  172. next if request && request == req
  173. emit(:error, req, ex)
  174. end
  175. end
  176. end
  177. 30 def ping
  178. reset
  179. emit(:reset)
  180. emit(:exhausted)
  181. end
  182. 30 def waiting_for_ping?
  183. 20 false
  184. end
  185. 30 private
  186. 30 def manage_connection(request, response)
  187. 5352 connection = response.headers["connection"]
  188. 4857 case connection
  189. when /keep-alive/i
  190. 525 if @handshake_completed
  191. if @max_requests.zero?
  192. @pending.unshift(*@requests)
  193. @requests.clear
  194. emit(:exhausted)
  195. end
  196. return
  197. end
  198. 525 keep_alive = response.headers["keep-alive"]
  199. 525 return unless keep_alive
  200. 109 parameters = Hash[keep_alive.split(/ *, */).map do |pair|
  201. 109 pair.split(/ *= */, 2)
  202. end]
  203. 109 @max_requests = parameters["max"].to_i - 1 if parameters.key?("max")
  204. 109 if parameters.key?("timeout")
  205. keep_alive_timeout = parameters["timeout"].to_i
  206. emit(:timeout, keep_alive_timeout)
  207. end
  208. 109 @handshake_completed = true
  209. when /close/i
  210. 4818 disable
  211. when nil
  212. # In HTTP/1.1, it's keep alive by default
  213. 9 return if response.version == "1.1" && request.headers["connection"] != "close"
  214. disable
  215. end
  216. end
  217. 30 def disable
  218. 4834 disable_pipelining
  219. 4834 reset
  220. 4834 emit(:reset)
  221. 4825 throw(:called)
  222. end
  223. 30 def disable_pipelining
  224. 4834 return if @requests.empty?
  225. # do not disable pipelining if already set to 1 request at a time
  226. 221 return if @max_concurrent_requests == 1
  227. 56 @requests.each do |r|
  228. 92 r.transition(:idle)
  229. # when we disable pipelining, we still want to try keep-alive.
  230. # only when keep-alive with one request fails, do we fallback to
  231. # connection: close.
  232. 92 r.headers["connection"] = "close" if @max_concurrent_requests == 1
  233. end
  234. # server doesn't handle pipelining, and probably
  235. # doesn't support keep-alive. Fallback to send only
  236. # 1 keep alive request.
  237. 56 @max_concurrent_requests = 1
  238. 56 @pipelining = false
  239. end
  240. 30 def set_protocol_headers(request)
  241. 5863 if !request.headers.key?("content-length") &&
  242. request.body.bytesize == Float::INFINITY
  243. 36 request.body.chunk!
  244. end
  245. 5863 extra_headers = {}
  246. 5863 unless request.headers.key?("connection")
  247. 5836 connection_value = if request.persistent?
  248. # when in a persistent connection, the request can't be at
  249. # the edge of a renegotiation
  250. 204 if @requests.index(request) + 1 < @max_requests
  251. 204 "keep-alive"
  252. else
  253. "close"
  254. end
  255. else
  256. # when it's not a persistent connection, it sets "Connection: close" always
  257. # on the last request of the possible batch (either allowed max requests,
  258. # or if smaller, the size of the batch itself)
  259. 5632 requests_limit = [@max_requests, @requests.size].min
  260. 5632 if request == @requests[requests_limit - 1]
  261. 5049 "close"
  262. else
  263. 583 "keep-alive"
  264. end
  265. end
  266. 5295 extra_headers["connection"] = connection_value
  267. end
  268. 5863 extra_headers["host"] = request.authority unless request.headers.key?("host")
  269. 5863 extra_headers
  270. end
  271. 30 def handle(request)
  272. 7376 catch(:buffer_full) do
  273. 7376 request.transition(:headers)
  274. 7367 join_headers(request) if request.state == :headers
  275. 7367 request.transition(:body)
  276. 7367 join_body(request) if request.state == :body
  277. 6066 request.transition(:trailers)
  278. # HTTP/1.1 trailers should only work for chunked encoding
  279. 6066 join_trailers(request) if request.body.chunked? && request.state == :trailers
  280. 6066 request.transition(:done)
  281. end
  282. end
  283. 30 def join_headline(request)
  284. 5239 "#{request.verb} #{request.path} HTTP/#{@version.join(".")}"
  285. end
  286. 30 def join_headers(request)
  287. 5863 headline = join_headline(request)
  288. 5863 @buffer << headline << CRLF
  289. 5917 log(color: :yellow) { "<- HEADLINE: #{headline.chomp.inspect}" }
  290. 5863 extra_headers = set_protocol_headers(request)
  291. 5863 join_headers2(request.headers.each(extra_headers))
  292. 5917 log { "<- " }
  293. 5863 @buffer << CRLF
  294. end
  295. 30 def join_body(request)
  296. 7146 return if request.body.empty?
  297. 7832 while (chunk = request.drain_body)
  298. 3838 log(color: :green) { "<- DATA: #{chunk.bytesize} bytes..." }
  299. 3838 log(level: 2, color: :green) { "<- #{log_redact_body(chunk.inspect)}" }
  300. 3838 @buffer << chunk
  301. 3838 throw(:buffer_full, request) if @buffer.full?
  302. end
  303. 1826 return unless (error = request.drain_error)
  304. raise error
  305. end
  306. 30 def join_trailers(request)
  307. 108 return unless request.trailers? && request.callbacks_for?(:trailers)
  308. 36 join_headers2(request.trailers)
  309. 36 log { "<- " }
  310. 36 @buffer << CRLF
  311. end
  312. 30 def join_headers2(headers)
  313. 5899 headers.each do |field, value|
  314. 36030 field = capitalized(field)
  315. 36300 log(color: :yellow) { "<- HEADER: #{[field, log_redact_headers(value)].join(": ")}" }
  316. 36030 @buffer << "#{field}: #{value}#{CRLF}"
  317. end
  318. end
  319. 30 def capitalized(field)
  320. 36030 UPCASED[field] || field.split("-").map(&:capitalize).join("-")
  321. end
  322. end
  323. end

lib/httpx/connection/http2.rb

95.6% lines covered

273 relevant lines. 261 lines covered and 12 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "securerandom"
  3. 30 require "http/2"
  4. 30 HTTP2::Connection.__send__(:public, :send_buffer) if HTTP2::VERSION < "1.1.1"
  5. 30 module HTTPX
  6. 30 class Connection::HTTP2
  7. 30 include Callbacks
  8. 30 include Loggable
  9. 30 MAX_CONCURRENT_REQUESTS = ::HTTP2::DEFAULT_MAX_CONCURRENT_STREAMS
  10. 30 class Error < Error
  11. 30 def initialize(id, error)
  12. 75 super("stream #{id} closed with error: #{error}")
  13. end
  14. end
  15. 30 class PingError < Error
  16. 30 def initialize
  17. super(0, :ping_error)
  18. end
  19. end
  20. 30 class GoawayError < Error
  21. 30 def initialize(code = :no_error)
  22. 47 super(0, code)
  23. end
  24. end
  25. 30 attr_reader :streams, :pending
  26. 30 def initialize(buffer, options)
  27. 3992 @options = options
  28. 3992 @settings = @options.http2_settings
  29. 3992 @pending = []
  30. 3992 @streams = {}
  31. 3992 @drains = {}
  32. 3992 @pings = []
  33. 3992 @buffer = buffer
  34. 3992 @handshake_completed = false
  35. 3992 @wait_for_handshake = @settings.key?(:wait_for_handshake) ? @settings.delete(:wait_for_handshake) : true
  36. 3992 @max_concurrent_requests = @options.max_concurrent_requests || MAX_CONCURRENT_REQUESTS
  37. 3992 @max_requests = @options.max_requests
  38. 3992 init_connection
  39. end
  40. 30 def timeout
  41. 7875 return @options.timeout[:operation_timeout] if @handshake_completed
  42. 3940 @options.timeout[:settings_timeout]
  43. end
  44. 30 def interests
  45. 110170 if @connection.state == :closed
  46. 10260 return unless @handshake_completed
  47. 10184 return if @buffer.empty?
  48. 5966 return :w
  49. end
  50. 99910 unless @connection.state == :connected && @handshake_completed
  51. 21988 return @buffer.empty? ? :r : :rw
  52. end
  53. 75471 unless @connection.send_buffer.empty?
  54. 18 return :rw unless @buffer.empty?
  55. # waiting for WINDOW_UPDATE frames
  56. 4 return :r
  57. end
  58. 75453 return :w if !@pending.empty? && can_buffer_more_requests?
  59. 75453 return :w unless @drains.empty?
  60. 70901 if @buffer.empty?
  61. 59696 return if @streams.empty? && @pings.empty?
  62. 56181 :r
  63. else
  64. 11205 :w
  65. end
  66. end
  67. 30 def close
  68. 3329 unless @connection.state == :closed
  69. 3320 @connection.goaway
  70. 3320 emit(:timeout, @options.timeout[:close_handshake_timeout])
  71. end
  72. 3329 emit(:close)
  73. end
  74. 30 def empty?
  75. 3349 @connection.state == :closed || @streams.empty?
  76. end
  77. 30 def exhausted?
  78. 3916 !@max_requests.positive?
  79. end
  80. 30 def <<(data)
  81. 41553 @connection << data
  82. end
  83. 30 def send(request, head = false)
  84. 8704 unless can_buffer_more_requests?
  85. 4224 head ? @pending.unshift(request) : @pending << request
  86. 4224 return false
  87. end
  88. 4480 unless (stream = @streams[request])
  89. 4480 stream = @connection.new_stream
  90. 4480 handle_stream(stream, request)
  91. 4043 @streams[request] = stream
  92. 4043 @max_requests -= 1
  93. end
  94. 4480 handle(request, stream)
  95. 4462 true
  96. rescue ::HTTP2::Error::StreamLimitExceeded
  97. @pending.unshift(request)
  98. false
  99. end
  100. 30 def consume
  101. 26949 @streams.each do |request, stream|
  102. 12307 next unless request.can_buffer?
  103. 1310 handle(request, stream)
  104. end
  105. end
  106. 30 def handle_error(ex, request = nil)
  107. 391 if ex.is_a?(OperationTimeoutError) && !@handshake_completed && @connection.state != :closed
  108. 21 @connection.goaway(:settings_timeout, "closing due to settings timeout")
  109. 21 emit(:close_handshake)
  110. 21 settings_ex = SettingsTimeoutError.new(ex.timeout, ex.message)
  111. 21 settings_ex.set_backtrace(ex.backtrace)
  112. 21 ex = settings_ex
  113. end
  114. 391 @streams.each_key do |req|
  115. 306 next if request && request == req
  116. 18 emit(:error, req, ex)
  117. end
  118. 771 while (req = @pending.shift)
  119. 69 next if request && request == req
  120. 69 emit(:error, req, ex)
  121. end
  122. end
  123. 30 def ping
  124. 22 ping = SecureRandom.gen_random(8)
  125. 22 @connection.ping(ping.dup)
  126. ensure
  127. 22 @pings << ping
  128. end
  129. 30 def waiting_for_ping?
  130. 472 @pings.any?
  131. end
  132. 30 private
  133. 30 def can_buffer_more_requests?
  134. 9641 (@handshake_completed || !@wait_for_handshake) &&
  135. @streams.size < @max_concurrent_requests &&
  136. @streams.size < @max_requests
  137. end
  138. 30 def send_pending
  139. 10685 while (request = @pending.shift)
  140. 4069 break unless send(request, true)
  141. end
  142. end
  143. 30 def handle(request, stream)
  144. 6034 catch(:buffer_full) do
  145. 6034 request.transition(:headers)
  146. 6025 join_headers(stream, request) if request.state == :headers
  147. 6025 request.transition(:body)
  148. 6025 join_body(stream, request) if request.state == :body
  149. 4601 request.transition(:trailers)
  150. 4601 join_trailers(stream, request) if request.state == :trailers && !request.body.empty?
  151. 4601 request.transition(:done)
  152. end
  153. end
  154. 30 def init_connection
  155. 3992 @connection = ::HTTP2::Client.new(@settings)
  156. 3992 @connection.on(:frame, &method(:on_frame))
  157. 3992 @connection.on(:frame_sent, &method(:on_frame_sent))
  158. 3992 @connection.on(:frame_received, &method(:on_frame_received))
  159. 3992 @connection.on(:origin, &method(:on_origin))
  160. 3992 @connection.on(:promise, &method(:on_promise))
  161. 3992 @connection.on(:altsvc) { |frame| on_altsvc(frame[:origin], frame) }
  162. 3992 @connection.on(:settings_ack, &method(:on_settings))
  163. 3992 @connection.on(:ack, &method(:on_pong))
  164. 3992 @connection.on(:goaway, &method(:on_close))
  165. #
  166. # Some servers initiate HTTP/2 negotiation right away, some don't.
  167. # As such, we have to check the socket buffer. If there is something
  168. # to read, the server initiated the negotiation. If not, we have to
  169. # initiate it.
  170. #
  171. 3992 @connection.send_connection_preface
  172. end
  173. 30 alias_method :reset, :init_connection
  174. 30 public :reset
  175. 30 def handle_stream(stream, request)
  176. 4498 request.on(:refuse, &method(:on_stream_refuse).curry(3)[stream, request])
  177. 4498 stream.on(:close, &method(:on_stream_close).curry(3)[stream, request])
  178. 4498 stream.on(:half_close) do
  179. 4450 log(level: 2) { "#{stream.id}: waiting for response..." }
  180. end
  181. 4498 stream.on(:altsvc, &method(:on_altsvc).curry(2)[request.origin])
  182. 4498 stream.on(:headers, &method(:on_stream_headers).curry(3)[stream, request])
  183. 4498 stream.on(:data, &method(:on_stream_data).curry(3)[stream, request])
  184. end
  185. 30 def set_protocol_headers(request)
  186. 435 {
  187. 4026 ":scheme" => request.scheme,
  188. ":method" => request.verb,
  189. ":path" => request.path,
  190. ":authority" => request.authority,
  191. }
  192. end
  193. 30 def join_headers(stream, request)
  194. 4462 extra_headers = set_protocol_headers(request)
  195. 4462 if request.headers.key?("host")
  196. 9 log { "forbidden \"host\" header found (#{log_redact_headers(request.headers["host"])}), will use it as authority..." }
  197. 8 extra_headers[":authority"] = request.headers["host"]
  198. end
  199. 4462 log(level: 1, color: :yellow) do
  200. 146 "\n#{request.headers.merge(extra_headers).each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{log_redact_headers(v)}" }.join("\n")}"
  201. end
  202. 4462 stream.headers(request.headers.each(extra_headers), end_stream: request.body.empty?)
  203. end
  204. 30 def join_trailers(stream, request)
  205. 1776 unless request.trailers?
  206. 1767 stream.data("", end_stream: true) if request.callbacks_for?(:trailers)
  207. 1602 return
  208. end
  209. 9 log(level: 1, color: :yellow) do
  210. 17 request.trailers.each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{log_redact_headers(v)}" }.join("\n")
  211. end
  212. 9 stream.headers(request.trailers.each, end_stream: true)
  213. end
  214. 30 def join_body(stream, request)
  215. 5834 return if request.body.empty?
  216. 3202 chunk = @drains.delete(request) || request.drain_body
  217. 3400 while chunk
  218. 3460 next_chunk = request.drain_body
  219. 3460 send_chunk(request, stream, chunk, next_chunk)
  220. 3226 if next_chunk && (@buffer.full? || request.body.unbounded_body?)
  221. 1062 @drains[request] = next_chunk
  222. 1190 throw(:buffer_full)
  223. end
  224. 2036 chunk = next_chunk
  225. end
  226. 1778 return unless (error = request.drain_error)
  227. 28 on_stream_refuse(stream, request, error)
  228. end
  229. 30 def send_chunk(request, stream, chunk, next_chunk)
  230. 3484 log(level: 1, color: :green) { "#{stream.id}: -> DATA: #{chunk.bytesize} bytes..." }
  231. 3484 log(level: 2, color: :green) { "#{stream.id}: -> #{log_redact_body(chunk.inspect)}" }
  232. 3460 stream.data(chunk, end_stream: end_stream?(request, next_chunk))
  233. end
  234. 30 def end_stream?(request, next_chunk)
  235. 3208 !(next_chunk || request.trailers? || request.callbacks_for?(:trailers))
  236. end
  237. ######
  238. # HTTP/2 Callbacks
  239. ######
  240. 30 def on_stream_headers(stream, request, h)
  241. 4347 response = request.response
  242. 4347 if response.is_a?(Response) && response.version == "2.0"
  243. 133 on_stream_trailers(stream, response, h)
  244. 133 return
  245. end
  246. 4214 log(color: :yellow) do
  247. 146 h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{log_redact_headers(v)}" }.join("\n")
  248. end
  249. 4214 _, status = h.shift
  250. 4214 headers = request.options.headers_class.new(h)
  251. 4214 response = request.options.response_class.new(request, status, "2.0", headers)
  252. 4214 request.response = response
  253. 3795 @streams[request] = stream
  254. 4205 handle(request, stream) if request.expects?
  255. end
  256. 30 def on_stream_trailers(stream, response, h)
  257. 133 log(color: :yellow) do
  258. h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{log_redact_headers(v)}" }.join("\n")
  259. end
  260. 133 response.merge_headers(h)
  261. end
  262. 30 def on_stream_data(stream, request, data)
  263. 8179 log(level: 1, color: :green) { "#{stream.id}: <- DATA: #{data.bytesize} bytes..." }
  264. 8179 log(level: 2, color: :green) { "#{stream.id}: <- #{log_redact_body(data.inspect)}" }
  265. 8155 request.response << data
  266. end
  267. 30 def on_stream_refuse(stream, request, error)
  268. 28 on_stream_close(stream, request, error)
  269. 28 stream.close
  270. end
  271. 30 def on_stream_close(stream, request, error)
  272. 4127 return if error == :stream_closed && !@streams.key?(request)
  273. 4115 log(level: 2) { "#{stream.id}: closing stream" }
  274. 4099 teardown(request)
  275. 4099 if error
  276. 28 case error
  277. when :http_1_1_required
  278. emit(:error, request, error)
  279. else
  280. 28 ex = Error.new(stream.id, error)
  281. 28 ex.set_backtrace(caller)
  282. 28 response = ErrorResponse.new(request, ex)
  283. 28 request.response = response
  284. 28 emit(:response, request, response)
  285. end
  286. else
  287. 4071 response = request.response
  288. 4071 if response && response.is_a?(Response) && response.status == 421
  289. 9 emit(:error, request, :http_1_1_required)
  290. else
  291. 4062 emit(:response, request, response)
  292. end
  293. end
  294. 4090 send(@pending.shift) unless @pending.empty?
  295. 4090 return unless @streams.empty? && exhausted?
  296. 9 if @pending.empty?
  297. close
  298. else
  299. 9 emit(:exhausted)
  300. end
  301. end
  302. 30 def on_frame(bytes)
  303. 24679 @buffer << bytes
  304. end
  305. 30 def on_settings(*)
  306. 3935 @handshake_completed = true
  307. 3935 emit(:current_timeout)
  308. 3935 @max_concurrent_requests = [@max_concurrent_requests, @connection.remote_settings[:settings_max_concurrent_streams]].min
  309. 3935 send_pending
  310. end
  311. 30 def on_close(_last_frame, error, _payload)
  312. 56 is_connection_closed = @connection.state == :closed
  313. 56 if error
  314. 56 @buffer.clear if is_connection_closed
  315. 50 case error
  316. when :http_1_1_required
  317. 24 while (request = @pending.shift)
  318. 9 emit(:error, request, error)
  319. end
  320. else
  321. 47 ex = GoawayError.new(error)
  322. 47 ex.set_backtrace(caller)
  323. 47 @pending.unshift(*@streams.keys)
  324. 47 teardown
  325. 47 handle_error(ex)
  326. end
  327. end
  328. 56 return unless is_connection_closed && @streams.empty?
  329. 56 emit(:close) if is_connection_closed
  330. end
  331. 30 def on_frame_sent(frame)
  332. 20776 log(level: 2) { "#{frame[:stream]}: frame was sent!" }
  333. 20680 log(level: 2, color: :blue) do
  334. 12 payload =
  335. 95 case frame[:type]
  336. when :data
  337. 27 frame.merge(payload: frame[:payload].bytesize)
  338. when :headers, :ping
  339. 27 frame.merge(payload: log_redact_headers(frame[:payload]))
  340. else
  341. 54 frame
  342. end
  343. 96 "#{frame[:stream]}: #{payload}"
  344. end
  345. end
  346. 30 def on_frame_received(frame)
  347. 22068 log(level: 2) { "#{frame[:stream]}: frame was received!" }
  348. 21996 log(level: 2, color: :magenta) do
  349. 9 payload =
  350. 71 case frame[:type]
  351. when :data
  352. 27 frame.merge(payload: frame[:payload].bytesize)
  353. when :headers, :ping
  354. 18 frame.merge(payload: log_redact_headers(frame[:payload]))
  355. else
  356. 36 frame
  357. end
  358. 72 "#{frame[:stream]}: #{payload}"
  359. end
  360. end
  361. 30 def on_altsvc(origin, frame)
  362. log(level: 2) { "#{frame[:stream]}: altsvc frame was received" }
  363. log(level: 2) { "#{frame[:stream]}: #{log_redact_headers(frame.inspect)}" }
  364. alt_origin = URI.parse("#{frame[:proto]}://#{frame[:host]}:#{frame[:port]}")
  365. params = { "ma" => frame[:max_age] }
  366. emit(:altsvc, origin, alt_origin, origin, params)
  367. end
  368. 30 def on_promise(stream)
  369. 27 emit(:promise, @streams.key(stream.parent), stream)
  370. end
  371. 30 def on_origin(origin)
  372. emit(:origin, origin)
  373. end
  374. 30 def on_pong(ping)
  375. 9 raise PingError unless @pings.delete(ping.to_s)
  376. 9 emit(:pong)
  377. end
  378. 30 def teardown(request = nil)
  379. 4146 if request
  380. 4099 @drains.delete(request)
  381. 4099 @streams.delete(request)
  382. else
  383. 47 @drains.clear
  384. 47 @streams.clear
  385. end
  386. end
  387. end
  388. 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. 30 require "ipaddr"
  28. 30 module HTTPX
  29. # Represents a domain name ready for extracting its registered domain
  30. # and TLD.
  31. 30 class DomainName
  32. 30 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. 30 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. 30 attr_reader :domain
  47. 30 class << self
  48. 30 def new(domain)
  49. 963 return domain if domain.is_a?(self)
  50. 891 super
  51. end
  52. # Normalizes a _domain_ using the Punycode algorithm as necessary.
  53. # The result will be a downcased, ASCII-only string.
  54. 30 def normalize(domain)
  55. 855 unless domain.ascii_only?
  56. domain = domain.chomp(".").unicode_normalize(:nfc)
  57. domain = Punycode.encode_hostname(domain)
  58. end
  59. 855 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. 30 def initialize(hostname)
  65. 891 hostname = String(hostname)
  66. 891 raise ArgumentError, "domain name must not start with a dot: #{hostname}" if hostname.start_with?(".")
  67. 98 begin
  68. 891 @ipaddr = IPAddr.new(hostname)
  69. 36 @hostname = @ipaddr.to_s
  70. 36 return
  71. rescue IPAddr::Error
  72. 855 nil
  73. end
  74. 855 @hostname = DomainName.normalize(hostname)
  75. 855 tld = if (last_dot = @hostname.rindex("."))
  76. 207 @hostname[(last_dot + 1)..-1]
  77. else
  78. 648 @hostname
  79. end
  80. # unknown/local TLD
  81. 855 @domain = if last_dot
  82. # fallback - accept cookies down to second level
  83. # cf. http://www.dkim-reputation.org/regdom-libs/
  84. 207 if (penultimate_dot = @hostname.rindex(".", last_dot - 1))
  85. 54 @hostname[(penultimate_dot + 1)..-1]
  86. else
  87. 153 @hostname
  88. end
  89. else
  90. # no domain part - must be a local hostname
  91. 648 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. 30 def cookie_domain?(domain, host_only = false)
  100. # RFC 6265 #5.3
  101. # When the user agent "receives a cookie":
  102. 36 return self == @domain if host_only
  103. 36 domain = DomainName.new(domain)
  104. # RFC 6265 #5.1.3
  105. # Do not perform subdomain matching against IP addresses.
  106. 36 @hostname == domain.hostname if @ipaddr
  107. # RFC 6265 #4.1.1
  108. # Domain-value must be a subdomain.
  109. 36 @domain && self <= domain && domain <= @domain
  110. end
  111. 30 def <=>(other)
  112. 54 other = DomainName.new(other)
  113. 54 othername = other.hostname
  114. 54 if othername == @hostname
  115. 18 0
  116. 35 elsif @hostname.end_with?(othername) && @hostname[-othername.size - 1, 1] == "."
  117. # The other is higher
  118. 18 -1
  119. else
  120. # The other is lower
  121. 18 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. 30 module HTTPX
  3. # the default exception class for exceptions raised by HTTPX.
  4. 30 class Error < StandardError; end
  5. 30 class UnsupportedSchemeError < Error; end
  6. 30 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. 30 class TimeoutError < Error
  10. # The timeout value which caused this error to be raised.
  11. 30 attr_reader :timeout
  12. # initializes the timeout exception with the +timeout+ causing the error, and the
  13. # error +message+ for it.
  14. 30 def initialize(timeout, message)
  15. 737 @timeout = timeout
  16. 737 super(message)
  17. end
  18. # clones this error into a HTTPX::ConnectionTimeoutError.
  19. 30 def to_connection_error
  20. 27 ex = ConnectTimeoutError.new(@timeout, message)
  21. 27 ex.set_backtrace(backtrace)
  22. 27 ex
  23. end
  24. end
  25. # Raise when it can't acquire a connection from the pool.
  26. 30 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. 30 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. 30 class RequestTimeoutError < TimeoutError
  34. # The HTTPX::Request request object this exception refers to.
  35. 30 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. 30 def initialize(request, response, timeout)
  39. 567 @request = request
  40. 567 @response = response
  41. 567 super(timeout, "Timed out after #{timeout} seconds")
  42. end
  43. 30 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. 30 class ReadTimeoutError < RequestTimeoutError; end
  49. # Error raised when there was a timeout while sending a request from the server.
  50. 30 class WriteTimeoutError < RequestTimeoutError; end
  51. # Error raised when there was a timeout while waiting for the HTTP/2 settings frame from the server.
  52. 30 class SettingsTimeoutError < TimeoutError; end
  53. # Error raised when there was a timeout while resolving a domain to an IP.
  54. 30 class ResolveTimeoutError < TimeoutError; end
  55. # Error raise when there was a timeout waiting for readiness of the socket the request is related to.
  56. 30 class OperationTimeoutError < TimeoutError; end
  57. # Error raised when there was an error while resolving a domain to an IP.
  58. 30 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. 30 class NativeResolveError < ResolveError
  62. 30 attr_reader :host
  63. 30 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. 30 def initialize(connection, host, message = "Can't resolve #{host}")
  67. 160 @connection = connection
  68. 160 @host = host
  69. 160 super(message)
  70. end
  71. end
  72. # The exception class for HTTP responses with 4xx or 5xx status.
  73. 30 class HTTPError < Error
  74. # The HTTPX::Response response object this exception refers to.
  75. 30 attr_reader :response
  76. # Creates the instance and assigns the HTTPX::Response +response+.
  77. 30 def initialize(response)
  78. 103 @response = response
  79. 103 super("HTTP Error: #{@response.status} #{@response.headers}\n#{@response.body}")
  80. end
  81. # The HTTP response status.
  82. #
  83. # error.status #=> 404
  84. 30 def status
  85. 18 @response.status
  86. end
  87. end
  88. end

lib/httpx/extensions.rb

95.24% lines covered

21 relevant lines. 20 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "uri"
  3. 30 module HTTPX
  4. 30 module ArrayExtensions
  5. 30 module Intersect
  6. refine Array do
  7. # Ruby 3.1 backport
  8. 4 def intersect?(arr)
  9. 18 if size < arr.size
  10. smaller = self
  11. else
  12. 18 smaller, arr = arr, self
  13. end
  14. 18 (arr & smaller).size > 0
  15. end
  16. 29 end unless Array.method_defined?(:intersect?)
  17. end
  18. end
  19. 30 module URIExtensions
  20. # uri 0.11 backport, ships with ruby 3.1
  21. 30 refine URI::Generic do
  22. 30 def non_ascii_hostname
  23. 838 @non_ascii_hostname
  24. end
  25. 30 def non_ascii_hostname=(hostname)
  26. 36 @non_ascii_hostname = hostname
  27. end
  28. def authority
  29. 6209 return host if port == default_port
  30. 699 "#{host}:#{port}"
  31. 29 end unless URI::HTTP.method_defined?(:authority)
  32. def origin
  33. 5070 "#{scheme}://#{authority}"
  34. 29 end unless URI::HTTP.method_defined?(:origin)
  35. end
  36. end
  37. 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. 30 module HTTPX
  3. 30 class Headers
  4. 30 class << self
  5. 30 def new(headers = nil)
  6. 31943 return headers if headers.is_a?(self)
  7. 13915 super
  8. end
  9. end
  10. 30 def initialize(headers = nil)
  11. 13915 if headers.nil? || headers.empty?
  12. 2139 @headers = headers.to_h
  13. 1928 return
  14. end
  15. 11776 @headers = {}
  16. 11776 headers.each do |field, value|
  17. 73338 field = downcased(field)
  18. 73338 value = array_value(value)
  19. 73338 current = @headers[field]
  20. 73338 if current.nil?
  21. 66141 @headers[field] = value
  22. else
  23. 62 current.concat(value)
  24. end
  25. end
  26. end
  27. # cloned initialization
  28. 30 def initialize_clone(orig, **kwargs)
  29. 9 super
  30. 9 @headers = orig.instance_variable_get(:@headers).clone(**kwargs)
  31. end
  32. # dupped initialization
  33. 30 def initialize_dup(orig)
  34. 26564 super
  35. 26564 @headers = orig.instance_variable_get(:@headers).transform_values(&:dup)
  36. end
  37. # freezes the headers hash
  38. 30 def freeze
  39. 26963 @headers.each_value(&:freeze).freeze
  40. 26963 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. 30 def merge(other)
  47. 5853 headers = dup
  48. 5853 other.each do |field, value|
  49. 14849 headers[downcased(field)] = value
  50. end
  51. 5853 headers
  52. end
  53. # returns the comma-separated values of the header field
  54. # identified by +field+, or nil otherwise.
  55. #
  56. 30 def [](field)
  57. 75886 a = @headers[downcased(field)] || return
  58. 31510 a.join(", ")
  59. end
  60. # sets +value+ (if not nil) as single value for the +field+ header.
  61. #
  62. 30 def []=(field, value)
  63. 29276 return unless value
  64. 26658 @headers[downcased(field)] = array_value(value)
  65. end
  66. # deletes all values associated with +field+ header.
  67. #
  68. 30 def delete(field)
  69. 361 canonical = downcased(field)
  70. 361 @headers.delete(canonical) if @headers.key?(canonical)
  71. end
  72. # adds additional +value+ to the existing, for header +field+.
  73. #
  74. 30 def add(field, value)
  75. 1698 (@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. 30 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. 30 def each(extra_headers = nil)
  89. 43656 return enum_for(__method__, extra_headers) { @headers.size } unless block_given?
  90. 24519 @headers.each do |field, value|
  91. 90296 yield(field, value.join(", ")) unless value.empty?
  92. end
  93. 6449 extra_headers.each do |field, value|
  94. 29645 yield(field, value) unless value.empty?
  95. 24518 end if extra_headers
  96. end
  97. 30 def ==(other)
  98. 6392 other == to_hash
  99. end
  100. 30 def empty?
  101. 360 @headers.empty?
  102. end
  103. # the headers store in Hash format
  104. 30 def to_hash
  105. 8525 Hash[to_a]
  106. end
  107. 30 alias_method :to_h, :to_hash
  108. # the headers store in array of pairs format
  109. 30 def to_a
  110. 8551 Array(each)
  111. end
  112. # headers as string
  113. 30 def to_s
  114. 2169 @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. 30 def key?(downcased_key)
  127. 91358 @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. 30 def get(field)
  134. 376 @headers[field] || EMPTY
  135. end
  136. 30 private
  137. 30 def array_value(value)
  138. 102614 Array(value)
  139. end
  140. 30 def downcased(field)
  141. 196759 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. 30 require "socket"
  3. 30 require "httpx/io/udp"
  4. 30 require "httpx/io/tcp"
  5. 30 require "httpx/io/unix"
  6. begin
  7. 30 require "httpx/io/ssl"
  8. rescue LoadError
  9. end

lib/httpx/io/ssl.rb

97.67% lines covered

86 relevant lines. 84 lines covered and 2 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "openssl"
  3. 30 module HTTPX
  4. 30 TLSError = OpenSSL::SSL::SSLError
  5. 30 class SSL < TCP
  6. # rubocop:disable Style/MutableConstant
  7. 30 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. 30 TLS_OPTIONS[:verify_hostname] = true if RUBY_ENGINE == "jruby" && JOpenSSL::VERSION < "0.15.4"
  11. # rubocop:enable Style/MutableConstant
  12. 30 TLS_OPTIONS.freeze
  13. 30 attr_writer :ssl_session
  14. 30 def initialize(_, _, options)
  15. 3668 super
  16. 3668 @ssl_session = nil
  17. 3668 ctx_options = TLS_OPTIONS.merge(options.ssl)
  18. 3668 @sni_hostname = ctx_options.delete(:hostname) || @hostname
  19. 3668 if @keep_open && @io.is_a?(OpenSSL::SSL::SSLSocket)
  20. # externally initiated ssl socket
  21. 25 @ctx = @io.context
  22. 25 @state = :negotiated
  23. else
  24. 3643 @ctx = OpenSSL::SSL::SSLContext.new
  25. 3643 @ctx.set_params(ctx_options) unless ctx_options.empty?
  26. 3643 unless @ctx.session_cache_mode.nil? # a dummy method on JRuby
  27. 3295 @ctx.session_cache_mode =
  28. OpenSSL::SSL::SSLContext::SESSION_CACHE_CLIENT | OpenSSL::SSL::SSLContext::SESSION_CACHE_NO_INTERNAL_STORE
  29. end
  30. 3643 yield(self) if block_given?
  31. end
  32. 3668 @verify_hostname = @ctx.verify_hostname
  33. end
  34. 30 if OpenSSL::SSL::SSLContext.method_defined?(:session_new_cb=)
  35. 29 def session_new_cb(&pr)
  36. 9484 @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. 30 def protocol
  43. 3600 @io.alpn_protocol || super
  44. rescue StandardError
  45. 11 super
  46. end
  47. 30 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. 383 proto = @io.alpn_protocol
  52. 382 return super if proto.nil? || proto.empty?
  53. 379 proto
  54. rescue StandardError
  55. 1 super
  56. end
  57. end
  58. 30 def can_verify_peer?
  59. 29 @ctx.verify_mode == OpenSSL::SSL::VERIFY_PEER
  60. end
  61. 30 def verify_hostname(host)
  62. 31 return false if @ctx.verify_mode == OpenSSL::SSL::VERIFY_NONE
  63. 31 return false if !@io.respond_to?(:peer_cert) || @io.peer_cert.nil?
  64. 31 OpenSSL::SSL.verify_certificate_identity(@io.peer_cert, host)
  65. end
  66. 30 def connected?
  67. 15903 @state == :negotiated
  68. end
  69. 30 def ssl_session_expired?
  70. 3939 @ssl_session.nil? || Process.clock_gettime(Process::CLOCK_REALTIME) >= (@ssl_session.time.to_f + @ssl_session.timeout)
  71. end
  72. 30 def connect
  73. 15969 return if @state == :negotiated
  74. 15969 unless @state == :connected
  75. 8826 super
  76. 8787 return unless @state == :connected
  77. end
  78. 10966 unless @io.is_a?(OpenSSL::SSL::SSLSocket)
  79. 3939 if (hostname_is_ip = (@ip == @sni_hostname)) && @ctx.verify_hostname
  80. # IPv6 address would be "[::1]", must turn to "0000:0000:0000:0000:0000:0000:0000:0001" for cert SAN check
  81. 45 @sni_hostname = @ip.to_string
  82. # IP addresses in SNI is not valid per RFC 6066, section 3.
  83. 45 @ctx.verify_hostname = false
  84. end
  85. 3939 @io = OpenSSL::SSL::SSLSocket.new(@io, @ctx)
  86. 3939 @io.hostname = @sni_hostname unless hostname_is_ip
  87. 3939 @io.session = @ssl_session unless ssl_session_expired?
  88. 3939 @io.sync_close = true
  89. end
  90. 10966 try_ssl_connect
  91. end
  92. 30 def try_ssl_connect
  93. 10966 ret = @io.connect_nonblock(exception: false)
  94. 10988 log(level: 3, color: :cyan) { "TLS CONNECT: #{ret}..." }
  95. 10203 case ret
  96. when :wait_readable
  97. 7054 @interests = :r
  98. 7054 return
  99. when :wait_writable
  100. @interests = :w
  101. return
  102. end
  103. 3886 @io.post_connection_check(@sni_hostname) if @ctx.verify_mode != OpenSSL::SSL::VERIFY_NONE && @verify_hostname
  104. 3885 transition(:negotiated)
  105. 3885 @interests = :w
  106. end
  107. 30 private
  108. 30 def transition(nextstate)
  109. 13863 case nextstate
  110. when :negotiated
  111. 3885 return unless @state == :connected
  112. when :closed
  113. 3801 return unless @state == :negotiated ||
  114. @state == :connected
  115. end
  116. 15400 do_transition(nextstate)
  117. end
  118. 30 def log_transition_state(nextstate)
  119. 79 return super unless nextstate == :negotiated
  120. 18 server_cert = @io.peer_cert
  121. 16 "#{super}\n\n" \
  122. 2 "SSL connection using #{@io.ssl_version} / #{Array(@io.cipher).first}\n" \
  123. 2 "ALPN, server accepted to use #{protocol}\n" \
  124. "Server certificate:\n " \
  125. 2 "subject: #{server_cert.subject}\n " \
  126. 2 "start date: #{server_cert.not_before}\n " \
  127. 2 "expire date: #{server_cert.not_after}\n " \
  128. 2 "issuer: #{server_cert.issuer}\n " \
  129. "SSL certificate verify ok."
  130. end
  131. end
  132. end

lib/httpx/io/tcp.rb

93.7% lines covered

127 relevant lines. 119 lines covered and 8 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "resolv"
  3. 30 module HTTPX
  4. 30 class TCP
  5. 30 include Loggable
  6. 30 using URIExtensions
  7. 30 attr_reader :ip, :port, :addresses, :state, :interests
  8. 30 alias_method :host, :ip
  9. 30 def initialize(origin, addresses, options)
  10. 8584 @state = :idle
  11. 8584 @keep_open = false
  12. 8584 @addresses = []
  13. 8584 @ip_index = -1
  14. 8584 @ip = nil
  15. 8584 @hostname = origin.host
  16. 8584 @options = options
  17. 8584 @fallback_protocol = @options.fallback_protocol
  18. 8584 @port = origin.port
  19. 8584 @interests = :w
  20. 8584 if @options.io
  21. 59 @io = case @options.io
  22. when Hash
  23. 18 @options.io[origin.authority]
  24. else
  25. 41 @options.io
  26. end
  27. 59 raise Error, "Given IO objects do not match the request authority" unless @io
  28. 59 _, _, _, ip = @io.addr
  29. 59 @ip = Resolver::Entry.new(ip)
  30. 59 @addresses << @ip
  31. 59 @keep_open = true
  32. 59 @state = :connected
  33. else
  34. 8525 add_addresses(addresses)
  35. end
  36. 8584 @ip_index = @addresses.size - 1
  37. end
  38. 30 def socket
  39. 219 @io
  40. end
  41. 30 def add_addresses(addrs)
  42. 8968 return if addrs.empty?
  43. 8959 ip_index = @ip_index || (@addresses.size - 1)
  44. 8959 if addrs.first.ipv6?
  45. # should be the next in line
  46. 389 @addresses = [*@addresses[0, ip_index], *addrs, *@addresses[ip_index..-1]]
  47. else
  48. 8570 @addresses.unshift(*addrs)
  49. end
  50. 8087 @ip_index += addrs.size
  51. end
  52. # eliminates expired entries and returns whether there are still any left.
  53. 30 def addresses?
  54. 892 prev_addr_size = @addresses.size
  55. 892 @addresses.delete_if(&:expired?).sort! do |addr1, addr2|
  56. 1660 if addr1.ipv6?
  57. 2 addr2.ipv6? ? 0 : 1
  58. else
  59. 1658 addr2.ipv6? ? -1 : 0
  60. end
  61. end
  62. 892 @ip_index = @addresses.size - 1 if prev_addr_size != @addresses.size
  63. 892 @addresses.any?
  64. end
  65. 30 def to_io
  66. 32398 @io.to_io
  67. end
  68. 30 def protocol
  69. 5377 @fallback_protocol
  70. end
  71. 30 def connect
  72. 31474 return unless closed?
  73. 31331 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. 31331 if !@io || @io.closed?
  83. 9424 transition(:idle)
  84. 9424 @io = build_socket
  85. end
  86. 31331 try_connect
  87. rescue Errno::EHOSTUNREACH,
  88. Errno::ENETUNREACH => e
  89. 31 @ip_index -= 1
  90. 31 raise e if @ip_index.negative?
  91. 22 log { "failed connecting to #{@ip} (#{e.message}), evict from cache and trying next..." }
  92. 22 @options.resolver_cache.evict(@hostname, @ip)
  93. 22 @io = build_socket
  94. 22 retry
  95. rescue Errno::ECONNREFUSED,
  96. Errno::EADDRNOTAVAIL,
  97. SocketError,
  98. IOError => e
  99. 1049 @ip_index -= 1
  100. 1068 raise e if @ip_index.negative?
  101. 1004 log { "failed connecting to #{@ip} (#{e.message}), trying next..." }
  102. 990 @io = build_socket
  103. 990 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. 30 def try_connect
  112. 31331 ret = @io.connect_nonblock(Socket.sockaddr_in(@port, @ip.to_s), exception: false)
  113. 19900 log(level: 3, color: :cyan) { "TCP CONNECT: #{ret}..." }
  114. 17837 case ret
  115. when :wait_readable
  116. @interests = :r
  117. return
  118. when :wait_writable
  119. 10422 @interests = :w
  120. 10422 return
  121. end
  122. 9306 transition(:connected)
  123. 9306 @interests = :w
  124. rescue Errno::EALREADY
  125. 10504 @interests = :w
  126. end
  127. 30 private :try_connect
  128. 30 def read(size, buffer)
  129. 66794 ret = @io.read_nonblock(size, buffer, exception: false)
  130. 66792 if ret == :wait_readable
  131. 16522 buffer.clear
  132. 15399 return 0
  133. end
  134. 50270 return if ret.nil?
  135. 50371 log { "READ: #{buffer.bytesize} bytes..." }
  136. 50252 buffer.bytesize
  137. end
  138. 30 def write(buffer)
  139. 22615 siz = @io.write_nonblock(buffer, exception: false)
  140. 22607 return 0 if siz == :wait_writable
  141. 22589 return if siz.nil?
  142. 22698 log { "WRITE: #{siz} bytes..." }
  143. 22589 buffer.shift!(siz)
  144. 22589 siz
  145. end
  146. 30 def close
  147. 10408 return if @keep_open || closed?
  148. 917 begin
  149. 9094 @io.close
  150. ensure
  151. 9094 transition(:closed)
  152. end
  153. end
  154. 30 def connected?
  155. 21604 @state == :connected
  156. end
  157. 30 def closed?
  158. 41963 @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. 30 private
  171. 30 def build_socket
  172. 10436 @ip = @addresses[@ip_index]
  173. 10436 Socket.new(@ip.family, :STREAM, 0)
  174. end
  175. 30 def transition(nextstate)
  176. 14674 case nextstate
  177. # when :idle
  178. when :connected
  179. 5499 return unless @state == :idle
  180. when :closed
  181. 5293 return unless @state == :connected
  182. end
  183. 16333 do_transition(nextstate)
  184. end
  185. 30 def do_transition(nextstate)
  186. 31981 log(level: 1) { log_transition_state(nextstate) }
  187. 31733 @state = nextstate
  188. end
  189. 30 def log_transition_state(nextstate)
  190. 248 label = host
  191. 248 label = "#{label}(##{@io.fileno})" if nextstate == :connected
  192. 222 "#{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. 30 require "ipaddr"
  3. 30 module HTTPX
  4. 30 class UDP
  5. 30 include Loggable
  6. 30 def initialize(ip, port, options)
  7. 530 @host = ip
  8. 530 @port = port
  9. 530 @io = UDPSocket.new(IPAddr.new(ip).family)
  10. 530 @options = options
  11. end
  12. 30 def to_io
  13. 1623 @io.to_io
  14. end
  15. 30 def connect; end
  16. 30 def connected?
  17. 530 true
  18. end
  19. 30 def close
  20. 533 @io.close
  21. end
  22. 30 if RUBY_ENGINE == "jruby"
  23. # In JRuby, sendmsg_nonblock is not implemented
  24. 1 def write(buffer)
  25. 53 siz = @io.send(buffer.to_s, 0, @host, @port)
  26. 53 log { "WRITE: #{siz} bytes..." }
  27. 53 buffer.shift!(siz)
  28. 53 siz
  29. end
  30. else
  31. 29 def write(buffer)
  32. 783 siz = @io.sendmsg_nonblock(buffer.to_s, 0, Socket.sockaddr_in(@port, @host.to_s), exception: false)
  33. 783 return 0 if siz == :wait_writable
  34. 783 return if siz.nil?
  35. 783 log { "WRITE: #{siz} bytes..." }
  36. 783 buffer.shift!(siz)
  37. 783 siz
  38. end
  39. end
  40. 30 def read(size, buffer)
  41. 1599 ret = @io.recvfrom_nonblock(size, 0, buffer, exception: false)
  42. 1599 return 0 if ret == :wait_readable
  43. 765 return if ret.nil?
  44. 765 log { "READ: #{buffer.bytesize} bytes..." }
  45. 765 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. 30 module HTTPX
  3. 30 class UNIX < TCP
  4. 30 using URIExtensions
  5. 30 attr_reader :path
  6. 30 alias_method :host, :path
  7. 30 def initialize(origin, path, options)
  8. 32 @addresses = []
  9. 32 @hostname = origin.host
  10. 32 @state = :idle
  11. 32 @options = options
  12. 32 @fallback_protocol = @options.fallback_protocol
  13. 32 if @options.io
  14. 16 @io = case @options.io
  15. when Hash
  16. 8 @options.io[origin.authority]
  17. else
  18. 8 @options.io
  19. end
  20. 16 raise Error, "Given IO objects do not match the request authority" unless @io
  21. 16 @path = @io.path
  22. 16 @keep_open = true
  23. 16 @state = :connected
  24. 16 elsif path
  25. 16 @path = path
  26. else
  27. raise Error, "No path given where to store the socket"
  28. end
  29. 32 @io ||= build_socket
  30. end
  31. 30 def connect
  32. 24 return unless closed?
  33. begin
  34. 24 if @io.closed?
  35. 8 transition(:idle)
  36. 8 @io = build_socket
  37. end
  38. 24 @io.connect_nonblock(Socket.sockaddr_un(@path))
  39. rescue Errno::EISCONN
  40. end
  41. 16 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. 30 def addresses?
  48. 16 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. 30 private
  56. 30 def build_socket
  57. 24 Socket.new(Socket::PF_UNIX, :STREAM, 0)
  58. end
  59. end
  60. end

lib/httpx/loggable.rb

100.0% lines covered

29 relevant lines. 29 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "fiber" if RUBY_VERSION < "3.0.0"
  3. 30 module HTTPX
  4. 30 module Loggable
  5. 30 COLORS = {
  6. black: 30,
  7. red: 31,
  8. green: 32,
  9. yellow: 33,
  10. blue: 34,
  11. magenta: 35,
  12. cyan: 36,
  13. white: 37,
  14. }.freeze
  15. 30 USE_DEBUG_LOG = ENV.key?("HTTPX_DEBUG")
  16. 30 def log(
  17. level: @options.debug_level,
  18. color: nil,
  19. debug_level: @options.debug_level,
  20. debug: @options.debug,
  21. &msg
  22. )
  23. 863123 return unless debug_level >= level
  24. 335134 debug_stream = debug || ($stderr if USE_DEBUG_LOG)
  25. 335134 return unless debug_stream
  26. 5048 klass = self.class
  27. 11077 until (class_name = klass.name)
  28. 2404 klass = klass.superclass
  29. end
  30. 5048 message = +"(time:#{Time.now.utc}, pid:#{Process.pid}, " \
  31. 508 "tid:#{Thread.current.object_id}, " \
  32. 508 "fid:#{Fiber.current.object_id}, " \
  33. 508 "self:#{class_name}##{object_id}) "
  34. 5048 message << msg.call << "\n"
  35. 5048 message = "\e[#{COLORS[color]}m#{message}\e[0m" if color && debug_stream.respond_to?(:isatty) && debug_stream.isatty
  36. 5048 debug_stream << message
  37. end
  38. 30 def log_exception(ex, level: @options.debug_level, color: nil, debug_level: @options.debug_level, debug: @options.debug)
  39. 1557 log(level: level, color: color, debug_level: debug_level, debug: debug) { ex.full_message }
  40. end
  41. 30 def log_redact_headers(text)
  42. 1044 log_redact(text, @options.debug_redact == :headers)
  43. end
  44. 30 def log_redact_body(text)
  45. 109 log_redact(text, @options.debug_redact == :body)
  46. end
  47. 30 def log_redact(text, should_redact)
  48. 1153 should_redact ||= @options.debug_redact == true
  49. 1153 return text.to_s unless should_redact
  50. 253 "[REDACTED]"
  51. end
  52. end
  53. end

lib/httpx/options.rb

96.27% lines covered

241 relevant lines. 232 lines covered and 9 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 module HTTPX
  3. # Contains a set of options which are passed and shared across from session to its requests or
  4. # responses.
  5. 30 class Options
  6. 30 BUFFER_SIZE = 1 << 14
  7. 30 WINDOW_SIZE = 1 << 14 # 16K
  8. 30 MAX_BODY_THRESHOLD_SIZE = (1 << 10) * 112 # 112K
  9. 30 KEEP_ALIVE_TIMEOUT = 20
  10. 30 SETTINGS_TIMEOUT = 10
  11. 30 CLOSE_HANDSHAKE_TIMEOUT = 10
  12. 30 CONNECT_TIMEOUT = READ_TIMEOUT = WRITE_TIMEOUT = 60
  13. 30 REQUEST_TIMEOUT = OPERATION_TIMEOUT = nil
  14. 30 RESOLVER_TYPES = %i[memory file].freeze
  15. # default value used for "user-agent" header, when not overridden.
  16. 30 USER_AGENT = "httpx.rb/#{VERSION}".freeze # rubocop:disable Style/RedundantFreeze
  17. 30 @options_names = []
  18. 30 class << self
  19. 30 attr_reader :options_names
  20. 30 def inherited(klass)
  21. 49 super
  22. 49 klass.instance_variable_set(:@options_names, @options_names.dup)
  23. end
  24. 30 def new(options = {})
  25. # let enhanced options go through
  26. 15656 return options if self == Options && options.class < self
  27. 11458 return options if options.is_a?(self)
  28. 6482 super
  29. end
  30. 30 def freeze
  31. 17150 @options_names.freeze
  32. 17150 super
  33. end
  34. 30 def method_added(meth)
  35. 35240 super
  36. 35240 return unless meth =~ /^option_(.+)$/
  37. 15126 optname = Regexp.last_match(1) #: String
  38. 15126 if optname =~ /^(.+[^_])_+with/
  39. # ignore alias method chain generated methods.
  40. # this is the case with RBS runtime tests.
  41. # it relies on the "_with/_without" separator, which is the most used convention,
  42. # however it shouldn't be used in practice in httpx given the plugin architecture
  43. # as the main extension API.
  44. orig_name = Regexp.last_match(1) #: String
  45. return if @options_names.include?(orig_name.to_sym)
  46. end
  47. 15126 optname = optname.to_sym
  48. 15126 attr_reader(optname) unless method_defined?(optname)
  49. 15126 @options_names << optname unless @options_names.include?(optname)
  50. end
  51. end
  52. # creates a new options instance from a given hash, which optionally define the following:
  53. #
  54. # :debug :: an object which log messages are written to (must respond to <tt><<</tt>)
  55. # :debug_level :: the log level of messages (can be 1, 2, or 3).
  56. # :debug_redact :: whether header/body payload should be redacted (defaults to <tt>false</tt>).
  57. # :ssl :: a hash of options which can be set as params of OpenSSL::SSL::SSLContext (see HTTPX::SSL)
  58. # :http2_settings :: a hash of options to be passed to a HTTP2::Connection (ex: <tt>{ max_concurrent_streams: 2 }</tt>)
  59. # :fallback_protocol :: version of HTTP protocol to use by default in the absence of protocol negotiation
  60. # like ALPN (defaults to <tt>"http/1.1"</tt>)
  61. # :supported_compression_formats :: list of compressions supported by the transcoder layer (defaults to <tt>%w[gzip deflate]</tt>).
  62. # :decompress_response_body :: whether to auto-decompress response body (defaults to <tt>true</tt>).
  63. # :compress_request_body :: whether to auto-decompress response body (defaults to <tt>true</tt>)
  64. # :timeout :: hash of timeout configurations (supports <tt>:connect_timeout</tt>, <tt>:settings_timeout</tt>,
  65. # <tt>:operation_timeout</tt>, <tt>:keep_alive_timeout</tt>, <tt>:read_timeout</tt>, <tt>:write_timeout</tt>
  66. # and <tt>:request_timeout</tt>
  67. # :headers :: hash of HTTP headers (ex: <tt>{ "x-custom-foo" => "bar" }</tt>)
  68. # :window_size :: number of bytes to read from a socket
  69. # :buffer_size :: internal read and write buffer size in bytes
  70. # :body_threshold_size :: maximum size in bytes of response payload that is buffered in memory.
  71. # :request_class :: class used to instantiate a request
  72. # :response_class :: class used to instantiate a response
  73. # :headers_class :: class used to instantiate headers
  74. # :request_body_class :: class used to instantiate a request body
  75. # :response_body_class :: class used to instantiate a response body
  76. # :connection_class :: class used to instantiate connections
  77. # :http1_class :: class used to manage HTTP1 sessions
  78. # :http2_class :: class used to imanage HTTP2 sessions
  79. # :resolver_native_class :: class used to resolve names using pure ruby DNS implementation
  80. # :resolver_system_class :: class used to resolve names using system-based (getaddrinfo) name resolution
  81. # :resolver_https_class :: class used to resolve names using DoH
  82. # :pool_class :: class used to instantiate the session connection pool
  83. # :options_class :: class used to instantiate options
  84. # :transport :: type of transport to use (set to "unix" for UNIX sockets)
  85. # :addresses :: bucket of peer addresses (can be a list of IP addresses, a hash of domain to list of adddresses;
  86. # paths should be used for UNIX sockets instead)
  87. # :io :: open socket, or domain/ip-to-socket hash, which requests should be sent to
  88. # :persistent :: whether to persist connections in between requests (defaults to <tt>true</tt>)
  89. # :resolver_class :: which resolver to use (defaults to <tt>:native</tt>, can also be <tt>:system<tt> for
  90. # using getaddrinfo or <tt>:https</tt> for DoH resolver, or a custom class inheriting
  91. # from HTTPX::Resolver::Resolver)
  92. # :resolver_cache :: strategy to cache DNS results, ignored by the <tt>:system</tt> resolver, can be set to <tt>:memory<tt>
  93. # or an instance of a custom class inheriting from HTTPX::Resolver::Cache::Base
  94. # :resolver_options :: hash of options passed to the resolver. Accepted keys depend on the resolver type.
  95. # :pool_options :: hash of options passed to the connection pool (See Pool#initialize).
  96. # :ip_families :: which socket families are supported (system-dependent)
  97. # :origin :: HTTP origin to set on requests with relative path (ex: "https://api.serv.com")
  98. # :base_path :: path to prefix given relative paths with (ex: "/v2")
  99. # :max_concurrent_requests :: max number of requests which can be set concurrently
  100. # :max_requests :: max number of requests which can be made on socket before it reconnects.
  101. # :close_on_fork :: whether the session automatically closes when the process is fork (defaults to <tt>false</tt>).
  102. # it only works if the session is persistent (and ruby 3.1 or higher is used).
  103. #
  104. # This list of options are enhanced with each loaded plugin, see the plugin docs for details.
  105. 30 def initialize(options = EMPTY_HASH)
  106. 6482 options_names = self.class.options_names
  107. 1286 defaults =
  108. 5196 case options
  109. when Options
  110. 4718 unknown_options = options.class.options_names - options_names
  111. 4718 raise Error, "unknown option: #{unknown_options.first}" unless unknown_options.empty?
  112. 4718 DEFAULT_OPTIONS.merge(options)
  113. else
  114. 1764 options.each_key do |k|
  115. 12051 raise Error, "unknown option: #{k}" unless options_names.include?(k)
  116. end
  117. 1755 options.empty? ? DEFAULT_OPTIONS : DEFAULT_OPTIONS.merge(options)
  118. end
  119. 6473 options_names.each do |k|
  120. 285351 v = defaults[k]
  121. 285351 if v.nil?
  122. 69992 instance_variable_set(:"@#{k}", v)
  123. 69992 next
  124. end
  125. 215359 value = __send__(:"option_#{k}", v)
  126. 215315 instance_variable_set(:"@#{k}", value)
  127. end
  128. 6429 do_initialize
  129. 6429 freeze
  130. end
  131. # returns the class with which to instantiate the DNS resolver.
  132. 30 def resolver_class
  133. 18366 case @resolver_class
  134. when Symbol
  135. 15882 public_send(:"resolver_#{@resolver_class}_class")
  136. else
  137. 4255 @resolver_class
  138. end
  139. end
  140. 30 def resolver_cache
  141. 18911 cache_type = @resolver_cache
  142. 17138 case cache_type
  143. when :memory
  144. 14868 Resolver::Cache::Memory.cache(cache_type)
  145. when :file
  146. Resolver::Cache::File.cache(cache_type)
  147. else
  148. 4043 unless cache_type.respond_to?(:resolve) &&
  149. cache_type.respond_to?(:get) &&
  150. cache_type.respond_to?(:set) &&
  151. cache_type.respond_to?(:evict)
  152. raise TypeError, ":resolver_cache must be a compatible resolver cache and implement #get, #set and #evict"
  153. end
  154. 4043 cache_type #: Object & Resolver::_Cache
  155. end
  156. end
  157. 30 def freeze
  158. 17089 self.class.options_names.each do |ivar|
  159. # avoid freezing debug option, as when it's set, it's usually an
  160. # object which cannot be frozen, like stderr or stdout. It's a
  161. # documented exception then, and still does not defeat the purpose
  162. # here, which is to make option objects shareable across ractors,
  163. # and in most cases debug should be nil, or one of the objects
  164. # which will eventually be shareable, like STDOUT or STDERR.
  165. 754789 next if ivar == :debug
  166. 737700 instance_variable_get(:"@#{ivar}").freeze
  167. end
  168. 17089 super
  169. end
  170. 30 REQUEST_BODY_IVARS = %i[@headers].freeze
  171. 30 def ==(other)
  172. 2403 super || options_equals?(other)
  173. end
  174. # checks whether +other+ is equal by comparing the session options
  175. 30 def options_equals?(other, ignore_ivars = REQUEST_BODY_IVARS)
  176. # headers and other request options do not play a role, as they are
  177. # relevant only for the request.
  178. 571 ivars = instance_variables - ignore_ivars
  179. 571 other_ivars = other.instance_variables - ignore_ivars
  180. 571 return false if ivars.size != other_ivars.size
  181. 571 return false if ivars.sort != other_ivars.sort
  182. 571 ivars.all? do |ivar|
  183. 23365 instance_variable_get(ivar) == other.instance_variable_get(ivar)
  184. end
  185. end
  186. # returns a HTTPX::Options instance resulting of the merging of +other+ with self.
  187. # it may return self if +other+ is self or equal to self.
  188. 30 def merge(other)
  189. 45520 if (is_options = other.is_a?(Options))
  190. 13810 return self if eql?(other)
  191. 3756 opts_names = other.class.options_names
  192. 125426 return self if opts_names.all? { |opt| public_send(opt) == other.public_send(opt) }
  193. 3485 other_opts = opts_names
  194. else
  195. 31710 other_opts = other # : Hash[Symbol, untyped]
  196. 31710 other_opts = Hash[other] unless other.is_a?(Hash)
  197. 31702 return self if other_opts.empty?
  198. 30229 return self if other_opts.all? { |opt, v| !respond_to?(opt) || public_send(opt) == v }
  199. end
  200. 17158 opts = dup
  201. 17158 other_opts.each do |opt, v|
  202. 182107 next unless respond_to?(opt)
  203. 182107 v = other.public_send(opt) if is_options
  204. 182107 ivar = :"@#{opt}"
  205. 182107 unless v
  206. 47854 opts.instance_variable_set(ivar, v)
  207. 47854 next
  208. end
  209. 134253 v = opts.__send__(:"option_#{opt}", v)
  210. 134235 orig_v = public_send(opt)
  211. 134235 v = orig_v.merge(v) if orig_v.respond_to?(:merge) && v.respond_to?(:merge)
  212. 134235 opts.instance_variable_set(ivar, v)
  213. end
  214. 17140 opts
  215. end
  216. 30 def to_hash
  217. 5243 instance_variables.each_with_object({}) do |ivar, hs|
  218. 221474 val = instance_variable_get(ivar)
  219. 221474 next if val.nil?
  220. 158023 hs[ivar[1..-1].to_sym] = val
  221. end
  222. end
  223. 30 def extend_with_plugin_classes(pl)
  224. # extend request class
  225. 10612 if defined?(pl::RequestMethods) || defined?(pl::RequestClassMethods)
  226. 3925 @request_class = @request_class.dup
  227. 3925 SET_TEMPORARY_NAME[@request_class, pl]
  228. 3925 @request_class.__send__(:include, pl::RequestMethods) if defined?(pl::RequestMethods)
  229. 3925 @request_class.extend(pl::RequestClassMethods) if defined?(pl::RequestClassMethods)
  230. end
  231. # extend response class
  232. 10612 if defined?(pl::ResponseMethods) || defined?(pl::ResponseClassMethods)
  233. 2923 @response_class = @response_class.dup
  234. 2923 SET_TEMPORARY_NAME[@response_class, pl]
  235. 2923 @response_class.__send__(:include, pl::ResponseMethods) if defined?(pl::ResponseMethods)
  236. 2923 @response_class.extend(pl::ResponseClassMethods) if defined?(pl::ResponseClassMethods)
  237. end
  238. # extend headers class
  239. 10612 if defined?(pl::HeadersMethods) || defined?(pl::HeadersClassMethods)
  240. 180 @headers_class = @headers_class.dup
  241. 180 SET_TEMPORARY_NAME[@headers_class, pl]
  242. 180 @headers_class.__send__(:include, pl::HeadersMethods) if defined?(pl::HeadersMethods)
  243. 180 @headers_class.extend(pl::HeadersClassMethods) if defined?(pl::HeadersClassMethods)
  244. end
  245. # extend request body class
  246. 10612 if defined?(pl::RequestBodyMethods) || defined?(pl::RequestBodyClassMethods)
  247. 432 @request_body_class = @request_body_class.dup
  248. 432 SET_TEMPORARY_NAME[@request_body_class, pl]
  249. 432 @request_body_class.__send__(:include, pl::RequestBodyMethods) if defined?(pl::RequestBodyMethods)
  250. 432 @request_body_class.extend(pl::RequestBodyClassMethods) if defined?(pl::RequestBodyClassMethods)
  251. end
  252. # extend response body class
  253. 10612 if defined?(pl::ResponseBodyMethods) || defined?(pl::ResponseBodyClassMethods)
  254. 1253 @response_body_class = @response_body_class.dup
  255. 1253 SET_TEMPORARY_NAME[@response_body_class, pl]
  256. 1253 @response_body_class.__send__(:include, pl::ResponseBodyMethods) if defined?(pl::ResponseBodyMethods)
  257. 1253 @response_body_class.extend(pl::ResponseBodyClassMethods) if defined?(pl::ResponseBodyClassMethods)
  258. end
  259. # extend connection pool class
  260. 10612 if defined?(pl::PoolMethods)
  261. 926 @pool_class = @pool_class.dup
  262. 926 SET_TEMPORARY_NAME[@pool_class, pl]
  263. 926 @pool_class.__send__(:include, pl::PoolMethods)
  264. end
  265. # extend connection class
  266. 10612 if defined?(pl::ConnectionMethods)
  267. 4579 @connection_class = @connection_class.dup
  268. 4579 SET_TEMPORARY_NAME[@connection_class, pl]
  269. 4579 @connection_class.__send__(:include, pl::ConnectionMethods)
  270. end
  271. # extend http1 class
  272. 10612 if defined?(pl::HTTP1Methods)
  273. 633 @http1_class = @http1_class.dup
  274. 633 SET_TEMPORARY_NAME[@http1_class, pl]
  275. 633 @http1_class.__send__(:include, pl::HTTP1Methods)
  276. end
  277. # extend http2 class
  278. 10612 if defined?(pl::HTTP2Methods)
  279. 696 @http2_class = @http2_class.dup
  280. 696 SET_TEMPORARY_NAME[@http2_class, pl]
  281. 696 @http2_class.__send__(:include, pl::HTTP2Methods)
  282. end
  283. # extend native resolver class
  284. 10612 if defined?(pl::ResolverNativeMethods)
  285. 1045 @resolver_native_class = @resolver_native_class.dup
  286. 1045 SET_TEMPORARY_NAME[@resolver_native_class, pl]
  287. 1045 @resolver_native_class.__send__(:include, pl::ResolverNativeMethods)
  288. end
  289. # extend system resolver class
  290. 10612 if defined?(pl::ResolverSystemMethods)
  291. 123 @resolver_system_class = @resolver_system_class.dup
  292. 123 SET_TEMPORARY_NAME[@resolver_system_class, pl]
  293. 123 @resolver_system_class.__send__(:include, pl::ResolverSystemMethods)
  294. end
  295. # extend https resolver class
  296. 10612 if defined?(pl::ResolverHTTPSMethods)
  297. 123 @resolver_https_class = @resolver_https_class.dup
  298. 123 SET_TEMPORARY_NAME[@resolver_https_class, pl]
  299. 123 @resolver_https_class.__send__(:include, pl::ResolverHTTPSMethods)
  300. end
  301. 10612 return unless defined?(pl::OptionsMethods)
  302. # extend option class
  303. # works around lack of initialize_dup callback
  304. 4718 @options_class = @options_class.dup
  305. # (self.class.options_names)
  306. 4718 @options_class.__send__(:include, pl::OptionsMethods)
  307. end
  308. 30 private
  309. # number options
  310. 30 %i[
  311. max_concurrent_requests max_requests window_size buffer_size
  312. body_threshold_size debug_level
  313. ].each do |option|
  314. 180 class_eval(<<-OUT, __FILE__, __LINE__ + 1)
  315. 6 # converts +v+ into an Integer before setting the +#{option}+ option.
  316. 6 private def option_#{option}(value) # private def option_max_requests(v)
  317. value = Integer(value) unless value.respond_to?(:infinite?) && value.infinite?
  318. 6 raise TypeError, ":#{option} must be positive" unless value.positive? # raise TypeError, ":max_requests must be positive" unless value.positive?
  319. value
  320. end
  321. OUT
  322. end
  323. # hashable options
  324. 30 %i[ssl http2_settings resolver_options pool_options].each do |option|
  325. 120 class_eval(<<-OUT, __FILE__, __LINE__ + 1)
  326. 4 # converts +v+ into an Hash before setting the +#{option}+ option.
  327. 4 private def option_#{option}(value) # def option_ssl(v)
  328. Hash[value]
  329. end
  330. OUT
  331. end
  332. 30 %i[
  333. request_class response_class headers_class request_body_class
  334. response_body_class connection_class http1_class http2_class
  335. resolver_native_class resolver_system_class resolver_https_class options_class pool_class
  336. io fallback_protocol debug debug_redact
  337. compress_request_body decompress_response_body
  338. persistent close_on_fork
  339. ].each do |method_name|
  340. 630 class_eval(<<-OUT, __FILE__, __LINE__ + 1)
  341. 21 # sets +v+ as the value of the +#{method_name}+ option
  342. 21 private def option_#{method_name}(v); v; end # private def option_smth(v); v; end
  343. OUT
  344. end
  345. 30 def option_origin(value)
  346. 696 URI(value)
  347. end
  348. 30 def option_base_path(value)
  349. 36 String(value)
  350. end
  351. 30 def option_headers(value)
  352. 10670 value = value.dup if value.frozen?
  353. 10670 headers_class.new(value)
  354. end
  355. 30 def option_timeout(value)
  356. 12054 timeout_hash = Hash[value]
  357. 12054 default_timeouts = DEFAULT_OPTIONS[:timeout]
  358. # Validate keys and values
  359. 12054 timeout_hash.each do |key, val|
  360. 82774 raise TypeError, "invalid timeout: :#{key}" unless default_timeouts.key?(key)
  361. 82765 next if val.nil?
  362. 63536 raise TypeError, ":#{key} must be numeric" unless val.is_a?(Numeric)
  363. end
  364. 12036 timeout_hash
  365. end
  366. 30 def option_supported_compression_formats(value)
  367. 10130 Array(value).map(&:to_s)
  368. end
  369. 30 def option_transport(value)
  370. 56 transport = value.to_s
  371. 56 raise TypeError, "#{transport} is an unsupported transport type" unless %w[unix].include?(transport)
  372. 56 transport
  373. end
  374. 30 def option_addresses(value)
  375. 105 Array(value).map { |entry| Resolver::Entry.convert(entry) }
  376. end
  377. 30 def option_ip_families(value)
  378. 210 Array(value)
  379. end
  380. 30 def option_resolver_class(resolver_type)
  381. 9665 case resolver_type
  382. when Symbol
  383. 6923 meth = :"resolver_#{resolver_type}_class"
  384. 6923 raise TypeError, ":resolver_class must be a supported type" unless respond_to?(meth)
  385. 6914 resolver_type
  386. when Class
  387. 3704 raise TypeError, ":resolver_class must be a subclass of `#{Resolver::Resolver}`" unless resolver_type < Resolver::Resolver
  388. 3696 resolver_type
  389. else
  390. raise TypeError, ":resolver_class must be a supported type"
  391. end
  392. end
  393. 30 def option_resolver_cache(cache_type)
  394. 10086 if cache_type.is_a?(Symbol)
  395. 6475 raise TypeError, ":resolver_cache: #{cache_type} is invalid" unless RESOLVER_TYPES.include?(cache_type)
  396. 6475 require "httpx/resolver/cache/file" if cache_type == :file
  397. else
  398. 3611 unless cache_type.respond_to?(:resolve) &&
  399. cache_type.respond_to?(:get) &&
  400. cache_type.respond_to?(:set) &&
  401. cache_type.respond_to?(:evict)
  402. raise TypeError, ":resolver_cache must be a compatible resolver cache and implement #resolve, #get, #set and #evict"
  403. end
  404. end
  405. 10086 cache_type
  406. end
  407. # called after all options are initialized
  408. 30 def do_initialize
  409. 6429 hs = @headers
  410. # initialized default request headers
  411. 6429 hs["user-agent"] = USER_AGENT unless hs.key?("user-agent")
  412. 6429 hs["accept"] = "*/*" unless hs.key?("accept")
  413. 6429 if hs.key?("range")
  414. 9 hs.delete("accept-encoding")
  415. else
  416. 6420 hs["accept-encoding"] = supported_compression_formats unless hs.key?("accept-encoding")
  417. end
  418. end
  419. 30 def access_option(obj, k, ivar_map)
  420. case obj
  421. when Hash
  422. obj[ivar_map[k]]
  423. else
  424. obj.instance_variable_get(k)
  425. end
  426. end
  427. # rubocop:disable Lint/UselessConstantScoping
  428. # these really need to be defined at the end of the class
  429. 30 SET_TEMPORARY_NAME = ->(klass, pl = nil) do
  430. 17806 if klass.respond_to?(:set_temporary_name) # ruby 3.4 only
  431. 8041 name = klass.name || "#{klass.superclass.name}(plugin)"
  432. 8041 name = "#{name}/#{pl}" if pl
  433. 8041 klass.set_temporary_name(name)
  434. end
  435. end
  436. 2 DEFAULT_OPTIONS = {
  437. 28 :max_requests => Float::INFINITY,
  438. :debug => nil,
  439. 30 :debug_level => (ENV["HTTPX_DEBUG"] || 1).to_i,
  440. :debug_redact => ENV.key?("HTTPX_DEBUG_REDACT"),
  441. :ssl => EMPTY_HASH,
  442. :http2_settings => { settings_enable_push: 0 }.freeze,
  443. :fallback_protocol => "http/1.1",
  444. :supported_compression_formats => %w[gzip deflate],
  445. :decompress_response_body => true,
  446. :compress_request_body => true,
  447. :timeout => {
  448. connect_timeout: CONNECT_TIMEOUT,
  449. settings_timeout: SETTINGS_TIMEOUT,
  450. close_handshake_timeout: CLOSE_HANDSHAKE_TIMEOUT,
  451. operation_timeout: OPERATION_TIMEOUT,
  452. keep_alive_timeout: KEEP_ALIVE_TIMEOUT,
  453. read_timeout: READ_TIMEOUT,
  454. write_timeout: WRITE_TIMEOUT,
  455. request_timeout: REQUEST_TIMEOUT,
  456. }.freeze,
  457. :headers_class => Class.new(Headers, &SET_TEMPORARY_NAME),
  458. :headers => EMPTY_HASH,
  459. :window_size => WINDOW_SIZE,
  460. :buffer_size => BUFFER_SIZE,
  461. :body_threshold_size => MAX_BODY_THRESHOLD_SIZE,
  462. :request_class => Class.new(Request, &SET_TEMPORARY_NAME),
  463. :response_class => Class.new(Response, &SET_TEMPORARY_NAME),
  464. :request_body_class => Class.new(Request::Body, &SET_TEMPORARY_NAME),
  465. :response_body_class => Class.new(Response::Body, &SET_TEMPORARY_NAME),
  466. :pool_class => Class.new(Pool, &SET_TEMPORARY_NAME),
  467. :connection_class => Class.new(Connection, &SET_TEMPORARY_NAME),
  468. :http1_class => Class.new(Connection::HTTP1, &SET_TEMPORARY_NAME),
  469. :http2_class => Class.new(Connection::HTTP2, &SET_TEMPORARY_NAME),
  470. :resolver_native_class => Class.new(Resolver::Native, &SET_TEMPORARY_NAME),
  471. :resolver_system_class => Class.new(Resolver::System, &SET_TEMPORARY_NAME),
  472. :resolver_https_class => Class.new(Resolver::HTTPS, &SET_TEMPORARY_NAME),
  473. :options_class => Class.new(self, &SET_TEMPORARY_NAME),
  474. :transport => nil,
  475. :addresses => nil,
  476. :persistent => false,
  477. 30 :resolver_class => (ENV["HTTPX_RESOLVER"] || :native).to_sym,
  478. 30 :resolver_cache => (ENV["HTTPX_RESOLVER_CACHE"] || :memory).to_sym,
  479. :resolver_options => { cache: true }.freeze,
  480. :pool_options => EMPTY_HASH,
  481. :ip_families => nil,
  482. :close_on_fork => false,
  483. }.each_value(&:freeze).freeze
  484. # rubocop:enable Lint/UselessConstantScoping
  485. end
  486. end

lib/httpx/parser/http1.rb

100.0% lines covered

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

lib/httpx/plugins/auth.rb

100.0% lines covered

52 relevant lines. 52 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module HTTPX
  3. 9 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. 9 module Auth
  12. 9 def self.subplugins
  13. 162 {
  14. 1299 retries: AuthRetries,
  15. }
  16. end
  17. # adds support for the following options:
  18. #
  19. # :auth_header_value :: the token to use as a string, or a callable which returns a string when called.
  20. # :auth_header_type :: the authentication type to use in the "authorization" header value (i.e. "Bearer", "Digest"...)
  21. # :generate_auth_value_on_retry :: callable which returns whether the request should regenerate the auth_header_value
  22. # when the request is retried (this option will only work if the session also loads the
  23. # <tt>:retries</tt> plugin).
  24. 9 module OptionsMethods
  25. 9 def option_auth_header_value(value)
  26. 504 value
  27. end
  28. 9 def option_auth_header_type(value)
  29. 504 value
  30. end
  31. 9 def option_generate_auth_value_on_retry(value)
  32. 54 raise TypeError, "`:generate_auth_value_on_retry` must be a callable" unless value.respond_to?(:call)
  33. 54 value
  34. end
  35. end
  36. 9 module InstanceMethods
  37. 9 def initialize(*)
  38. 1590 super
  39. 1590 @auth_header_value = nil
  40. 1590 @skip_auth_header_value = false
  41. end
  42. 9 def authorization(token = nil, auth_header_type: nil, &blk)
  43. 252 with(auth_header_type: auth_header_type, auth_header_value: token || blk)
  44. end
  45. 9 def bearer_auth(token = nil, &blk)
  46. 18 authorization(token, auth_header_type: "Bearer", &blk)
  47. end
  48. 9 def skip_auth_header
  49. 144 @skip_auth_header_value = true
  50. 144 yield
  51. ensure
  52. 144 @skip_auth_header_value = false
  53. end
  54. 9 def reset_auth_header_value!
  55. 18 @auth_header_value = nil
  56. end
  57. 9 private
  58. 9 def send_request(request, *)
  59. 1396 return super if @skip_auth_header_value
  60. 1252 @auth_header_value ||= generate_auth_token
  61. 1252 request.authorize(@auth_header_value) if @auth_header_value
  62. 1252 super
  63. end
  64. 9 def generate_auth_token
  65. 676 return unless (auth_value = @options.auth_header_value)
  66. 288 auth_value = auth_value.call(self) if auth_value.respond_to?(:call)
  67. 288 auth_value
  68. end
  69. end
  70. 9 module RequestMethods
  71. 9 def authorize(auth_value)
  72. 1032 if (auth_type = @options.auth_header_type)
  73. 72 auth_value = "#{auth_type} #{auth_value}"
  74. end
  75. 1032 @headers.add("authorization", auth_value)
  76. end
  77. end
  78. 9 module AuthRetries
  79. 9 module InstanceMethods
  80. 9 def prepare_to_retry(request, response)
  81. 36 super
  82. 36 return unless @options.generate_auth_value_on_retry && @options.generate_auth_value_on_retry.call(response)
  83. 36 request.headers.get("authorization").pop
  84. 36 @auth_header_value = generate_auth_token
  85. end
  86. end
  87. end
  88. end
  89. 9 register_plugin :auth, Auth
  90. end
  91. 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. 10 require "httpx/base64"
  3. 10 module HTTPX
  4. 10 module Plugins
  5. 10 module Authentication
  6. 10 class Basic
  7. 10 def initialize(user, password, **)
  8. 362 @user = user
  9. 362 @password = password
  10. end
  11. 10 def authenticate(*)
  12. 341 "Basic #{Base64.strict_encode64("#{@user}:#{@password}")}"
  13. end
  14. end
  15. end
  16. end
  17. end

lib/httpx/plugins/auth/digest.rb

98.8% lines covered

83 relevant lines. 82 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 require "time"
  3. 9 require "securerandom"
  4. 9 require "digest"
  5. 9 module HTTPX
  6. 9 module Plugins
  7. 9 module Authentication
  8. 9 class Digest
  9. 9 Error = Class.new(Error)
  10. 9 def initialize(user, password, hashed: false, **)
  11. 198 @user = user
  12. 198 @password = password
  13. 198 @nonce = 0
  14. 198 @hashed = hashed
  15. end
  16. 9 def can_authenticate?(authenticate)
  17. 180 authenticate && /Digest .*/.match?(authenticate)
  18. end
  19. 9 def authenticate(request, authenticate)
  20. 180 "Digest #{generate_header(request.verb, request.path, authenticate)}"
  21. end
  22. 9 private
  23. 9 def generate_header(meth, uri, authenticate)
  24. # discard first token, it's Digest
  25. 180 auth_info = authenticate[/^(\w+) (.*)/, 2]
  26. 180 raise_format_error unless auth_info
  27. 180 s = StringScanner.new(auth_info)
  28. 180 params = {}
  29. 284 until s.eos?
  30. 936 k = s.scan_until(/=/)
  31. 936 raise_format_error unless k&.end_with?("=")
  32. 936 if s.peek(1) == "\""
  33. 720 s.skip("\"")
  34. 720 v = s.scan_until(/"/)
  35. 720 raise_format_error unless v&.end_with?("\"")
  36. 720 v = v[0..-2]
  37. 720 s.skip_until(/,/)
  38. else
  39. 216 v = s.scan_until(/,|$/)
  40. 216 if v&.end_with?(",")
  41. 142 v = v[0..-2]
  42. else
  43. 74 raise_format_error unless s.eos?
  44. end
  45. 216 v = v[0..-2] if v&.end_with?(",")
  46. end
  47. 832 params[k[0..-2]] = v
  48. 936 s.skip(/\s/)
  49. end
  50. 180 nonce = params["nonce"]
  51. 180 nc = next_nonce
  52. # verify qop
  53. 180 qop = params["qop"]
  54. 180 if qop
  55. # some servers send multiple values wrapped in parentheses (i.e. "(qauth,)")
  56. 180 qop = qop[/\(?([^)]+)\)?/, 1]
  57. 360 qop = qop.split(",").map { |s| s.delete_prefix("'").delete_suffix("'") }.delete_if(&:empty?).map.first
  58. end
  59. 180 if params["algorithm"] =~ /(.*?)(-sess)?$/
  60. 162 alg = Regexp.last_match(1)
  61. 162 algorithm = ::Digest.const_get(alg)
  62. 162 raise Error, "unknown algorithm \"#{alg}\"" unless algorithm
  63. 162 sess = Regexp.last_match(2)
  64. else
  65. 18 algorithm = ::Digest::MD5
  66. end
  67. 180 if qop || sess
  68. 180 cnonce = make_cnonce
  69. 180 nc = format("%<nonce>08x", nonce: nc)
  70. end
  71. 180 a1 = if sess
  72. 4 [
  73. 36 (@hashed ? @password : algorithm.hexdigest("#{@user}:#{params["realm"]}:#{@password}")),
  74. nonce,
  75. cnonce,
  76. 3 ].join ":"
  77. else
  78. 144 @hashed ? @password : "#{@user}:#{params["realm"]}:#{@password}"
  79. end
  80. 180 ha1 = algorithm.hexdigest(a1)
  81. 180 ha2 = algorithm.hexdigest("#{meth}:#{uri}")
  82. 180 request_digest = [ha1, nonce]
  83. 180 request_digest.push(nc, cnonce, qop) if qop
  84. 180 request_digest << ha2
  85. 180 request_digest = request_digest.join(":")
  86. 40 header = [
  87. 160 %(username="#{@user}"),
  88. 20 %(nonce="#{nonce}"),
  89. 20 %(uri="#{uri}"),
  90. 20 %(response="#{algorithm.hexdigest(request_digest)}"),
  91. ]
  92. 180 header << %(realm="#{params["realm"]}") if params.key?("realm")
  93. 180 header << %(algorithm=#{params["algorithm"]}) if params.key?("algorithm")
  94. 180 header << %(cnonce="#{cnonce}") if cnonce
  95. 180 header << %(nc=#{nc})
  96. 180 header << %(qop=#{qop}) if qop
  97. 180 header << %(opaque="#{params["opaque"]}") if params.key?("opaque")
  98. 180 header.join ", "
  99. end
  100. 9 def make_cnonce
  101. 200 ::Digest::MD5.hexdigest [
  102. Time.now.to_i,
  103. Process.pid,
  104. SecureRandom.random_number(2**32),
  105. ].join ":"
  106. end
  107. 9 def next_nonce
  108. 160 @nonce += 1
  109. end
  110. 9 def raise_format_error
  111. raise Error, "unsupported digest header format"
  112. end
  113. end
  114. end
  115. end
  116. 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. 11 module HTTPX
  3. 11 module Plugins
  4. 11 module Authentication
  5. 11 class Socks5
  6. 11 def initialize(user, password, **)
  7. 54 @user = user
  8. 54 @password = password
  9. end
  10. 11 def can_authenticate?(*)
  11. 54 @user && @password
  12. end
  13. 11 def authenticate(*)
  14. 54 [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. 9 module HTTPX
  3. 9 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. 9 module AwsSdkAuthentication
  10. # Mock configuration, to be used only when resolving credentials
  11. 9 class Configuration
  12. 9 attr_reader :profile
  13. 9 def initialize(profile)
  14. 36 @profile = profile
  15. end
  16. 9 def respond_to_missing?(*)
  17. 18 true
  18. end
  19. 9 def method_missing(*); end
  20. end
  21. #
  22. # encapsulates access to an AWS SDK credentials store.
  23. #
  24. 9 class Credentials
  25. 9 def initialize(aws_credentials)
  26. 18 @aws_credentials = aws_credentials
  27. end
  28. 9 def username
  29. 18 @aws_credentials.access_key_id
  30. end
  31. 9 def password
  32. 18 @aws_credentials.secret_access_key
  33. end
  34. 9 def security_token
  35. 18 @aws_credentials.session_token
  36. end
  37. end
  38. 9 class << self
  39. 9 def load_dependencies(_klass)
  40. 18 require "aws-sdk-core"
  41. end
  42. 9 def configure(klass)
  43. 18 klass.plugin(:aws_sigv4)
  44. end
  45. 9 def extra_options(options)
  46. 18 options.merge(max_concurrent_requests: 1)
  47. end
  48. 9 def credentials(profile)
  49. 18 mock_configuration = Configuration.new(profile)
  50. 18 Credentials.new(Aws::CredentialProviderChain.new(mock_configuration).resolve)
  51. end
  52. 9 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. 18 keys = %w[AWS_REGION AMAZON_REGION AWS_DEFAULT_REGION]
  55. 18 env_region = ENV.values_at(*keys).compact.first
  56. 18 env_region = nil if env_region == ""
  57. 18 cfg_region = Aws.shared_config.region(profile: profile)
  58. 18 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. 9 module OptionsMethods
  65. 9 private
  66. 9 def option_aws_profile(value)
  67. 90 String(value)
  68. end
  69. end
  70. 9 module InstanceMethods
  71. #
  72. # aws_authentication
  73. # aws_authentication(credentials: Aws::Credentials.new('akid', 'secret'))
  74. # aws_authentication()
  75. #
  76. 9 def aws_sdk_authentication(
  77. credentials: AwsSdkAuthentication.credentials(@options.aws_profile),
  78. region: AwsSdkAuthentication.region(@options.aws_profile),
  79. **options
  80. )
  81. 18 aws_sigv4_authentication(
  82. credentials: credentials,
  83. region: region,
  84. provider_prefix: "aws",
  85. header_provider_field: "amz",
  86. **options
  87. )
  88. end
  89. 9 alias_method :aws_auth, :aws_sdk_authentication
  90. end
  91. end
  92. 9 register_plugin :aws_sdk_authentication, AwsSdkAuthentication
  93. end
  94. end

lib/httpx/plugins/aws_sigv4.rb

100.0% lines covered

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

lib/httpx/plugins/callbacks.rb

92.65% lines covered

68 relevant lines. 63 lines covered and 5 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 module HTTPX
  3. 30 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. 30 module Callbacks
  10. 30 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. 30 class CallbackError < Exception; end # rubocop:disable Lint/InheritException
  20. 30 module InstanceMethods
  21. 30 include HTTPX::Callbacks
  22. 30 CALLBACKS.each do |meth|
  23. 270 class_eval(<<-MOD, __FILE__, __LINE__ + 1)
  24. 9 def on_#{meth}(&blk) # def on_connection_opened(&blk)
  25. 9 on(:#{meth}, &blk) # on(:connection_opened, &blk)
  26. self # self
  27. end # end
  28. MOD
  29. end
  30. 30 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. 30 private
  40. 30 def branch(options, &blk)
  41. 36 super(options).tap do |sess|
  42. 36 CALLBACKS.each do |cb|
  43. 324 next unless callbacks_for?(cb)
  44. 18 sess.callbacks(cb).concat(callbacks(cb))
  45. end
  46. 36 sess.wrap(&blk) if blk
  47. end
  48. end
  49. 30 def do_init_connection(connection, selector)
  50. 254 super
  51. 254 connection.on(:open) do
  52. 219 next unless connection.current_session == self
  53. 219 emit_or_callback_error(:connection_opened, connection.origin, connection.io.socket)
  54. end
  55. 254 connection.on(:callback_connection_closed) do
  56. 256 next unless connection.current_session == self
  57. 256 emit_or_callback_error(:connection_closed, connection.origin) if connection.used?
  58. end
  59. 254 connection
  60. end
  61. 30 def set_request_callbacks(request)
  62. 255 super
  63. 255 request.on(:headers) do
  64. 201 emit_or_callback_error(:request_started, request)
  65. end
  66. 255 request.on(:body_chunk) do |chunk|
  67. 18 emit_or_callback_error(:request_body_chunk, request, chunk)
  68. end
  69. 255 request.on(:done) do
  70. 183 emit_or_callback_error(:request_completed, request)
  71. end
  72. 255 request.on(:response_started) do |res|
  73. 201 if res.is_a?(Response)
  74. 165 emit_or_callback_error(:response_started, request, res)
  75. 147 res.on(:chunk_received) do |chunk|
  76. 188 emit_or_callback_error(:response_body_chunk, request, res, chunk)
  77. end
  78. else
  79. 36 emit_or_callback_error(:request_error, request, res.error)
  80. end
  81. end
  82. 255 request.on(:response) do |res|
  83. 147 emit_or_callback_error(:response_completed, request, res) if res.is_a?(Response)
  84. end
  85. end
  86. 30 def emit_or_callback_error(*args)
  87. 1367 emit(*args)
  88. rescue StandardError => e
  89. 153 ex = CallbackError.new(e.message)
  90. 153 ex.set_backtrace(e.backtrace)
  91. 153 raise ex
  92. end
  93. 30 def receive_requests(*)
  94. 255 super
  95. rescue CallbackError => e
  96. 135 raise e.cause
  97. end
  98. 30 def close(*)
  99. 253 super
  100. rescue CallbackError => e
  101. 9 raise e.cause
  102. end
  103. end
  104. 30 module ConnectionMethods
  105. 30 private
  106. 30 def disconnect
  107. 301 return if @exhausted
  108. 301 return unless @current_session && @current_selector
  109. 256 emit(:callback_connection_closed)
  110. 229 super
  111. end
  112. end
  113. end
  114. 30 register_plugin :callbacks, Callbacks
  115. end
  116. end

lib/httpx/plugins/circuit_breaker.rb

100.0% lines covered

67 relevant lines. 67 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module HTTPX
  3. 9 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. 9 module CircuitBreaker
  10. 9 using URIExtensions
  11. 9 def self.load_dependencies(*)
  12. 63 require_relative "circuit_breaker/circuit"
  13. 63 require_relative "circuit_breaker/circuit_store"
  14. end
  15. 9 def self.extra_options(options)
  16. 63 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. 9 module InstanceMethods
  24. 9 include HTTPX::Callbacks
  25. 9 def initialize(*)
  26. 63 super
  27. 63 @circuit_store = CircuitStore.new(@options)
  28. end
  29. 9 %i[circuit_open].each do |meth|
  30. 9 class_eval(<<-MOD, __FILE__, __LINE__ + 1)
  31. 1 def on_#{meth}(&blk) # def on_circuit_open(&blk)
  32. 1 on(:#{meth}, &blk) # on(:circuit_open, &blk)
  33. self # self
  34. end # end
  35. MOD
  36. end
  37. 9 private
  38. 9 def send_requests(*requests)
  39. # @type var short_circuit_responses: Array[response]
  40. 252 short_circuit_responses = []
  41. # run all requests through the circuit breaker, see if the circuit is
  42. # open for any of them.
  43. 252 real_requests = requests.each_with_index.with_object([]) do |(req, idx), real_reqs|
  44. 252 short_circuit_response = @circuit_store.try_respond(req)
  45. 252 if short_circuit_response.nil?
  46. 198 real_reqs << req
  47. 198 next
  48. end
  49. 48 short_circuit_responses[idx] = short_circuit_response
  50. end
  51. # run requests for the remainder
  52. 252 unless real_requests.empty?
  53. 198 responses = super(*real_requests)
  54. 198 real_requests.each_with_index do |request, idx|
  55. 176 short_circuit_responses[requests.index(request)] = responses[idx]
  56. end
  57. end
  58. 252 short_circuit_responses
  59. end
  60. 9 def set_request_callbacks(request)
  61. 252 super
  62. 252 request.on(:response) do |response|
  63. 198 emit(:circuit_open, request) if try_circuit_open(request, response)
  64. end
  65. end
  66. 9 def try_circuit_open(request, response)
  67. 198 if response.is_a?(ErrorResponse)
  68. 128 case response.error
  69. when RequestTimeoutError
  70. 90 @circuit_store.try_open(request.uri, response)
  71. else
  72. 54 @circuit_store.try_open(request.origin, response)
  73. end
  74. 54 elsif (break_on = request.options.circuit_breaker_break_on) && break_on.call(response)
  75. 18 @circuit_store.try_open(request.uri, response)
  76. else
  77. 36 @circuit_store.try_close(request.uri)
  78. 16 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. 9 module OptionsMethods
  93. 9 private
  94. 9 def option_circuit_breaker_max_attempts(value)
  95. 126 attempts = Integer(value)
  96. 126 raise TypeError, ":circuit_breaker_max_attempts must be positive" unless attempts.positive?
  97. 126 attempts
  98. end
  99. 9 def option_circuit_breaker_reset_attempts_in(value)
  100. 72 timeout = Float(value)
  101. 72 raise TypeError, ":circuit_breaker_reset_attempts_in must be positive" unless timeout.positive?
  102. 72 timeout
  103. end
  104. 9 def option_circuit_breaker_break_in(value)
  105. 99 timeout = Float(value)
  106. 99 raise TypeError, ":circuit_breaker_break_in must be positive" unless timeout.positive?
  107. 99 timeout
  108. end
  109. 9 def option_circuit_breaker_half_open_drip_rate(value)
  110. 99 ratio = Float(value)
  111. 99 raise TypeError, ":circuit_breaker_half_open_drip_rate must be a number between 0 and 1" unless (0..1).cover?(ratio)
  112. 99 ratio
  113. end
  114. 9 def option_circuit_breaker_break_on(value)
  115. 18 raise TypeError, ":circuit_breaker_break_on must be called with the response" unless value.respond_to?(:call)
  116. 18 value
  117. end
  118. end
  119. end
  120. 9 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. 9 module HTTPX
  3. 9 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. 9 class Circuit
  13. 9 def initialize(max_attempts, reset_attempts_in, break_in, circuit_breaker_half_open_drip_rate)
  14. 63 @max_attempts = max_attempts
  15. 63 @reset_attempts_in = reset_attempts_in
  16. 63 @break_in = break_in
  17. 63 @circuit_breaker_half_open_drip_rate = circuit_breaker_half_open_drip_rate
  18. 63 @attempts = 0
  19. 63 total_real_attempts = @max_attempts * @circuit_breaker_half_open_drip_rate
  20. 63 @drip_factor = (@max_attempts / total_real_attempts).round
  21. 63 @state = :closed
  22. end
  23. 9 def respond
  24. 252 try_close
  25. 224 case @state
  26. when :closed
  27. 68 nil
  28. when :half_open
  29. 56 @attempts += 1
  30. # do real requests while drip rate valid
  31. 63 if (@real_attempts % @drip_factor).zero?
  32. 40 @real_attempts += 1
  33. 40 return
  34. end
  35. 18 @response
  36. when :open
  37. 36 @response
  38. end
  39. end
  40. 9 def try_open(response)
  41. 144 case @state
  42. when :closed
  43. 135 now = Utils.now
  44. 135 if @attempts.positive?
  45. # reset if error happened long ago
  46. 54 @attempts = 0 if now - @attempted_at > @reset_attempts_in
  47. else
  48. 81 @attempted_at = now
  49. end
  50. 120 @attempts += 1
  51. 135 return unless @attempts >= @max_attempts
  52. 72 @state = :open
  53. 72 @opened_at = now
  54. 72 @response = response
  55. when :half_open
  56. # open immediately
  57. 27 @state = :open
  58. 27 @attempted_at = @opened_at = Utils.now
  59. 27 @response = response
  60. end
  61. end
  62. 9 def try_close
  63. 256 case @state
  64. when :closed
  65. 68 nil
  66. when :half_open
  67. # do not close circuit unless attempts exhausted
  68. 54 return unless @attempts >= @max_attempts
  69. # reset!
  70. 18 @attempts = 0
  71. 18 @opened_at = @attempted_at = @response = nil
  72. 18 @state = :closed
  73. when :open
  74. 81 if Utils.elapsed_time(@opened_at) > @break_in
  75. 45 @state = :half_open
  76. 45 @attempts = 0
  77. 45 @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. 9 module HTTPX::Plugins::CircuitBreaker
  3. 9 using HTTPX::URIExtensions
  4. 9 class CircuitStore
  5. 9 def initialize(options)
  6. 63 @circuits = Hash.new do |h, k|
  7. 56 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. 63 @circuits_mutex = Thread::Mutex.new
  15. end
  16. 9 def try_open(uri, response)
  17. 324 circuit = @circuits_mutex.synchronize { get_circuit_for_uri(uri) }
  18. 162 circuit.try_open(response)
  19. end
  20. 9 def try_close(uri)
  21. 36 circuit = @circuits_mutex.synchronize do
  22. 36 return unless @circuits.key?(uri.origin) || @circuits.key?(uri.to_s)
  23. 36 get_circuit_for_uri(uri)
  24. end
  25. 36 circuit.try_close
  26. end
  27. # if circuit is open, it'll respond with the stored response.
  28. # if not, nil.
  29. 9 def try_respond(request)
  30. 504 circuit = @circuits_mutex.synchronize { get_circuit_for_uri(request.uri) }
  31. 252 circuit.respond
  32. end
  33. 9 private
  34. 9 def get_circuit_for_uri(uri)
  35. 450 if uri.respond_to?(:origin) && @circuits.key?(uri.origin)
  36. 324 @circuits[uri.origin]
  37. else
  38. 126 @circuits[uri.to_s]
  39. end
  40. end
  41. end
  42. end

lib/httpx/plugins/content_digest.rb

100.0% lines covered

103 relevant lines. 103 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module HTTPX
  3. 9 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. 9 module ContentDigest
  11. 9 class Error < HTTPX::Error; end
  12. # Error raised on response "content-digest" header validation.
  13. 9 class ValidationError < Error
  14. 9 attr_reader :response
  15. 9 def initialize(message, response)
  16. 54 super(message)
  17. 54 @response = response
  18. end
  19. end
  20. 9 class MissingContentDigestError < ValidationError; end
  21. 9 class InvalidContentDigestError < ValidationError; end
  22. 2 SUPPORTED_ALGORITHMS = {
  23. 7 "sha-256" => OpenSSL::Digest::SHA256,
  24. "sha-512" => OpenSSL::Digest::SHA512,
  25. }.freeze
  26. 9 class << self
  27. 9 def extra_options(options)
  28. 234 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. 9 module OptionsMethods
  39. 9 private
  40. 9 def option_content_digest_algorithm(value)
  41. 243 raise TypeError, ":content_digest_algorithm must be one of 'sha-256', 'sha-512'" unless SUPPORTED_ALGORITHMS.key?(value)
  42. 243 value
  43. end
  44. 9 def option_encode_content_digest(value)
  45. 234 value
  46. end
  47. 9 def option_validate_content_digest(value)
  48. 162 value
  49. end
  50. end
  51. 9 module ResponseBodyMethods
  52. 9 attr_reader :content_digest_buffer
  53. 9 def initialize(response, options)
  54. 198 super
  55. 198 return unless response.headers.key?("content-digest")
  56. 144 should_validate = options.validate_content_digest
  57. 144 should_validate = should_validate.call(response) if should_validate.respond_to?(:call)
  58. 144 return unless should_validate
  59. 126 @content_digest_buffer = Response::Buffer.new(
  60. threshold_size: @options.body_threshold_size,
  61. bytesize: @length,
  62. encoding: @encoding
  63. )
  64. end
  65. 9 def write(chunk)
  66. 326 @content_digest_buffer.write(chunk) if @content_digest_buffer
  67. 326 super
  68. end
  69. 9 def close
  70. 126 if @content_digest_buffer
  71. 126 @content_digest_buffer.close
  72. 126 @content_digest_buffer = nil
  73. end
  74. 126 super
  75. end
  76. end
  77. 9 module InstanceMethods
  78. 9 def build_request(*)
  79. 252 request = super
  80. 252 return request if request.empty?
  81. 54 return request if request.headers.key?("content-digest")
  82. 54 perform_encoding = @options.encode_content_digest
  83. 54 perform_encoding = perform_encoding.call(request) if perform_encoding.respond_to?(:call)
  84. 54 return request unless perform_encoding
  85. 45 digest = base64digest(request.body)
  86. 45 request.headers.add("content-digest", "#{@options.content_digest_algorithm}=:#{digest}:")
  87. 45 request
  88. end
  89. 9 private
  90. 9 def fetch_response(request, _, _)
  91. 682 response = super
  92. 682 return response unless response.is_a?(Response)
  93. 198 perform_validation = @options.validate_content_digest
  94. 198 perform_validation = perform_validation.call(response) if perform_validation.respond_to?(:call)
  95. 198 validate_content_digest(response) if perform_validation
  96. 144 response
  97. rescue ValidationError => e
  98. 54 ErrorResponse.new(request, e)
  99. end
  100. 9 def validate_content_digest(response)
  101. 144 content_digest_header = response.headers["content-digest"]
  102. 144 raise MissingContentDigestError.new("response is missing a `content-digest` header", response) unless content_digest_header
  103. 126 digests = extract_content_digests(content_digest_header)
  104. 126 included_algorithms = SUPPORTED_ALGORITHMS.keys & digests.keys
  105. 126 raise MissingContentDigestError.new("unsupported algorithms: #{digests.keys.join(", ")}", response) if included_algorithms.empty?
  106. 126 content_buffer = response.body.content_digest_buffer
  107. 126 included_algorithms.each do |algorithm|
  108. 126 digest = SUPPORTED_ALGORITHMS.fetch(algorithm).new
  109. 126 digest_received = digests[algorithm]
  110. 14 digest_computed =
  111. 125 if content_buffer.respond_to?(:to_path)
  112. 18 content_buffer.flush
  113. 18 digest.file(content_buffer.to_path).base64digest
  114. else
  115. 108 digest.base64digest(content_buffer.to_s)
  116. end
  117. 4 raise InvalidContentDigestError.new("#{algorithm} digest does not match content",
  118. 125 response) unless digest_received == digest_computed
  119. end
  120. end
  121. 9 def extract_content_digests(header)
  122. 126 header.split(",").to_h do |entry|
  123. 144 algorithm, digest = entry.split("=", 2)
  124. 144 raise Error, "#{entry} is an invalid digest format" unless algorithm && digest
  125. 144 [algorithm, digest.byteslice(1..-2)]
  126. end
  127. end
  128. 9 def base64digest(body)
  129. 45 digest = SUPPORTED_ALGORITHMS.fetch(@options.content_digest_algorithm).new
  130. 45 if body.respond_to?(:read)
  131. 36 if body.respond_to?(:to_path)
  132. 9 digest.file(body.to_path).base64digest
  133. else
  134. 27 raise ContentDigestError, "request body must be rewindable" unless body.respond_to?(:rewind)
  135. 27 buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
  136. 2 begin
  137. 27 IO.copy_stream(body, buffer)
  138. 27 buffer.flush
  139. 27 digest.file(buffer.to_path).base64digest
  140. ensure
  141. 27 body.rewind
  142. 27 buffer.close
  143. 27 buffer.unlink
  144. end
  145. end
  146. else
  147. 9 raise ContentDigestError, "base64digest for endless enumerators is not supported" if body.unbounded_body?
  148. 9 buffer = "".b
  149. 18 body.each { |chunk| buffer << chunk }
  150. 9 digest.base64digest(buffer)
  151. end
  152. end
  153. end
  154. end
  155. 9 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. 9 require "forwardable"
  3. 9 module HTTPX
  4. 9 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. 9 module Cookies
  13. 9 def self.load_dependencies(*)
  14. 162 require "httpx/plugins/cookies/jar"
  15. 162 require "httpx/plugins/cookies/cookie"
  16. 162 require "httpx/plugins/cookies/set_cookie_parser"
  17. end
  18. 9 module InstanceMethods
  19. 9 extend Forwardable
  20. 9 def_delegator :@options, :cookies
  21. 9 def initialize(options = {}, &blk)
  22. 324 super({ cookies: Jar.new }.merge(options), &blk)
  23. end
  24. 9 def wrap
  25. 18 return super unless block_given?
  26. 18 super do |session|
  27. 18 old_cookies_jar = @options.cookies.dup
  28. 1 begin
  29. 18 yield session
  30. ensure
  31. 18 @options = @options.merge(cookies: old_cookies_jar)
  32. end
  33. end
  34. end
  35. 9 def build_request(*)
  36. 360 request = super
  37. 360 request.headers.set_cookie(request.options.cookies[request.uri])
  38. 360 request
  39. end
  40. 9 private
  41. 9 def set_request_callbacks(request)
  42. 360 super
  43. 360 request.on(:response) do |response|
  44. 360 next unless response && response.respond_to?(:headers) && (set_cookie = response.headers["set-cookie"])
  45. 72 log { "cookies: set-cookie is over #{Cookie::MAX_LENGTH}" } if set_cookie.bytesize > Cookie::MAX_LENGTH
  46. 72 @options.cookies.parse(set_cookie)
  47. end
  48. end
  49. end
  50. 9 module HeadersMethods
  51. 9 def set_cookie(cookies)
  52. 360 return if cookies.empty?
  53. 306 header_value = cookies.sort.join("; ")
  54. 306 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. 9 module OptionsMethods
  61. 9 private
  62. 9 def option_headers(*)
  63. 360 value = super
  64. 360 merge_cookie_in_jar(value.delete("cookie"), @cookies) if defined?(@cookies) && value.key?("cookie")
  65. 360 value
  66. end
  67. 9 def option_cookies(value)
  68. 540 jar = value.is_a?(Jar) ? value : Jar.new(value)
  69. 540 merge_cookie_in_jar(@headers.delete("cookie"), jar) if defined?(@headers) && @headers.key?("cookie")
  70. 540 jar
  71. end
  72. 9 def merge_cookie_in_jar(cookies, jar)
  73. 18 cookies.each do |ck|
  74. 18 ck.split(/ *; */).each do |cookie|
  75. 36 name, value = cookie.split("=", 2)
  76. 36 jar.add(Cookie.new(name, value))
  77. end
  78. end
  79. end
  80. end
  81. end
  82. 9 register_plugin :cookies, Cookies
  83. end
  84. end

lib/httpx/plugins/cookies/cookie.rb

100.0% lines covered

77 relevant lines. 77 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module HTTPX
  3. 9 module Plugins::Cookies
  4. # The HTTP Cookie.
  5. #
  6. # Contains the single cookie info: name, value and attributes.
  7. 9 class Cookie
  8. 9 include Comparable
  9. # Maximum number of bytes per cookie (RFC 6265 6.1 requires 4096 at
  10. # least)
  11. 9 MAX_LENGTH = 4096
  12. 9 attr_reader :domain, :path, :name, :value, :created_at
  13. 9 def path=(path)
  14. 207 path = String(path)
  15. 207 @path = path.start_with?("/") ? path : "/"
  16. end
  17. # See #domain.
  18. 9 def domain=(domain)
  19. 45 domain = String(domain)
  20. 45 if domain.start_with?(".")
  21. 18 @for_domain = true
  22. 18 domain = domain[1..-1]
  23. end
  24. 45 return if domain.empty?
  25. 45 @domain_name = DomainName.new(domain)
  26. # RFC 6265 5.3 5.
  27. 45 @for_domain = false if @domain_name.domain.nil? # a public suffix or IP address
  28. 45 @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. 9 def <=>(other)
  33. # RFC 6265 5.4
  34. # Precedence: 1. longer path 2. older creation
  35. 774 (@name <=> other.name).nonzero? ||
  36. 67 (other.path.length <=> @path.length).nonzero? ||
  37. 39 (@created_at <=> other.created_at).nonzero? || 0
  38. end
  39. 9 class << self
  40. 9 def new(cookie, *args)
  41. 567 return cookie if cookie.is_a?(self)
  42. 567 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. 9 def path_match?(base_path, target_path)
  62. 1521 base_path.start_with?("/") || (return false)
  63. # RFC 6265 5.1.4
  64. 1521 bsize = base_path.size
  65. 1521 tsize = target_path.size
  66. 1521 return bsize == 1 if tsize.zero? # treat empty target_path as "/"
  67. 1521 return false unless target_path.start_with?(base_path)
  68. 1512 return true if bsize == tsize || base_path.end_with?("/")
  69. 18 target_path[bsize] == "/"
  70. end
  71. end
  72. 9 def initialize(arg, *attrs)
  73. 567 @created_at = Time.now
  74. 567 if attrs.empty?
  75. 27 attr_hash = Hash.try_convert(arg)
  76. else
  77. 540 @name = arg
  78. 540 @value, attr_hash = attrs
  79. 540 attr_hash = Hash.try_convert(attr_hash)
  80. end
  81. 33 attr_hash.each do |key, val|
  82. 351 key = key.downcase.tr("-", "_").to_sym unless key.is_a?(Symbol)
  83. 312 case key
  84. when :domain, :path
  85. 229 __send__(:"#{key}=", val)
  86. else
  87. 99 instance_variable_set(:"@#{key}", val)
  88. end
  89. 566 end if attr_hash
  90. 567 @path ||= "/"
  91. 567 raise ArgumentError, "name must be specified" if @name.nil?
  92. 567 @name = @name.to_s
  93. end
  94. 9 def expires
  95. 855 @expires || (@created_at && @max_age ? @created_at + @max_age : nil)
  96. end
  97. 9 def expired?(time = Time.now)
  98. 819 return false unless expires
  99. 36 expires <= time
  100. end
  101. # Returns a string for use in the Cookie header, i.e. `name=value`
  102. # or `name="value"`.
  103. 9 def cookie_value
  104. 552 "#{@name}=#{Scanner.quote(@value.to_s)}"
  105. end
  106. 9 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. 9 def valid_for_uri?(uri)
  110. 801 uri = URI(uri)
  111. # RFC 6265 5.4
  112. 801 return false if @secure && uri.scheme != "https"
  113. 792 acceptable_from_uri?(uri) && Cookie.path_match?(@path, uri.path)
  114. end
  115. 9 private
  116. # Tests if it is OK to accept this cookie if it is sent from a given
  117. # URI/URL, `uri`.
  118. 9 def acceptable_from_uri?(uri)
  119. 828 uri = URI(uri)
  120. 828 host = DomainName.new(uri.host)
  121. # RFC 6265 5.3
  122. 828 if host.hostname == @domain
  123. 18 true
  124. 809 elsif @for_domain # !host-only-flag
  125. 36 host.cookie_domain?(@domain_name)
  126. else
  127. 774 @domain.nil?
  128. end
  129. end
  130. 9 module Scanner
  131. 9 RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/.freeze
  132. 9 module_function
  133. 9 def quote(s)
  134. 621 return s unless s.match(RE_BAD_CHAR)
  135. 9 "\"#{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. 9 module HTTPX
  3. 9 module Plugins::Cookies
  4. # The Cookie Jar
  5. #
  6. # It holds a bunch of cookies.
  7. 9 class Jar
  8. 9 using URIExtensions
  9. 9 include Enumerable
  10. 9 def initialize_dup(orig)
  11. 243 super
  12. 243 @cookies = orig.instance_variable_get(:@cookies).dup
  13. end
  14. 9 def initialize(cookies = nil)
  15. 603 @cookies = []
  16. 120 cookies.each do |elem|
  17. 198 cookie = case elem
  18. when Cookie
  19. 18 elem
  20. when Array
  21. 162 Cookie.new(*elem)
  22. else
  23. 18 Cookie.new(elem)
  24. end
  25. 198 @cookies << cookie
  26. 602 end if cookies
  27. end
  28. 9 def parse(set_cookie)
  29. 162 SetCookieParser.call(set_cookie) do |name, value, attrs|
  30. 234 add(Cookie.new(name, value, attrs))
  31. end
  32. end
  33. 9 def add(cookie, path = nil)
  34. 513 c = cookie.dup
  35. 513 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. 972 @cookies.delete_if { |ck| ck.name == c.name && ck.domain == c.domain && ck.path == c.path }
  39. 513 @cookies << c
  40. end
  41. 9 def [](uri)
  42. 531 each(uri).sort
  43. end
  44. 9 def each(uri = nil, &blk)
  45. 1332 return enum_for(__method__, uri) unless blk
  46. 765 return @cookies.each(&blk) unless uri
  47. 531 now = Time.now
  48. 531 tpath = uri.path
  49. 531 @cookies.delete_if do |cookie|
  50. 819 if cookie.expired?(now)
  51. 18 true
  52. else
  53. 801 yield cookie if cookie.valid_for_uri?(uri) && Cookie.path_match?(cookie.path, tpath)
  54. 801 false
  55. end
  56. end
  57. end
  58. 9 def merge(other)
  59. 225 cookies_dup = dup
  60. 225 other.each do |elem|
  61. 243 cookie = case elem
  62. when Cookie
  63. 225 elem
  64. when Array
  65. 9 Cookie.new(*elem)
  66. else
  67. 9 Cookie.new(elem)
  68. end
  69. 243 cookies_dup.add(cookie)
  70. end
  71. 225 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. 9 require "strscan"
  3. 9 require "time"
  4. 9 module HTTPX
  5. 9 module Plugins::Cookies
  6. 9 module SetCookieParser
  7. # Whitespace.
  8. 9 RE_WSP = /[ \t]+/.freeze
  9. # A pattern that matches a cookie name or attribute name which may
  10. # be empty, capturing trailing whitespace.
  11. 9 RE_NAME = /(?!#{RE_WSP})[^,;\\"=]*/.freeze
  12. 9 RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/.freeze
  13. # A pattern that matches the comma in a (typically date) value.
  14. 9 RE_COOKIE_COMMA = /,(?=#{RE_WSP}?#{RE_NAME}=)/.freeze
  15. 9 module_function
  16. 9 def scan_dquoted(scanner)
  17. 18 s = +""
  18. 24 until scanner.eos?
  19. 72 break if scanner.skip(/"/)
  20. 54 if scanner.skip(/\\/)
  21. 18 s << scanner.getch
  22. 35 elsif scanner.scan(/[^"\\]+/)
  23. 36 s << scanner.matched
  24. end
  25. end
  26. 18 s
  27. end
  28. 9 def scan_value(scanner, comma_as_separator = false)
  29. 495 value = +""
  30. 553 until scanner.eos?
  31. 855 if scanner.scan(/[^,;"]+/)
  32. 486 value << scanner.matched
  33. 368 elsif scanner.skip(/"/)
  34. # RFC 6265 2.2
  35. # A cookie-value may be DQUOTE'd.
  36. 18 value << scan_dquoted(scanner)
  37. 350 elsif scanner.check(/;/)
  38. 261 break
  39. 89 elsif comma_as_separator && scanner.check(RE_COOKIE_COMMA)
  40. 72 break
  41. else
  42. 18 value << scanner.getch
  43. end
  44. end
  45. 495 value.rstrip!
  46. 495 value
  47. end
  48. 9 def scan_name_value(scanner, comma_as_separator = false)
  49. 495 name = scanner.scan(RE_NAME)
  50. 495 name.rstrip! if name
  51. 495 if scanner.skip(/=/)
  52. 486 value = scan_value(scanner, comma_as_separator)
  53. else
  54. 9 scan_value(scanner, comma_as_separator)
  55. 9 value = nil
  56. end
  57. 495 [name, value]
  58. end
  59. 9 def call(set_cookie)
  60. 162 scanner = StringScanner.new(set_cookie)
  61. # RFC 6265 4.1.1 & 5.2
  62. 188 until scanner.eos?
  63. 234 start = scanner.pos
  64. 234 len = nil
  65. 234 scanner.skip(RE_WSP)
  66. 234 name, value = scan_name_value(scanner, true)
  67. 234 value = nil if name && name.empty?
  68. 234 attrs = {}
  69. 263 until scanner.eos?
  70. 333 if scanner.skip(/,/)
  71. # The comma is used as separator for concatenating multiple
  72. # values of a header.
  73. 72 len = (scanner.pos - 1) - start
  74. 72 break
  75. 260 elsif scanner.skip(/;/)
  76. 261 scanner.skip(RE_WSP)
  77. 261 aname, avalue = scan_name_value(scanner, true)
  78. 261 next if (aname.nil? || aname.empty?) || value.nil?
  79. 261 aname.downcase!
  80. 232 case aname
  81. when "expires"
  82. 18 next unless avalue
  83. # RFC 6265 5.2.1
  84. 18 (avalue = Time.parse(avalue)) || next
  85. when "max-age"
  86. 9 next unless avalue
  87. # RFC 6265 5.2.2
  88. 9 next unless /\A-?\d+\z/.match?(avalue)
  89. 9 avalue = Integer(avalue)
  90. when "domain"
  91. # RFC 6265 5.2.3
  92. # An empty value SHOULD be ignored.
  93. 27 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. 198 next unless avalue && avalue.start_with?("/")
  99. when "secure", "httponly"
  100. # RFC 6265 5.2.5, 5.2.6
  101. 8 avalue = true
  102. end
  103. 232 attrs[aname] = avalue
  104. end
  105. end
  106. 234 len ||= scanner.pos - start
  107. 234 next if len > Cookie::MAX_LENGTH
  108. 234 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. 9 module HTTPX
  3. 9 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. 9 module DigestAuth
  10. 9 class << self
  11. 9 def extra_options(options)
  12. 180 options.merge(max_concurrent_requests: 1)
  13. end
  14. 9 def load_dependencies(klass)
  15. 180 require_relative "auth/digest"
  16. 180 klass.plugin(:auth)
  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. 9 module OptionsMethods
  23. 9 private
  24. 9 def option_digest(value)
  25. 360 raise TypeError, ":digest must be a #{Authentication::Digest}" unless value.is_a?(Authentication::Digest)
  26. 360 value
  27. end
  28. end
  29. 9 module InstanceMethods
  30. 9 def digest_auth(user, password, hashed: false)
  31. 180 with(digest: Authentication::Digest.new(user, password, hashed: hashed))
  32. end
  33. 9 private
  34. 9 def send_requests(*requests)
  35. 216 requests.flat_map do |request|
  36. 216 digest = request.options.digest
  37. 216 next super(request) unless digest
  38. 360 probe_response = wrap { super(request).first }
  39. 180 return [probe_response] * requests.size unless probe_response.is_a?(Response)
  40. 180 if probe_response.status == 401 && digest.can_authenticate?(probe_response.headers["www-authenticate"])
  41. 162 request.transition(:idle)
  42. 162 request.authorize(digest.authenticate(request, probe_response.headers["www-authenticate"]))
  43. 162 super(request)
  44. else
  45. 18 probe_response
  46. end
  47. end
  48. end
  49. end
  50. end
  51. 9 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. 10 module HTTPX
  3. 10 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. 10 module Expect
  10. 10 EXPECT_TIMEOUT = 2
  11. 10 class << self
  12. 10 def no_expect_store
  13. 182 @no_expect_store ||= []
  14. end
  15. 10 def extra_options(options)
  16. 227 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. 10 module OptionsMethods
  25. 10 private
  26. 10 def option_expect_timeout(value)
  27. 416 seconds = Float(value)
  28. 416 raise TypeError, ":expect_timeout must be positive" unless seconds.positive?
  29. 416 seconds
  30. end
  31. 10 def option_expect_threshold_size(value)
  32. 18 bytes = Integer(value)
  33. 18 raise TypeError, ":expect_threshold_size must be positive" unless bytes.positive?
  34. 18 bytes
  35. end
  36. end
  37. 10 module RequestMethods
  38. 10 def initialize(*)
  39. 263 super
  40. 263 return if @body.empty?
  41. 173 threshold = @options.expect_threshold_size
  42. 173 return if threshold && !@body.unbounded_body? && @body.bytesize < threshold
  43. 155 return if Expect.no_expect_store.include?(origin)
  44. 130 @headers["expect"] = "100-continue"
  45. end
  46. 10 def response=(response)
  47. 159 if response.is_a?(Response) &&
  48. response.status == 100 &&
  49. !@headers.key?("expect") &&
  50. 4 (@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. 8 @headers["expect"] = "100-continue"
  58. 9 @informational_status = 100
  59. 9 Expect.no_expect_store.delete(origin)
  60. end
  61. 159 super
  62. end
  63. end
  64. 10 module ConnectionMethods
  65. 10 def send_request_to_parser(request)
  66. 94 super
  67. 94 return unless request.headers["expect"] == "100-continue"
  68. 74 expect_timeout = request.options.expect_timeout
  69. 74 return if expect_timeout.nil? || expect_timeout.infinite?
  70. 74 set_request_timeout(:expect_timeout, request, expect_timeout, :expect, %i[body response]) do
  71. # expect timeout expired
  72. 18 if request.state == :expect && !request.expects?
  73. 18 Expect.no_expect_store << request.origin
  74. 18 request.headers.delete("expect")
  75. 18 consume
  76. end
  77. end
  78. end
  79. end
  80. 10 module InstanceMethods
  81. 10 def fetch_response(request, selector, options)
  82. 427 response = super
  83. 427 return unless response
  84. 94 if response.is_a?(Response) && response.status == 417 && request.headers.key?("expect")
  85. 2 response.close
  86. 2 request.headers.delete("expect")
  87. 2 request.transition(:idle)
  88. 2 send_request(request, selector, options)
  89. 2 return
  90. end
  91. 92 response
  92. end
  93. end
  94. end
  95. 10 register_plugin :expect, Expect
  96. end
  97. end

lib/httpx/plugins/fiber_concurrency.rb

88.0% lines covered

100 relevant lines. 88 lines covered and 12 lines missed.
    
  1. # frozen_string_literal: true
  2. 19 module HTTPX
  3. 19 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/Fiber-Concurrency
  9. #
  10. 19 module FiberConcurrency
  11. 19 def self.subplugins
  12. 124 {
  13. 2066 h2c: FiberConcurrencyH2C,
  14. stream: FiberConcurrencyStream,
  15. }
  16. end
  17. 19 module InstanceMethods
  18. 19 private
  19. 19 def send_request(request, *)
  20. 771 request.set_context!
  21. 771 super
  22. end
  23. 19 def get_current_selector
  24. 686 super(&nil) || begin
  25. 596 return unless block_given?
  26. 596 default = yield
  27. 596 set_current_selector(default)
  28. 596 default
  29. end
  30. end
  31. end
  32. 19 module RequestMethods
  33. # the execution context (fiber) this request was sent on.
  34. 19 attr_reader :context
  35. 19 def initialize(*)
  36. 699 super
  37. 699 @context = nil
  38. end
  39. # sets the execution context for this request. the default is the current fiber.
  40. 19 def set_context!
  41. 1559 @context ||= Fiber.current # rubocop:disable Naming/MemoizedInstanceVariableName
  42. end
  43. # checks whether the current execution context is the one where the request was created.
  44. 19 def current_context?
  45. 4255 @context == Fiber.current
  46. end
  47. 19 def complete!(response = @response)
  48. 699 @context = nil
  49. 699 super
  50. end
  51. end
  52. 19 module ConnectionMethods
  53. 19 def current_context?
  54. @pending.any?(&:current_context?) || (
  55. @sibling && @sibling.pending.any?(&:current_context?)
  56. )
  57. end
  58. 19 def interests
  59. 12272 return if connecting? && @pending.none?(&:current_context?)
  60. 12044 super
  61. end
  62. 19 def send(request)
  63. # DoH requests bypass the session, so context needs to be set here.
  64. 788 request.set_context!
  65. 788 super
  66. end
  67. end
  68. 19 module HTTP1Methods
  69. 19 def interests
  70. 1337 request = @request || @requests.first
  71. 1337 return unless request
  72. 1317 return unless request.current_context? || @requests.any?(&:current_context?) || @pending.any?(&:current_context?)
  73. 1304 super
  74. end
  75. end
  76. 19 module HTTP2Methods
  77. 19 def initialize(*)
  78. 455 super
  79. 1382 @contexts = Hash.new { |hs, k| hs[k] = Set.new }
  80. end
  81. 19 def interests
  82. 9402 if @connection.state == :connected && @handshake_completed && !@contexts.key?(Fiber.current)
  83. 585 return :w unless @pings.empty?
  84. 503 return
  85. end
  86. 8817 super
  87. end
  88. 19 def send(request, *)
  89. 1021 add_to_context(request)
  90. 1021 super
  91. end
  92. 19 private
  93. 19 def on_close(_, error, _)
  94. 20 if error == :http_1_1_required
  95. # remove all pending requests context
  96. @pending.each do |req|
  97. clear_from_context(req)
  98. end
  99. end
  100. 20 super
  101. end
  102. 19 def on_stream_close(_, request, error)
  103. 516 clear_from_context(request) if error != :stream_closed && @streams.key?(request)
  104. 516 super
  105. end
  106. 19 def teardown(request = nil)
  107. 508 super
  108. 508 if request
  109. 488 clear_from_context(request)
  110. else
  111. 20 @contexts.clear
  112. end
  113. end
  114. 19 def add_to_context(request)
  115. 1021 @contexts[request.context] << request
  116. end
  117. 19 def clear_from_context(request)
  118. 976 requests = @contexts[request.context]
  119. 976 requests.delete(request)
  120. 976 @contexts.delete(request.context) if requests.empty?
  121. end
  122. end
  123. 19 module NativeResolverMethods
  124. 19 private
  125. 19 def calculate_interests
  126. return if @queries.empty?
  127. return unless @queries.values.any?(&:current_context?) || @connections.any?(&:current_context?)
  128. super
  129. end
  130. end
  131. 19 module SystemResolverMethods
  132. 19 def interests
  133. return unless @queries.any? { |_, conn| conn.current_context? }
  134. super
  135. end
  136. end
  137. 19 module FiberConcurrencyH2C
  138. 19 module HTTP2Methods
  139. 19 def upgrade(request, *)
  140. @contexts[request.context] << request
  141. super
  142. end
  143. end
  144. end
  145. 19 module FiberConcurrencyStream
  146. 19 module StreamResponseMethods
  147. 19 def close
  148. 9 unless @request.current_context?
  149. 9 @request.close
  150. 9 return
  151. end
  152. super
  153. end
  154. end
  155. end
  156. end
  157. 19 register_plugin :fiber_concurrency, FiberConcurrency
  158. end
  159. 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. 17 module HTTPX
  3. 17 InsecureRedirectError = Class.new(Error)
  4. 17 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. 17 module FollowRedirects
  21. 17 MAX_REDIRECTS = 3
  22. 17 REDIRECT_STATUS = (300..399).freeze
  23. 17 REQUEST_BODY_HEADERS = %w[transfer-encoding content-encoding content-type content-length content-language content-md5 trailer].freeze
  24. 17 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. 17 module OptionsMethods
  34. 17 private
  35. 17 def option_max_redirects(value)
  36. 520 num = Integer(value)
  37. 520 raise TypeError, ":max_redirects must be positive" if num.negative?
  38. 520 num
  39. end
  40. 17 def option_follow_insecure_redirects(value)
  41. 27 value
  42. end
  43. 17 def option_allow_auth_to_other_origins(value)
  44. 27 value
  45. end
  46. 17 def option_redirect_on(value)
  47. 54 raise TypeError, ":redirect_on must be callable" unless value.respond_to?(:call)
  48. 54 value
  49. end
  50. end
  51. 17 module InstanceMethods
  52. # returns a session with the *max_redirects* option set to +n+
  53. 17 def max_redirects(n)
  54. 54 with(max_redirects: n.to_i)
  55. end
  56. 17 private
  57. 17 def fetch_response(request, selector, options)
  58. 1826 redirect_request = request.redirect_request
  59. 1826 response = super(redirect_request, selector, options)
  60. 1826 return unless response
  61. 640 max_redirects = redirect_request.max_redirects
  62. 640 return response unless response.is_a?(Response)
  63. 622 return response unless REDIRECT_STATUS.include?(response.status) && response.headers.key?("location")
  64. 407 return response unless max_redirects.positive?
  65. 371 redirect_uri = __get_location_from_response(response)
  66. 371 if options.redirect_on
  67. 36 redirect_allowed = options.redirect_on.call(redirect_uri)
  68. 36 return response unless redirect_allowed
  69. end
  70. # build redirect request
  71. 353 request_body = redirect_request.body
  72. 353 redirect_method = "GET"
  73. 353 redirect_params = {}
  74. 353 if response.status == 305 && options.respond_to?(:proxy)
  75. 9 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. 9 redirect_options = options.merge(headers: redirect_request.headers,
  79. proxy: { uri: redirect_uri },
  80. max_redirects: max_redirects - 1)
  81. 8 redirect_params[:body] = request_body
  82. 9 redirect_uri = redirect_request.uri
  83. 9 options = redirect_options
  84. else
  85. 344 redirect_headers = redirect_request_headers(redirect_request.uri, redirect_uri, request.headers, options)
  86. 344 redirect_opts = Hash[options]
  87. 307 redirect_params[:max_redirects] = max_redirects - 1
  88. 344 unless request_body.empty?
  89. 27 if response.status == 307
  90. # The method and the body of the original request are reused to perform the redirected request.
  91. 9 redirect_method = redirect_request.verb
  92. 9 request_body.rewind
  93. 8 redirect_params[:body] = request_body
  94. else
  95. # redirects are **ALWAYS** GET, so remove body-related headers
  96. 18 REQUEST_BODY_HEADERS.each do |h|
  97. 126 redirect_headers.delete(h)
  98. end
  99. 16 redirect_params[:body] = nil
  100. end
  101. end
  102. 344 options = options.class.new(redirect_opts.merge(headers: redirect_headers.to_h))
  103. end
  104. 353 redirect_uri = Utils.to_uri(redirect_uri)
  105. 353 if !options.follow_insecure_redirects &&
  106. response.uri.scheme == "https" &&
  107. redirect_uri.scheme == "http"
  108. 9 error = InsecureRedirectError.new(redirect_uri.to_s)
  109. 9 error.set_backtrace(caller)
  110. 8 return ErrorResponse.new(request, error)
  111. end
  112. 344 retry_request = build_request(redirect_method, redirect_uri, redirect_params, options)
  113. 344 request.redirect_request = retry_request
  114. 344 redirect_after = response.headers["retry-after"]
  115. 344 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. 36 redirect_after = Utils.parse_retry_after(redirect_after)
  123. 36 retry_start = Utils.now
  124. 36 log { "redirecting after #{redirect_after} secs..." }
  125. 36 selector.after(redirect_after) do
  126. 36 if (response = request.response)
  127. 18 response.finish!
  128. 18 retry_request.response = response
  129. # request has terminated abruptly meanwhile
  130. 18 retry_request.emit(:response, response)
  131. else
  132. 18 log { "redirecting (elapsed time: #{Utils.elapsed_time(retry_start)})!!" }
  133. 18 send_request(retry_request, selector, options)
  134. end
  135. end
  136. else
  137. 308 send_request(retry_request, selector, options)
  138. end
  139. 154 nil
  140. end
  141. # :nodoc:
  142. 17 def redirect_request_headers(original_uri, redirect_uri, headers, options)
  143. 344 headers = headers.dup
  144. 344 return headers if options.allow_auth_to_other_origins
  145. 335 return headers unless headers.key?("authorization")
  146. 9 return headers if original_uri.origin == redirect_uri.origin
  147. 9 headers.delete("authorization")
  148. 9 headers
  149. end
  150. # :nodoc:
  151. 17 def __get_location_from_response(response)
  152. # @type var location_uri: http_uri
  153. 371 location_uri = URI(response.headers["location"])
  154. 371 location_uri = response.uri.merge(location_uri) if location_uri.relative?
  155. 371 location_uri
  156. end
  157. end
  158. 17 module RequestMethods
  159. # returns the top-most original HTTPX::Request from the redirect chain
  160. 17 attr_accessor :root_request
  161. # returns the follow-up redirect request, or itself
  162. 17 def redirect_request
  163. 1826 @redirect_request || self
  164. end
  165. # sets the follow-up redirect request
  166. 17 def redirect_request=(req)
  167. 344 @redirect_request = req
  168. 344 req.root_request = @root_request || self
  169. 344 @response = nil
  170. end
  171. 17 def response
  172. 4086 return super unless @redirect_request && @response.nil?
  173. 116 @redirect_request.response
  174. end
  175. 17 def max_redirects
  176. 640 @options.max_redirects || MAX_REDIRECTS
  177. end
  178. end
  179. 17 module ConnectionMethods
  180. 17 private
  181. 17 def set_request_request_timeout(request)
  182. 608 return unless request.root_request.nil?
  183. 289 super
  184. end
  185. end
  186. end
  187. 17 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. 7 module HTTPX
  3. 7 GRPCError = Class.new(Error) do
  4. 7 attr_reader :status, :details, :metadata
  5. 7 def initialize(status, details, metadata)
  6. 28 @status = status
  7. 28 @details = details
  8. 28 @metadata = metadata
  9. 28 super("GRPC error, code=#{status}, details=#{details}, metadata=#{metadata}")
  10. end
  11. end
  12. 7 module Plugins
  13. #
  14. # This plugin adds DSL to build GRPC interfaces.
  15. #
  16. # https://gitlab.com/os85/httpx/wikis/GRPC
  17. #
  18. 7 module GRPC
  19. 7 unless String.method_defined?(:underscore)
  20. 7 module StringExtensions
  21. 7 refine String do
  22. 7 def underscore
  23. 364 s = dup # Avoid mutating the argument, as it might be frozen.
  24. 364 s.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
  25. 364 s.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
  26. 364 s.tr!("-", "_")
  27. 364 s.downcase!
  28. 364 s
  29. end
  30. end
  31. end
  32. 7 using StringExtensions
  33. end
  34. 7 DEADLINE = 60
  35. 7 MARSHAL_METHOD = :encode
  36. 7 UNMARSHAL_METHOD = :decode
  37. 7 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. 7 class << self
  45. 7 def load_dependencies(*)
  46. 161 require "stringio"
  47. 161 require "httpx/plugins/grpc/grpc_encoding"
  48. 161 require "httpx/plugins/grpc/message"
  49. 161 require "httpx/plugins/grpc/call"
  50. end
  51. 7 def configure(klass)
  52. 161 klass.plugin(:persistent)
  53. 161 klass.plugin(:stream)
  54. end
  55. 7 def extra_options(options)
  56. 161 options.merge(
  57. fallback_protocol: "h2",
  58. grpc_rpcs: {}.freeze,
  59. grpc_compression: false,
  60. grpc_deadline: DEADLINE
  61. )
  62. end
  63. end
  64. 7 module OptionsMethods
  65. 7 private
  66. 7 def option_grpc_service(value)
  67. 140 String(value)
  68. end
  69. 7 def option_grpc_compression(value)
  70. 350 case value
  71. when true, false
  72. 322 value
  73. else
  74. 28 value.to_s
  75. end
  76. end
  77. 7 def option_grpc_rpcs(value)
  78. 1463 Hash[value]
  79. end
  80. 7 def option_grpc_deadline(value)
  81. 1099 raise TypeError, ":grpc_deadline must be positive" unless value.positive?
  82. 1099 value
  83. end
  84. 7 def option_call_credentials(value)
  85. 21 raise TypeError, ":call_credentials must respond to #call" unless value.respond_to?(:call)
  86. 21 value
  87. end
  88. end
  89. 7 module ResponseMethods
  90. 7 attr_reader :trailing_metadata
  91. 7 def merge_headers(trailers)
  92. 133 @trailing_metadata = Hash[trailers]
  93. 133 super
  94. end
  95. end
  96. 7 module RequestBodyMethods
  97. 7 def initialize(*, **)
  98. 147 super
  99. 147 if (compression = @headers["grpc-encoding"])
  100. 14 deflater_body = self.class.initialize_deflater_body(@body, compression)
  101. 14 @body = Transcoder::GRPCEncoding.encode(deflater_body || @body, compressed: !deflater_body.nil?)
  102. else
  103. 133 @body = Transcoder::GRPCEncoding.encode(@body, compressed: false)
  104. end
  105. end
  106. end
  107. 7 module InstanceMethods
  108. 7 def with_channel_credentials(ca_path, key = nil, cert = nil, **ssl_opts)
  109. # @type var ssl_params: ::Hash[::Symbol, untyped]
  110. 84 ssl_params = {
  111. **ssl_opts,
  112. ca_file: ca_path,
  113. }
  114. 84 if key
  115. 84 key = File.read(key) if File.file?(key)
  116. 84 ssl_params[:key] = OpenSSL::PKey.read(key)
  117. end
  118. 84 if cert
  119. 84 cert = File.read(cert) if File.file?(cert)
  120. 84 ssl_params[:cert] = OpenSSL::X509::Certificate.new(cert)
  121. end
  122. 84 with(ssl: ssl_params)
  123. end
  124. 7 def rpc(rpc_name, input, output, **opts)
  125. 364 rpc_name = rpc_name.to_s
  126. 364 raise Error, "rpc #{rpc_name} already defined" if @options.grpc_rpcs.key?(rpc_name)
  127. rpc_opts = {
  128. 364 deadline: @options.grpc_deadline,
  129. }.merge(opts)
  130. 364 local_rpc_name = rpc_name.underscore
  131. 364 session_class = Class.new(self.class) do
  132. # define rpc method with ruby style name
  133. 364 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. 364 unless local_rpc_name == rpc_name
  140. 14 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. 364 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. 7 def build_stub(origin, service: nil, compression: false)
  154. 161 scheme = @options.ssl.empty? ? "http" : "https"
  155. 161 origin = URI.parse("#{scheme}://#{origin}")
  156. 161 session = self
  157. 161 if service && service.respond_to?(:rpc_descs)
  158. # it's a grpc generic service
  159. 70 service.rpc_descs.each do |rpc_name, rpc_desc|
  160. rpc_opts = {
  161. 350 marshal_method: rpc_desc.marshal_method,
  162. unmarshal_method: rpc_desc.unmarshal_method,
  163. }
  164. 350 input = rpc_desc.input
  165. 350 input = input.type if input.respond_to?(:type)
  166. 350 output = rpc_desc.output
  167. 350 if output.respond_to?(:type)
  168. 140 rpc_opts[:stream] = true
  169. 140 output = output.type
  170. end
  171. 350 session = session.rpc(rpc_name, input, output, **rpc_opts)
  172. end
  173. 70 service = service.service_name
  174. end
  175. 161 session.with(origin: origin, grpc_service: service, grpc_compression: compression)
  176. end
  177. 7 def execute(rpc_method, input,
  178. deadline: DEADLINE,
  179. metadata: nil,
  180. **opts)
  181. 147 grpc_request = build_grpc_request(rpc_method, input, deadline: deadline, metadata: metadata, **opts)
  182. 147 response = request(grpc_request, **opts)
  183. 147 response.raise_for_status unless opts[:stream]
  184. 133 GRPC::Call.new(response)
  185. end
  186. 7 private
  187. 7 def rpc_execute(rpc_name, input, **opts)
  188. 70 rpc_name, input_enc, output_enc, rpc_opts = @options.grpc_rpcs[rpc_name]
  189. 70 exec_opts = rpc_opts.merge(opts)
  190. 70 marshal_method ||= exec_opts.delete(:marshal_method) || MARSHAL_METHOD
  191. 70 unmarshal_method ||= exec_opts.delete(:unmarshal_method) || UNMARSHAL_METHOD
  192. 70 messages = if input.respond_to?(:each)
  193. 28 Enumerator.new do |y|
  194. 28 input.each do |message|
  195. 56 y << input_enc.__send__(marshal_method, message)
  196. end
  197. end
  198. else
  199. 42 input_enc.__send__(marshal_method, input)
  200. end
  201. 70 call = execute(rpc_name, messages, **exec_opts)
  202. 70 call.decoder = output_enc.method(unmarshal_method)
  203. 70 call
  204. end
  205. 7 def build_grpc_request(rpc_method, input, deadline:, metadata: nil, **opts)
  206. 147 uri = @options.origin.dup
  207. 147 rpc_method = "/#{rpc_method}" unless rpc_method.start_with?("/")
  208. 147 rpc_method = "/#{@options.grpc_service}#{rpc_method}" if @options.grpc_service
  209. 147 uri.path = rpc_method
  210. 147 headers = HEADERS.merge(
  211. "grpc-accept-encoding" => ["identity", *@options.supported_compression_formats]
  212. )
  213. 147 unless deadline == Float::INFINITY
  214. # convert to milliseconds
  215. 147 deadline = (deadline * 1000.0).to_i
  216. 147 headers["grpc-timeout"] = "#{deadline}m"
  217. end
  218. 147 headers = headers.merge(metadata.transform_keys(&:to_s)) if metadata
  219. # prepare compressor
  220. 147 compression = @options.grpc_compression == true ? "gzip" : @options.grpc_compression
  221. 147 headers["grpc-encoding"] = compression if compression
  222. 147 headers.merge!(@options.call_credentials.call.transform_keys(&:to_s)) if @options.call_credentials
  223. 147 build_request("POST", uri, headers: headers, body: input, **opts)
  224. end
  225. end
  226. end
  227. 7 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. 7 module HTTPX
  3. 7 module Plugins
  4. 7 module GRPC
  5. # Encapsulates call information
  6. 7 class Call
  7. 7 attr_writer :decoder
  8. 7 def initialize(response)
  9. 133 @response = response
  10. 182 @decoder = ->(z) { z }
  11. 133 @consumed = false
  12. 133 @grpc_response = nil
  13. end
  14. 7 def inspect
  15. "#{self.class}(#{grpc_response})"
  16. end
  17. 7 def to_s
  18. 77 grpc_response.to_s
  19. end
  20. 7 def metadata
  21. response.headers
  22. end
  23. 7 def trailing_metadata
  24. 84 return unless @consumed
  25. 56 @response.trailing_metadata
  26. end
  27. 7 private
  28. 7 def grpc_response
  29. 217 @grpc_response ||= if @response.respond_to?(:each)
  30. 28 Enumerator.new do |y|
  31. 28 Message.stream(@response).each do |message|
  32. 56 y << @decoder.call(message)
  33. end
  34. 28 @consumed = true
  35. end
  36. else
  37. 105 @consumed = true
  38. 105 @decoder.call(Message.unary(@response))
  39. end
  40. end
  41. 7 def respond_to_missing?(meth, *args, &blk)
  42. 28 grpc_response.respond_to?(meth, *args) || super
  43. end
  44. 7 def method_missing(meth, *args, &blk)
  45. 56 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. 7 module HTTPX
  3. 7 module Transcoder
  4. 7 module GRPCEncoding
  5. 7 class Deflater
  6. 7 extend Forwardable
  7. 7 attr_reader :content_type
  8. 7 def initialize(body, compressed:)
  9. 147 @content_type = body.content_type
  10. 147 @body = BodyReader.new(body)
  11. 147 @compressed = compressed
  12. end
  13. 7 def bytesize
  14. 525 return @body.bytesize if @body.respond_to?(:bytesize)
  15. Float::INFINITY
  16. end
  17. 7 def read(length = nil, outbuf = nil)
  18. 322 buf = @body.read(length, outbuf)
  19. 294 return unless buf
  20. 161 compressed_flag = @compressed ? 1 : 0
  21. 161 buf = outbuf if outbuf
  22. 161 buf = buf.b if buf.frozen?
  23. 161 buf.prepend([compressed_flag, buf.bytesize].pack("CL>"))
  24. 161 buf
  25. end
  26. end
  27. 7 class Inflater
  28. 7 def initialize(response)
  29. 105 @response = response
  30. 105 @grpc_encodings = nil
  31. end
  32. 7 def call(message, &blk)
  33. 133 data = "".b
  34. 133 until message.empty?
  35. 133 compressed, size = message.unpack("CL>")
  36. 133 encoded_data = message.byteslice(5..(size + 5 - 1))
  37. 133 if compressed == 1
  38. 14 grpc_encodings.reverse_each do |encoding|
  39. 14 decoder = @response.body.class.initialize_inflater_by_encoding(encoding, @response, bytesize: encoded_data.bytesize)
  40. 14 encoded_data = decoder.call(encoded_data)
  41. 14 blk.call(encoded_data) if blk
  42. 14 data << encoded_data
  43. end
  44. else
  45. 119 blk.call(encoded_data) if blk
  46. 119 data << encoded_data
  47. end
  48. 133 message = message.byteslice((size + 5)..-1)
  49. end
  50. 133 data
  51. end
  52. 7 private
  53. 7 def grpc_encodings
  54. 14 @grpc_encodings ||= @response.headers.get("grpc-encoding")
  55. end
  56. end
  57. 7 def self.encode(*args, **kwargs)
  58. 147 Deflater.new(*args, **kwargs)
  59. end
  60. 7 def self.decode(response)
  61. 105 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. 7 module HTTPX
  3. 7 module Plugins
  4. 7 module GRPC
  5. # Encoding module for GRPC responses
  6. #
  7. # Can encode and decode grpc messages.
  8. 7 module Message
  9. 7 module_function
  10. # decodes a unary grpc response
  11. 7 def unary(response)
  12. 105 verify_status(response)
  13. 77 decoder = Transcoder::GRPCEncoding.decode(response)
  14. 77 decoder.call(response.to_s)
  15. end
  16. # lazy decodes a grpc stream response
  17. 7 def stream(response, &block)
  18. 56 return enum_for(__method__, response) unless block
  19. 28 decoder = Transcoder::GRPCEncoding.decode(response)
  20. 28 response.each do |frame|
  21. 56 decoder.call(frame, &block)
  22. end
  23. 28 verify_status(response)
  24. end
  25. 7 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. 7 def verify_status(response)
  31. # return standard errors if need be
  32. 133 response.raise_for_status
  33. 133 status = Integer(response.headers["grpc-status"])
  34. 133 message = response.headers["grpc-message"]
  35. 133 return if status.zero?
  36. 28 response.close
  37. 28 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. 19 module HTTPX
  3. 19 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. 19 module H2C
  11. 19 VALID_H2C_VERBS = %w[GET OPTIONS HEAD].freeze
  12. 19 class << self
  13. 19 def load_dependencies(klass)
  14. 18 klass.plugin(:upgrade)
  15. end
  16. 19 def call(connection, request, response)
  17. 18 connection.upgrade_to_h2c(request, response)
  18. end
  19. 19 def extra_options(options)
  20. 20 options.merge(
  21. 18 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. 19 module OptionsMethods
  28. 19 def option_h2c_class(value)
  29. 18 value
  30. end
  31. end
  32. 19 module RequestMethods
  33. 19 def valid_h2c_verb?
  34. 18 VALID_H2C_VERBS.include?(@verb)
  35. end
  36. end
  37. 19 module ConnectionMethods
  38. 19 using URIExtensions
  39. 19 def initialize(*)
  40. 18 super
  41. 18 @h2c_handshake = false
  42. end
  43. 19 def send(request)
  44. 63 return super if @h2c_handshake
  45. 18 return super unless request.valid_h2c_verb? && request.scheme == "http"
  46. 18 return super if @upgrade_protocol == "h2c"
  47. 18 @h2c_handshake = true
  48. # build upgrade request
  49. 18 request.headers.add("connection", "upgrade")
  50. 18 request.headers.add("connection", "http2-settings")
  51. 16 request.headers["upgrade"] = "h2c"
  52. 16 request.headers["http2-settings"] = ::HTTP2::Client.settings_header(request.options.http2_settings)
  53. 18 super
  54. end
  55. 19 def upgrade_to_h2c(request, response)
  56. 18 prev_parser = @parser
  57. 18 if prev_parser
  58. 18 prev_parser.reset
  59. 16 @inflight -= prev_parser.requests.size
  60. end
  61. 18 @parser = request.options.h2c_class.new(@write_buffer, @options)
  62. 18 set_parser_callbacks(@parser)
  63. 16 @inflight += 1
  64. 18 @parser.upgrade(request, response)
  65. 18 @upgrade_protocol = "h2c"
  66. 18 prev_parser.requests.each do |req|
  67. 18 req.transition(:idle)
  68. 18 send(req)
  69. end
  70. end
  71. 19 private
  72. 19 def send_request_to_parser(request)
  73. 63 super
  74. 63 return unless request.headers["upgrade"] == "h2c" && parser.is_a?(Connection::HTTP1)
  75. 18 max_concurrent_requests = parser.max_concurrent_requests
  76. 18 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. 19 module H2CParser
  84. 19 def upgrade(request, response)
  85. # skip checks, it is assumed that this is the first
  86. # request in the connection
  87. 18 stream = @connection.upgrade
  88. # on_settings
  89. 18 handle_stream(stream, request)
  90. 16 @streams[request] = stream
  91. # clean up data left behind in the buffer, if the server started
  92. # sending frames
  93. 18 data = response.read
  94. 18 @connection << data
  95. end
  96. end
  97. end
  98. 19 register_plugin(:h2c, H2C)
  99. end
  100. end

lib/httpx/plugins/ntlm_auth.rb

100.0% lines covered

33 relevant lines. 33 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. 2 klass.plugin(:auth)
  12. end
  13. 3 def extra_options(options)
  14. 2 options.merge(max_concurrent_requests: 1)
  15. end
  16. end
  17. 3 module OptionsMethods
  18. 3 private
  19. 3 def option_ntlm(value)
  20. 8 raise TypeError, ":ntlm must be a #{Authentication::Ntlm}" unless value.is_a?(Authentication::Ntlm)
  21. 8 value
  22. end
  23. end
  24. 3 module InstanceMethods
  25. 3 def ntlm_auth(user, password, domain = nil)
  26. 4 with(ntlm: Authentication::Ntlm.new(user, password, domain: domain))
  27. end
  28. 3 private
  29. 3 def send_requests(*requests)
  30. 8 requests.flat_map do |request|
  31. 8 ntlm = request.options.ntlm
  32. 8 if ntlm
  33. 4 request.authorize(ntlm.negotiate)
  34. 8 probe_response = wrap { super(request).first }
  35. 4 return probe_response unless probe_response.is_a?(Response)
  36. 4 if probe_response.status == 401 && ntlm.can_authenticate?(probe_response.headers["www-authenticate"])
  37. 2 request.transition(:idle)
  38. 2 request.headers.get("authorization").pop
  39. 2 request.authorize(ntlm.authenticate(request, probe_response.headers["www-authenticate"]).encode("utf-8"))
  40. 2 super(request)
  41. else
  42. 2 probe_response
  43. end
  44. else
  45. 4 super(request)
  46. end
  47. end
  48. end
  49. end
  50. end
  51. 3 register_plugin :ntlm_auth, NTLMAuth
  52. end
  53. end

lib/httpx/plugins/oauth.rb

90.65% lines covered

139 relevant lines. 126 lines covered and 13 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module HTTPX
  3. 9 module Plugins
  4. #
  5. # This plugin adds support for managing an OAuth Session associated with the given session.
  6. #
  7. # The scope of OAuth support is limited to the `client_crendentials` and `refresh_token` grants.
  8. #
  9. # https://gitlab.com/os85/httpx/wikis/OAuth
  10. #
  11. 9 module OAuth
  12. 9 class << self
  13. 9 def load_dependencies(klass)
  14. 270 require_relative "auth/basic"
  15. 270 klass.plugin(:auth)
  16. end
  17. 9 def subplugins
  18. 60 {
  19. 479 retries: OAuthRetries,
  20. }
  21. end
  22. 9 def extra_options(options)
  23. 270 options.merge(auth_header_type: "Bearer")
  24. end
  25. end
  26. 9 SUPPORTED_GRANT_TYPES = %w[client_credentials refresh_token].freeze
  27. 9 SUPPORTED_AUTH_METHODS = %w[client_secret_basic client_secret_post].freeze
  28. # Implements the bulk of functionality and maintains the state associated with the
  29. # management of the the lifecycle of an OAuth session.
  30. 9 class OAuthSession
  31. 9 attr_reader :access_token, :refresh_token
  32. 9 def initialize(
  33. issuer:,
  34. client_id:,
  35. client_secret:,
  36. access_token: nil,
  37. refresh_token: nil,
  38. scope: nil,
  39. audience: nil,
  40. token_endpoint: nil,
  41. grant_type: nil,
  42. token_endpoint_auth_method: nil
  43. )
  44. 270 @issuer = URI(issuer)
  45. 270 @client_id = client_id
  46. 270 @client_secret = client_secret
  47. 270 @token_endpoint = URI(token_endpoint) if token_endpoint
  48. 270 @scope = case scope
  49. when String
  50. 162 scope.split
  51. when Array
  52. 36 scope
  53. end
  54. 270 @audience = audience
  55. 270 @access_token = access_token
  56. 270 @refresh_token = refresh_token
  57. 270 @token_endpoint_auth_method = String(token_endpoint_auth_method) if token_endpoint_auth_method
  58. 270 @grant_type = grant_type || (@refresh_token ? "refresh_token" : "client_credentials")
  59. 270 @access_token = access_token
  60. 270 @refresh_token = refresh_token
  61. 270 unless @token_endpoint_auth_method.nil? || SUPPORTED_AUTH_METHODS.include?(@token_endpoint_auth_method)
  62. 18 raise Error, "#{@token_endpoint_auth_method} is not a supported auth method"
  63. end
  64. 252 return if SUPPORTED_GRANT_TYPES.include?(@grant_type)
  65. 18 raise Error, "#{@grant_type} is not a supported grant type"
  66. end
  67. # returns the URL where to request access and refresh tokens from.
  68. 9 def token_endpoint
  69. 252 @token_endpoint || "#{@issuer}/token"
  70. end
  71. # returns the oauth-documented authorization method to use when requesting a token.
  72. 9 def token_endpoint_auth_method
  73. 360 @token_endpoint_auth_method || "client_secret_basic"
  74. end
  75. 9 def reset!
  76. 36 @access_token = nil
  77. end
  78. # when not available, it uses the +http+ object to request new access and refresh tokens.
  79. 9 def fetch_access_token(http)
  80. 126 return access_token if access_token
  81. 108 load(http)
  82. # always prefer refresh token grant if a refresh token is available
  83. 108 grant_type = @refresh_token ? "refresh_token" : @grant_type
  84. 108 headers = {} # : Hash[String ,String]
  85. 24 form_post = {
  86. 84 "grant_type" => @grant_type,
  87. "scope" => Array(@scope).join(" "),
  88. "audience" => @audience,
  89. }.compact
  90. # auth
  91. 96 case token_endpoint_auth_method
  92. when "client_secret_post"
  93. 16 form_post["client_id"] = @client_id
  94. 16 form_post["client_secret"] = @client_secret
  95. when "client_secret_basic"
  96. 80 headers["authorization"] = Authentication::Basic.new(@client_id, @client_secret).authenticate
  97. end
  98. 96 case grant_type
  99. when "client_credentials"
  100. # do nothing
  101. when "refresh_token"
  102. 18 raise Error, "cannot use the `\"refresh_token\"` grant type without a refresh token" unless refresh_token
  103. 16 form_post["refresh_token"] = refresh_token
  104. end
  105. # POST /token
  106. 108 token_request = http.build_request("POST", token_endpoint, headers: headers, form: form_post)
  107. 108 token_request.headers.delete("authorization") unless token_endpoint_auth_method == "client_secret_basic"
  108. 216 token_response = http.skip_auth_header { http.request(token_request) }
  109. 11 begin
  110. 108 token_response.raise_for_status
  111. rescue HTTPError => e
  112. @refresh_token = nil if e.response.status == 401 && (grant_type == "refresh_token")
  113. raise e
  114. end
  115. 108 payload = token_response.json
  116. 108 @refresh_token = payload["refresh_token"] || @refresh_token
  117. 108 @access_token = payload["access_token"]
  118. end
  119. # TODO: remove this after deprecating the `:oauth_session` option
  120. 9 def merge(other)
  121. obj = dup
  122. case other
  123. when OAuthSession
  124. other.instance_variables.each do |ivar|
  125. val = other.instance_variable_get(ivar)
  126. next unless val
  127. obj.instance_variable_set(ivar, val)
  128. end
  129. when Hash
  130. other.each do |k, v|
  131. obj.instance_variable_set(:"@#{k}", v) if obj.instance_variable_defined?(:"@#{k}")
  132. end
  133. end
  134. obj
  135. end
  136. 9 private
  137. # uses +http+ to fetch for the oauth server metadata.
  138. 9 def load(http)
  139. 126 return if @grant_type && @scope
  140. 72 metadata = http.skip_auth_header { http.get("#{@issuer}/.well-known/oauth-authorization-server").raise_for_status.json }
  141. 36 @token_endpoint = metadata["token_endpoint"]
  142. 36 @scope = metadata["scopes_supported"]
  143. 144 @grant_type = Array(metadata["grant_types_supported"]).find { |gr| SUPPORTED_GRANT_TYPES.include?(gr) }
  144. 36 @token_endpoint_auth_method = Array(metadata["token_endpoint_auth_methods_supported"]).find do |am|
  145. 36 SUPPORTED_AUTH_METHODS.include?(am)
  146. end
  147. 16 nil
  148. end
  149. end
  150. # adds support for the following options:
  151. #
  152. # :oauth_options :: an hash of options to be used during session management.
  153. # check the parameters to initialize the OAuthSession class.
  154. 9 module OptionsMethods
  155. 9 private
  156. 9 def option_oauth_session(value)
  157. 36 warn "DEPRECATION WARNING: option `:oauth_session` is deprecated. " \
  158. "Use `:oauth_options` instead."
  159. 32 case value
  160. when Hash
  161. 18 OAuthSession.new(**value)
  162. when OAuthSession
  163. 18 value
  164. else
  165. raise TypeError, ":oauth_session must be a #{OAuthSession}"
  166. end
  167. end
  168. 9 def option_oauth_options(value)
  169. 450 value = Hash[value] unless value.is_a?(Hash)
  170. 432 value
  171. end
  172. end
  173. 9 module InstanceMethods
  174. 9 attr_reader :oauth_session
  175. 9 protected :oauth_session
  176. 9 def initialize(*)
  177. 468 super
  178. 468 @oauth_session = if @options.oauth_options
  179. 252 OAuthSession.new(**@options.oauth_options)
  180. 215 elsif @options.oauth_session
  181. 18 @oauth_session = @options.oauth_session.dup
  182. end
  183. end
  184. 9 def initialize_dup(other)
  185. 18 super
  186. 18 @oauth_session = other.instance_variable_get(:@oauth_session).dup
  187. end
  188. 9 def oauth_auth(**args)
  189. 18 warn "DEPRECATION WARNING: `#{__method__}` is deprecated. " \
  190. "Use `with(oauth_options: options)` instead."
  191. 18 with(oauth_options: args)
  192. end
  193. # will eagerly negotiate new oauth tokens with the issuer
  194. 9 def refresh_oauth_tokens!
  195. 18 return unless @oauth_session
  196. 18 @oauth_session.reset!
  197. 18 @oauth_session.fetch_access_token(self)
  198. end
  199. # TODO: deprecate
  200. 9 def with_access_token
  201. 18 warn "DEPRECATION WARNING: `#{__method__}` is deprecated. " \
  202. "The session will automatically handle token lifecycles for you."
  203. 18 other_session = dup # : instance
  204. 18 oauth_session = other_session.oauth_session
  205. 18 oauth_session.fetch_access_token(other_session)
  206. 18 other_session
  207. end
  208. 9 private
  209. 9 def generate_auth_token
  210. 54 return unless @oauth_session
  211. 54 @oauth_session.fetch_access_token(self)
  212. end
  213. end
  214. 9 module OAuthRetries
  215. 9 class << self
  216. 9 def extra_options(options)
  217. 18 options.merge(
  218. 1 retry_on: method(:response_oauth_error?),
  219. generate_auth_value_on_retry: method(:response_oauth_error?)
  220. )
  221. end
  222. 9 def response_oauth_error?(res)
  223. 72 res.is_a?(Response) && res.status == 401
  224. end
  225. end
  226. 9 module InstanceMethods
  227. 9 def prepare_to_retry(_request, response)
  228. 18 unless @oauth_session && @options.generate_auth_value_on_retry && @options.generate_auth_value_on_retry.call(response)
  229. return super
  230. end
  231. 18 @oauth_session.reset!
  232. 18 super
  233. end
  234. end
  235. end
  236. end
  237. 9 register_plugin :oauth, OAuth
  238. end
  239. 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. 19 module HTTPX
  3. 19 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. 19 module Persistent
  20. 19 class << self
  21. 19 def load_dependencies(klass)
  22. 595 klass.plugin(:fiber_concurrency)
  23. 595 max_retries = if klass.default_options.respond_to?(:max_retries)
  24. 9 [klass.default_options.max_retries, 1].max
  25. else
  26. 586 1
  27. end
  28. 595 klass.plugin(:retries, max_retries: max_retries)
  29. end
  30. end
  31. 19 def self.extra_options(options)
  32. 595 options.merge(persistent: true)
  33. end
  34. 19 module InstanceMethods
  35. 19 def close(*)
  36. 341 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. 341 Thread.list.each do |th|
  41. 4701 store = thread_selector_store(th)
  42. 4701 next unless store && store.key?(self)
  43. 333 selector = store.delete(self)
  44. 333 selector_close(selector)
  45. end
  46. end
  47. 19 private
  48. 19 def repeatable_request?(request, _)
  49. 686 super || begin
  50. 226 response = request.response
  51. 226 return false unless response && response.is_a?(ErrorResponse)
  52. 32 error = response.error
  53. 352 Retries::RECONNECTABLE_ERRORS.any? { |klass| error.is_a?(klass) }
  54. end
  55. end
  56. 19 def retryable_error?(ex)
  57. 97 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. 81 (!ex.is_a?(RequestTimeoutError) || @options.max_retries != 1)
  63. end
  64. end
  65. end
  66. 19 register_plugin :persistent, Persistent
  67. end
  68. end

lib/httpx/plugins/proxy.rb

94.77% lines covered

172 relevant lines. 163 lines covered and 9 lines missed.
    
  1. # frozen_string_literal: true
  2. 11 module HTTPX
  3. 11 class ProxyError < ConnectionError; end
  4. 11 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. 11 module Proxy
  16. 11 class ProxyConnectionError < ProxyError; end
  17. 11 PROXY_ERRORS = [TimeoutError, IOError, SystemCallError, Error].freeze
  18. 11 class << self
  19. 11 def configure(klass)
  20. 387 klass.plugin(:"proxy/http")
  21. 387 klass.plugin(:"proxy/socks4")
  22. 387 klass.plugin(:"proxy/socks5")
  23. end
  24. 11 def extra_options(options)
  25. 387 options.merge(supported_proxy_protocols: [])
  26. end
  27. 11 def subplugins
  28. 170 {
  29. 1398 retries: ProxyRetries,
  30. }
  31. end
  32. end
  33. 11 class Parameters
  34. 11 attr_reader :uri, :username, :password, :scheme, :no_proxy
  35. 11 def initialize(uri: nil, scheme: nil, username: nil, password: nil, no_proxy: nil, **extra)
  36. 425 @no_proxy = Array(no_proxy) if no_proxy
  37. 425 @uris = Array(uri)
  38. 425 uri = @uris.first
  39. 425 @username = username
  40. 425 @password = password
  41. 425 @ns = 0
  42. 425 if uri
  43. 380 @uri = uri.is_a?(URI::Generic) ? uri : URI(uri)
  44. 380 @username ||= @uri.user
  45. 380 @password ||= @uri.password
  46. end
  47. 425 @scheme = scheme
  48. 425 return unless @uri && @username && @password
  49. 236 @authenticator = nil
  50. 236 @scheme ||= infer_default_auth_scheme(@uri)
  51. 236 return unless @scheme
  52. 182 @authenticator = load_authenticator(@scheme, @username, @password, **extra)
  53. end
  54. 11 def shift
  55. # TODO: this operation must be synchronized
  56. 16 @ns += 1
  57. 18 @uri = @uris[@ns]
  58. 18 return unless @uri
  59. 18 @uri = URI(@uri) unless @uri.is_a?(URI::Generic)
  60. 18 scheme = infer_default_auth_scheme(@uri)
  61. 18 return unless scheme != @scheme
  62. 18 @scheme = scheme
  63. 18 @username = username || @uri.user
  64. 18 @password = password || @uri.password
  65. 18 @authenticator = load_authenticator(scheme, @username, @password)
  66. end
  67. 11 def can_authenticate?(*args)
  68. 207 return false unless @authenticator
  69. 72 @authenticator.can_authenticate?(*args)
  70. end
  71. 11 def authenticate(*args)
  72. 179 return unless @authenticator
  73. 179 @authenticator.authenticate(*args)
  74. end
  75. 11 def ==(other)
  76. 460 case other
  77. when Parameters
  78. 470 @uri == other.uri &&
  79. @username == other.username &&
  80. @password == other.password &&
  81. @scheme == other.scheme
  82. when URI::Generic, String
  83. 27 proxy_uri = @uri.dup
  84. 27 proxy_uri.user = @username
  85. 27 proxy_uri.password = @password
  86. 27 other_uri = other.is_a?(URI::Generic) ? other : URI.parse(other)
  87. 27 proxy_uri == other_uri
  88. else
  89. 18 super
  90. end
  91. end
  92. 11 private
  93. 11 def infer_default_auth_scheme(uri)
  94. 211 case uri.scheme
  95. when "socks5"
  96. 54 uri.scheme
  97. when "http", "https"
  98. 115 "basic"
  99. end
  100. end
  101. 11 def load_authenticator(scheme, username, password, **extra)
  102. 200 auth_scheme = scheme.to_s.capitalize
  103. 200 require_relative "auth/#{scheme}" unless defined?(Authentication) && Authentication.const_defined?(auth_scheme, false)
  104. 200 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. 11 module OptionsMethods
  112. 11 private
  113. 11 def option_proxy(value)
  114. 772 value.is_a?(Parameters) ? value : Parameters.new(**Hash[value])
  115. end
  116. 11 def option_supported_proxy_protocols(value)
  117. 1951 raise TypeError, ":supported_proxy_protocols must be an Array" unless value.is_a?(Array)
  118. 1951 value.map(&:to_s)
  119. end
  120. end
  121. 11 module InstanceMethods
  122. 11 def find_connection(request_uri, selector, options)
  123. 493 return super unless options.respond_to?(:proxy)
  124. 493 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. 489 proxy = options.proxy
  128. 489 return super unless proxy
  129. 478 next_proxy = proxy.uri
  130. 478 raise ProxyError, "Failed to connect to proxy" unless next_proxy
  131. 1 raise ProxyError,
  132. 460 "#{next_proxy.scheme}: unsupported proxy protocol" unless options.supported_proxy_protocols.include?(next_proxy.scheme)
  133. 451 if (no_proxy = proxy.no_proxy)
  134. 18 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. 18 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. 442 super(request_uri, selector, options.merge(proxy: proxy))
  140. end
  141. 11 private
  142. 11 def fetch_response(request, selector, options)
  143. 2077 response = request.response # in case it goes wrong later
  144. 160 begin
  145. 2077 response = super
  146. 2077 if response.is_a?(ErrorResponse) && proxy_error?(request, response, options)
  147. 18 options.proxy.shift
  148. # return last error response if no more proxies to try
  149. 18 return response if options.proxy.uri.nil?
  150. 18 log { "failed connecting to proxy, trying next..." }
  151. 18 request.transition(:idle)
  152. 18 send_request(request, selector, options)
  153. 18 return
  154. end
  155. 2059 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. 11 def proxy_error?(_request, response, options)
  163. 190 return false unless options.proxy
  164. 189 error = response.error
  165. 168 case error
  166. when NativeResolveError
  167. 18 proxy_uri = URI(options.proxy.uri)
  168. 18 unresolved_host = error.host
  169. # failed resolving proxy domain
  170. 18 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. 171 false
  179. end
  180. end
  181. end
  182. 11 module ConnectionMethods
  183. 11 using URIExtensions
  184. 11 def initialize(*)
  185. 440 super
  186. 440 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. 420 @proxy_uri = URI(@options.proxy.uri)
  190. end
  191. 11 def peer
  192. 1072 @proxy_uri || super
  193. end
  194. 11 def connecting?
  195. 6782 return super unless @options.proxy
  196. 6581 super || @state == :connecting || @state == :connected
  197. end
  198. 11 def call
  199. 1559 super
  200. 1559 return unless @options.proxy
  201. 1401 case @state
  202. when :connecting
  203. 392 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. 11 def reset
  214. 466 return super unless @options.proxy
  215. 447 @state = :open
  216. 447 super
  217. # emit(:close)
  218. end
  219. 11 private
  220. 11 def initialize_type(uri, options)
  221. 440 return super unless options.proxy
  222. 420 "tcp"
  223. end
  224. 11 def connect
  225. 1272 return super unless @options.proxy
  226. 1105 case @state
  227. when :idle
  228. 833 transition(:connecting)
  229. when :connected
  230. 401 transition(:open)
  231. end
  232. end
  233. 11 def handle_transition(nextstate)
  234. 2579 return super unless @options.proxy
  235. 2219 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. 447 @state = :open if @state == :connecting
  240. end
  241. 2482 super
  242. end
  243. 11 def purge_after_closed
  244. 493 super
  245. 493 @io = @io.proxy_io if @io.respond_to?(:proxy_io)
  246. end
  247. end
  248. 11 module ProxyRetries
  249. 11 module InstanceMethods
  250. 11 def retryable_error?(ex)
  251. 62 super || ex.is_a?(ProxyConnectionError)
  252. end
  253. end
  254. end
  255. end
  256. 11 register_plugin :proxy, Proxy
  257. end
  258. 11 class ProxySSL < SSL
  259. 11 attr_reader :proxy_io
  260. 11 def initialize(tcp, request_uri, options)
  261. 116 @proxy_io = tcp
  262. 116 @io = tcp.to_io
  263. 116 super(request_uri, tcp.addresses, options)
  264. 116 @hostname = request_uri.host
  265. 116 @state = :connected
  266. end
  267. end
  268. end

lib/httpx/plugins/proxy/http.rb

94.74% lines covered

114 relevant lines. 108 lines covered and 6 lines missed.
    
  1. # frozen_string_literal: true
  2. 11 module HTTPX
  3. 11 module Plugins
  4. 11 module Proxy
  5. 11 module HTTP
  6. 11 class << self
  7. 11 def extra_options(options)
  8. 387 options.merge(supported_proxy_protocols: options.supported_proxy_protocols + %w[http])
  9. end
  10. end
  11. 11 module InstanceMethods
  12. 11 def with_proxy_basic_auth(opts)
  13. 9 with(proxy: opts.merge(scheme: "basic"))
  14. end
  15. 11 def with_proxy_digest_auth(opts)
  16. 27 with(proxy: opts.merge(scheme: "digest"))
  17. end
  18. 11 def with_proxy_ntlm_auth(opts)
  19. 9 with(proxy: opts.merge(scheme: "ntlm"))
  20. end
  21. 11 def fetch_response(request, selector, options)
  22. 2077 response = super
  23. 2077 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. 9 request.transition(:idle)
  29. 8 request.headers["proxy-authorization"] =
  30. options.proxy.authenticate(request, response.headers["proxy-authenticate"])
  31. 9 send_request(request, selector, options)
  32. 8 return
  33. end
  34. 2068 response
  35. end
  36. end
  37. 11 module ConnectionMethods
  38. 11 def force_close(*)
  39. if @state == :connecting
  40. # proxy connect related requests should not be reenqueed
  41. @parser.reset!
  42. @inflight -= @parser.pending.size
  43. @parser.pending.clear
  44. end
  45. super
  46. end
  47. 11 private
  48. 11 def handle_transition(nextstate)
  49. 2864 return super unless @options.proxy && @options.proxy.uri.scheme == "http"
  50. 1350 case nextstate
  51. when :connecting
  52. 374 return unless @state == :idle
  53. 374 @io.connect
  54. 374 return unless @io.connected?
  55. 187 @parser || begin
  56. 178 @parser = parser_type(@io.protocol).new(@write_buffer, @options.merge(max_concurrent_requests: 1))
  57. 178 parser = @parser
  58. 178 parser.extend(ProxyParser)
  59. 178 parser.on(:response, &method(:__http_on_connect))
  60. 178 parser.on(:close) do
  61. 80 next unless @parser
  62. 9 reset
  63. 9 disconnect
  64. end
  65. 178 parser.on(:reset) do
  66. 18 if parser.empty?
  67. 9 reset
  68. else
  69. 9 enqueue_pending_requests_from_parser(parser)
  70. 9 initial_state = @state
  71. 9 reset
  72. 9 if @pending.empty?
  73. @parser = nil
  74. next
  75. end
  76. # keep parser state around due to proxy auth protocol;
  77. # intermediate authenticated request is already inside
  78. # the parser
  79. 9 parser = nil
  80. 9 if initial_state == :connecting
  81. 9 parser = @parser
  82. 9 @parser.reset
  83. end
  84. 9 idling
  85. 9 @parser = parser
  86. 9 transition(:connecting)
  87. end
  88. end
  89. 178 __http_proxy_connect(parser)
  90. end
  91. 187 return if @state == :connected
  92. when :connected
  93. 169 return unless @state == :idle || @state == :connecting
  94. 152 case @state
  95. when :connecting
  96. 71 parser = @parser
  97. 71 @parser = nil
  98. 71 parser.close
  99. when :idle
  100. 98 @parser.callbacks.clear
  101. 98 set_parser_callbacks(@parser)
  102. end
  103. end
  104. 1218 super
  105. end
  106. 11 def __http_proxy_connect(parser)
  107. 178 req = @pending.first
  108. 178 if req && req.uri.scheme == "https"
  109. # if the first request after CONNECT is to an https address, it is assumed that
  110. # all requests in the queue are not only ALL HTTPS, but they also share the certificate,
  111. # and therefore, will share the connection.
  112. #
  113. 80 connect_request = ConnectRequest.new(req.uri, @options)
  114. 72 @inflight += 1
  115. 80 parser.send(connect_request)
  116. else
  117. 98 handle_transition(:connected)
  118. end
  119. end
  120. 11 def __http_on_connect(request, response)
  121. 80 @inflight -= 1
  122. 89 if response.is_a?(Response) && response.status == 200
  123. 71 req = @pending.first
  124. 71 request_uri = req.uri
  125. 71 @io = ProxySSL.new(@io, request_uri, @options)
  126. 71 transition(:connected)
  127. 71 throw(:called)
  128. 17 elsif response.is_a?(Response) &&
  129. response.status == 407 &&
  130. !request.headers.key?("proxy-authorization") &&
  131. @options.proxy.can_authenticate?(response.headers["proxy-authenticate"])
  132. 9 request.transition(:idle)
  133. 8 request.headers["proxy-authorization"] = @options.proxy.authenticate(request, response.headers["proxy-authenticate"])
  134. 9 @parser.send(request)
  135. 8 @inflight += 1
  136. else
  137. 9 pending = @pending + @parser.pending
  138. 24 while (req = pending.shift)
  139. 9 response.finish!
  140. 9 req.response = response
  141. 9 req.emit(:response, response)
  142. end
  143. 9 reset
  144. end
  145. end
  146. end
  147. 11 module ProxyParser
  148. 11 def join_headline(request)
  149. 178 return super if request.verb == "CONNECT"
  150. 80 "#{request.verb} #{request.uri} HTTP/#{@version.join(".")}"
  151. end
  152. 11 def set_protocol_headers(request)
  153. 187 extra_headers = super
  154. 187 proxy_params = @options.proxy
  155. 187 if proxy_params.scheme == "basic"
  156. # opt for basic auth
  157. 97 extra_headers["proxy-authorization"] = proxy_params.authenticate(extra_headers)
  158. end
  159. 187 extra_headers["proxy-connection"] = extra_headers.delete("connection") if extra_headers.key?("connection")
  160. 187 extra_headers
  161. end
  162. end
  163. 11 class ConnectRequest < Request
  164. 11 def initialize(uri, options)
  165. 80 super("CONNECT", uri, options)
  166. 80 @headers.delete("accept")
  167. end
  168. 11 def path
  169. 88 "#{@uri.hostname}:#{@uri.port}"
  170. end
  171. end
  172. end
  173. end
  174. 11 register_plugin :"proxy/http", Proxy::HTTP
  175. end
  176. 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. 11 require "resolv"
  3. 11 require "ipaddr"
  4. 11 module HTTPX
  5. 11 class Socks4Error < ProxyError; end
  6. 11 module Plugins
  7. 11 module Proxy
  8. 11 module Socks4
  9. 11 VERSION = 4
  10. 11 CONNECT = 1
  11. 11 GRANTED = 0x5A
  12. 11 PROTOCOLS = %w[socks4 socks4a].freeze
  13. 11 Error = Socks4Error
  14. 11 class << self
  15. 11 def extra_options(options)
  16. 387 options.merge(supported_proxy_protocols: options.supported_proxy_protocols + PROTOCOLS)
  17. end
  18. end
  19. 11 module ConnectionMethods
  20. 11 def interests
  21. 4729 if @state == :connecting
  22. return @write_buffer.empty? ? :r : :w
  23. end
  24. 4729 super
  25. end
  26. 11 private
  27. 11 def handle_transition(nextstate)
  28. 2936 return super unless @options.proxy && PROTOCOLS.include?(@options.proxy.uri.scheme)
  29. 439 case nextstate
  30. when :connecting
  31. 144 return unless @state == :idle
  32. 144 @io.connect
  33. 144 return unless @io.connected?
  34. 72 req = @pending.first
  35. 72 return unless req
  36. 72 request_uri = req.uri
  37. 72 @write_buffer << Packet.connect(@options.proxy, request_uri)
  38. 72 __socks4_proxy_connect
  39. when :connected
  40. 54 return unless @state == :connecting
  41. 54 @parser = nil
  42. end
  43. 420 log(level: 1) { "SOCKS4: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
  44. 420 super
  45. end
  46. 11 def __socks4_proxy_connect
  47. 72 @parser = SocksParser.new(@write_buffer, @options)
  48. 72 @parser.once(:packet, &method(:__socks4_on_packet))
  49. end
  50. 11 def __socks4_on_packet(packet)
  51. 72 _version, status, _port, _ip = packet.unpack("CCnN")
  52. 72 if status == GRANTED
  53. 54 req = @pending.first
  54. 54 request_uri = req.uri
  55. 54 @io = ProxySSL.new(@io, request_uri, @options) if request_uri.scheme == "https"
  56. 54 transition(:connected)
  57. 54 throw(:called)
  58. else
  59. 18 on_socks4_error("socks error: #{status}")
  60. end
  61. end
  62. 11 def on_socks4_error(message)
  63. 18 ex = Error.new(message)
  64. 18 ex.set_backtrace(caller)
  65. 18 on_error(ex)
  66. 18 throw(:called)
  67. end
  68. end
  69. 11 class SocksParser
  70. 11 include HTTPX::Callbacks
  71. 11 def initialize(buffer, options)
  72. 72 @buffer = buffer
  73. 72 @options = options
  74. end
  75. 11 def close; end
  76. 11 def consume(*); end
  77. 11 def empty?
  78. true
  79. end
  80. 11 def <<(packet)
  81. 72 emit(:packet, packet)
  82. end
  83. end
  84. 11 module Packet
  85. 11 module_function
  86. 11 def connect(parameters, uri)
  87. 72 packet = [VERSION, CONNECT, uri.port].pack("CCn")
  88. 64 case parameters.uri.scheme
  89. when "socks4"
  90. 54 socks_host = uri.host
  91. 5 begin
  92. 108 ip = IPAddr.new(socks_host)
  93. 54 packet << ip.hton
  94. rescue IPAddr::InvalidAddressError
  95. 54 socks_host = Resolv.getaddress(socks_host)
  96. 54 retry
  97. end
  98. 54 packet << [parameters.username].pack("Z*")
  99. when "socks4a"
  100. 18 packet << "\x0\x0\x0\x1" << [parameters.username].pack("Z*") << uri.host << "\x0"
  101. end
  102. 72 packet
  103. end
  104. end
  105. end
  106. end
  107. 11 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. 11 module HTTPX
  3. 11 class Socks5Error < ProxyError; end
  4. 11 module Plugins
  5. 11 module Proxy
  6. 11 module Socks5
  7. 11 VERSION = 5
  8. 11 NOAUTH = 0
  9. 11 PASSWD = 2
  10. 11 NONE = 0xff
  11. 11 CONNECT = 1
  12. 11 IPV4 = 1
  13. 11 DOMAIN = 3
  14. 11 IPV6 = 4
  15. 11 SUCCESS = 0
  16. 11 Error = Socks5Error
  17. 11 class << self
  18. 11 def load_dependencies(*)
  19. 387 require_relative "../auth/socks5"
  20. end
  21. 11 def extra_options(options)
  22. 387 options.merge(supported_proxy_protocols: options.supported_proxy_protocols + %w[socks5])
  23. end
  24. end
  25. 11 module ConnectionMethods
  26. 11 def call
  27. 1559 super
  28. 1559 return unless @options.proxy && @options.proxy.uri.scheme == "socks5"
  29. 378 case @state
  30. when :connecting,
  31. :negotiating,
  32. :authenticating
  33. 175 consume
  34. end
  35. end
  36. 11 def connecting?
  37. 6782 super || @state == :authenticating || @state == :negotiating
  38. end
  39. 11 def interests
  40. 7817 if @state == :connecting || @state == :authenticating || @state == :negotiating
  41. 2874 return @write_buffer.empty? ? :r : :w
  42. end
  43. 4729 super
  44. end
  45. 11 private
  46. 11 def handle_transition(nextstate)
  47. 3260 return super unless @options.proxy && @options.proxy.uri.scheme == "socks5"
  48. 1038 case nextstate
  49. when :connecting
  50. 324 return unless @state == :idle
  51. 324 @io.connect
  52. 324 return unless @io.connected?
  53. 162 @write_buffer << Packet.negotiate(@options.proxy)
  54. 162 __socks5_proxy_connect
  55. when :authenticating
  56. 54 return unless @state == :connecting
  57. 54 @write_buffer << Packet.authenticate(@options.proxy)
  58. when :negotiating
  59. 216 return unless @state == :connecting || @state == :authenticating
  60. 54 req = @pending.first
  61. 54 request_uri = req.uri
  62. 54 @write_buffer << Packet.connect(request_uri)
  63. when :connected
  64. 36 return unless @state == :negotiating
  65. 36 @parser = nil
  66. end
  67. 844 log(level: 1) { "SOCKS5: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
  68. 844 super
  69. end
  70. 11 def __socks5_proxy_connect
  71. 162 @parser = SocksParser.new(@write_buffer, @options)
  72. 162 @parser.on(:packet, &method(:__socks5_on_packet))
  73. 162 transition(:negotiating)
  74. end
  75. 11 def __socks5_on_packet(packet)
  76. 240 case @state
  77. when :connecting
  78. 162 version, method = packet.unpack("CC")
  79. 162 __socks5_check_version(version)
  80. 144 case method
  81. when PASSWD
  82. 54 transition(:authenticating)
  83. 24 nil
  84. when NONE
  85. 90 __on_socks5_error("no supported authorization methods")
  86. else
  87. 18 transition(:negotiating)
  88. end
  89. when :authenticating
  90. 54 _, status = packet.unpack("CC")
  91. 54 return transition(:negotiating) if status == SUCCESS
  92. 18 __on_socks5_error("socks authentication error: #{status}")
  93. when :negotiating
  94. 54 version, reply, = packet.unpack("CC")
  95. 54 __socks5_check_version(version)
  96. 54 __on_socks5_error("socks5 negotiation error: #{reply}") unless reply == SUCCESS
  97. 36 req = @pending.first
  98. 36 request_uri = req.uri
  99. 36 @io = ProxySSL.new(@io, request_uri, @options) if request_uri.scheme == "https"
  100. 36 transition(:connected)
  101. 36 throw(:called)
  102. end
  103. end
  104. 11 def __socks5_check_version(version)
  105. 216 __on_socks5_error("invalid SOCKS version (#{version})") if version != 5
  106. end
  107. 11 def __on_socks5_error(message)
  108. 126 ex = Error.new(message)
  109. 126 ex.set_backtrace(caller)
  110. 126 on_error(ex)
  111. 126 throw(:called)
  112. end
  113. end
  114. 11 class SocksParser
  115. 11 include HTTPX::Callbacks
  116. 11 def initialize(buffer, options)
  117. 162 @buffer = buffer
  118. 162 @options = options
  119. end
  120. 11 def close; end
  121. 11 def consume(*); end
  122. 11 def empty?
  123. true
  124. end
  125. 11 def <<(packet)
  126. 270 emit(:packet, packet)
  127. end
  128. end
  129. 11 module Packet
  130. 11 module_function
  131. 11 def negotiate(parameters)
  132. 162 methods = [NOAUTH]
  133. 162 methods << PASSWD if parameters.can_authenticate?
  134. 162 methods.unshift(methods.size)
  135. 162 methods.unshift(VERSION)
  136. 162 methods.pack("C*")
  137. end
  138. 11 def authenticate(parameters)
  139. 54 parameters.authenticate
  140. end
  141. 11 def connect(uri)
  142. 54 packet = [VERSION, CONNECT, 0].pack("C*")
  143. 5 begin
  144. 54 ip = IPAddr.new(uri.host)
  145. 18 ipcode = ip.ipv6? ? IPV6 : IPV4
  146. 18 packet << [ipcode].pack("C") << ip.hton
  147. rescue IPAddr::InvalidAddressError
  148. 36 packet << [DOMAIN, uri.host.bytesize, uri.host].pack("CCA*")
  149. end
  150. 54 packet << [uri.port].pack("n")
  151. 54 packet
  152. end
  153. end
  154. end
  155. end
  156. 11 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. 7 require "httpx/plugins/proxy"
  3. 7 module HTTPX
  4. 7 module Plugins
  5. 7 module Proxy
  6. 7 module SSH
  7. 7 class << self
  8. 7 def load_dependencies(*)
  9. 14 require "net/ssh/gateway"
  10. end
  11. end
  12. 7 module OptionsMethods
  13. 7 private
  14. 7 def option_proxy(value)
  15. 28 Hash[value]
  16. end
  17. end
  18. 7 module InstanceMethods
  19. 7 def request(*args, **options)
  20. 14 raise ArgumentError, "must perform at least one request" if args.empty?
  21. 14 requests = args.first.is_a?(Request) ? args : build_requests(*args, options)
  22. 14 request = requests.first or return super
  23. 14 request_options = request.options
  24. 14 return super unless request_options.proxy
  25. 14 ssh_options = request_options.proxy
  26. 14 ssh_uris = ssh_options.delete(:uri)
  27. 14 ssh_uri = URI.parse(ssh_uris.shift)
  28. 14 return super unless ssh_uri.scheme == "ssh"
  29. 14 ssh_username = ssh_options.delete(:username)
  30. 14 ssh_options[:port] ||= ssh_uri.port || 22
  31. 14 if request_options.debug
  32. ssh_options[:verbose] = request_options.debug_level == 2 ? :debug : :info
  33. end
  34. 14 request_uri = URI(requests.first.uri)
  35. 14 @_gateway = Net::SSH::Gateway.new(ssh_uri.host, ssh_username, ssh_options)
  36. begin
  37. 14 @_gateway.open(request_uri.host, request_uri.port) do |local_port|
  38. 14 io = build_gateway_socket(local_port, request_uri, request_options)
  39. 14 super(*args, **options.merge(io: io))
  40. end
  41. ensure
  42. 14 @_gateway.shutdown!
  43. end
  44. end
  45. 7 private
  46. 7 def build_gateway_socket(port, request_uri, options)
  47. 14 case request_uri.scheme
  48. when "https"
  49. 7 ctx = OpenSSL::SSL::SSLContext.new
  50. 7 ctx_options = SSL::TLS_OPTIONS.merge(options.ssl)
  51. 7 ctx.set_params(ctx_options) unless ctx_options.empty?
  52. 7 sock = TCPSocket.open("localhost", port)
  53. 7 io = OpenSSL::SSL::SSLSocket.new(sock, ctx)
  54. 7 io.hostname = request_uri.host
  55. 7 io.sync_close = true
  56. 7 io.connect
  57. 7 io.post_connection_check(request_uri.host) if ctx.verify_mode != OpenSSL::SSL::VERIFY_NONE
  58. 7 io
  59. when "http"
  60. 7 TCPSocket.open("localhost", port)
  61. else
  62. raise TypeError, "unexpected scheme: #{request_uri.scheme}"
  63. end
  64. end
  65. end
  66. 7 module ConnectionMethods
  67. # should not coalesce connections here, as the IP is the IP of the proxy
  68. 7 def coalescable?(*)
  69. return super unless @options.proxy
  70. false
  71. end
  72. end
  73. end
  74. end
  75. 7 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. 9 module HTTPX
  3. 9 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. 9 module PushPromise
  13. 9 def self.extra_options(options)
  14. 18 options.merge(http2_settings: { settings_enable_push: 1 },
  15. max_concurrent_requests: 1)
  16. end
  17. 9 module ResponseMethods
  18. 9 def pushed?
  19. 18 @__pushed
  20. end
  21. 9 def mark_as_pushed!
  22. 9 @__pushed = true
  23. end
  24. end
  25. 9 module InstanceMethods
  26. 9 private
  27. 9 def promise_headers
  28. 18 @promise_headers ||= {}
  29. end
  30. 9 def on_promise(parser, stream)
  31. 18 stream.on(:promise_headers) do |h|
  32. 18 __on_promise_request(parser, stream, h)
  33. end
  34. 18 stream.on(:headers) do |h|
  35. 9 __on_promise_response(parser, stream, h)
  36. end
  37. end
  38. 9 def __on_promise_request(parser, stream, h)
  39. 18 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. 18 headers = @options.headers_class.new(h)
  45. 18 path = headers[":path"]
  46. 18 authority = headers[":authority"]
  47. 27 request = parser.pending.find { |r| r.authority == authority && r.path == path }
  48. 18 if request
  49. 9 request.merge_headers(headers)
  50. 8 promise_headers[stream] = request
  51. 9 parser.pending.delete(request)
  52. 8 parser.streams[request] = stream
  53. 9 request.transition(:done)
  54. else
  55. 9 stream.refuse
  56. end
  57. end
  58. 9 def __on_promise_response(parser, stream, h)
  59. 9 request = promise_headers.delete(stream)
  60. 9 return unless request
  61. 9 parser.__send__(:on_stream_headers, stream, request, h)
  62. 9 response = request.response
  63. 9 response.mark_as_pushed!
  64. 9 stream.on(:data, &parser.method(:on_stream_data).curry(3)[stream, request])
  65. 9 stream.on(:close, &parser.method(:on_stream_close).curry(3)[stream, request])
  66. end
  67. end
  68. end
  69. 9 register_plugin(:push_promise, PushPromise)
  70. end
  71. end

lib/httpx/plugins/query.rb

100.0% lines covered

15 relevant lines. 15 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module HTTPX
  3. 9 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. 9 module Query
  9. 9 def self.subplugins
  10. 3 {
  11. 23 retries: QueryRetries,
  12. }
  13. end
  14. 9 module InstanceMethods
  15. 9 def query(*uri, **options)
  16. 18 request("QUERY", uri, **options)
  17. end
  18. end
  19. 9 module QueryRetries
  20. 9 module InstanceMethods
  21. 9 private
  22. 9 def repeatable_request?(request, options)
  23. 27 super || request.verb == "QUERY"
  24. end
  25. end
  26. end
  27. end
  28. 9 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. 9 module HTTPX
  3. 9 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. 9 module RateLimiter
  14. 9 class << self
  15. 9 RATE_LIMIT_CODES = [429, 503].freeze
  16. 9 def configure(klass)
  17. 72 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. 9 def retry_on_rate_limited_response?(response)
  23. 144 return false unless response.is_a?(Response)
  24. 144 status = response.status
  25. 144 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. 9 def retry_after_rate_limit(_, response)
  36. 72 return unless response.is_a?(Response)
  37. 72 retry_after = response.headers["retry-after"]
  38. 72 return unless retry_after
  39. 36 Utils.parse_retry_after(retry_after)
  40. end
  41. end
  42. end
  43. 9 register_plugin :rate_limiter, RateLimiter
  44. end
  45. end

lib/httpx/plugins/response_cache.rb

100.0% lines covered

148 relevant lines. 148 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module HTTPX
  3. 9 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. 9 module ResponseCache
  10. 9 CACHEABLE_VERBS = %w[GET HEAD].freeze
  11. 9 CACHEABLE_STATUS_CODES = [200, 203, 206, 300, 301, 410].freeze
  12. 9 SUPPORTED_VARY_HEADERS = %w[accept accept-encoding accept-language cookie origin].sort.freeze
  13. 9 private_constant :CACHEABLE_VERBS
  14. 9 private_constant :CACHEABLE_STATUS_CODES
  15. 9 class << self
  16. 9 def load_dependencies(*)
  17. 270 require_relative "response_cache/store"
  18. 270 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. 9 def cacheable_response?(response)
  23. 153 response.is_a?(Response) &&
  24. (
  25. 153 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. 9 def not_modified?(response)
  40. 189 response.is_a?(Response) && response.status == 304
  41. end
  42. 9 def extra_options(options)
  43. 270 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. 9 module OptionsMethods
  64. 9 private
  65. 9 def option_response_cache_store(value)
  66. 408 case value
  67. when :store
  68. 288 Store.new
  69. when :file_store
  70. 18 FileStore.new
  71. else
  72. 153 value
  73. end
  74. end
  75. 9 def option_supported_vary_headers(value)
  76. 270 Array(value).sort
  77. end
  78. end
  79. 9 module InstanceMethods
  80. # wipes out all cached responses from the cache store.
  81. 9 def clear_response_cache
  82. 171 @options.response_cache_store.clear
  83. end
  84. 9 def build_request(*)
  85. 558 request = super
  86. 558 return request unless cacheable_request?(request)
  87. 540 prepare_cache(request)
  88. 540 request
  89. end
  90. 9 private
  91. 9 def send_request(request, *)
  92. 189 return request if request.response
  93. 171 super
  94. end
  95. 9 def fetch_response(request, *)
  96. 665 response = super
  97. 665 return unless response
  98. 189 if ResponseCache.not_modified?(response)
  99. 36 log { "returning cached response for #{request.uri}" }
  100. 36 response.copy_from_cached!
  101. 152 elsif request.cacheable_verb? && ResponseCache.cacheable_response?(response)
  102. 126 unless response.cached?
  103. 108 log { "caching response for #{request.uri}..." }
  104. 108 request.options.response_cache_store.set(request, response)
  105. end
  106. end
  107. 189 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. 9 def prepare_cache(request)
  112. 792 cached_response = request.options.response_cache_store.get(request)
  113. 792 return unless cached_response && match_by_vary?(request, cached_response)
  114. 342 cached_response.body.rewind
  115. 342 if cached_response.fresh?
  116. 72 cached_response = cached_response.dup
  117. 72 cached_response.mark_as_cached!
  118. 72 request.response = cached_response
  119. 72 request.emit(:response, cached_response)
  120. 64 return
  121. end
  122. 270 request.cached_response = cached_response
  123. 270 if !request.headers.key?("if-modified-since") && (last_modified = cached_response.headers["last-modified"])
  124. 36 request.headers.add("if-modified-since", last_modified)
  125. end
  126. 270 if !request.headers.key?("if-none-match") && (etag = cached_response.headers["etag"])
  127. 198 request.headers.add("if-none-match", etag)
  128. end
  129. end
  130. 9 def cacheable_request?(request)
  131. 558 request.cacheable_verb? &&
  132. (
  133. 540 !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. 9 def match_by_vary?(request, response)
  139. 342 vary = response.vary
  140. 342 return true unless vary
  141. 108 original_request = response.original_request
  142. 108 if vary == %w[*]
  143. 36 request.options.supported_vary_headers.each do |field|
  144. 180 return false unless request.headers[field] == original_request.headers[field]
  145. end
  146. 32 return true
  147. end
  148. 72 vary.all? do |field|
  149. 72 !original_request.headers.key?(field) || request.headers[field] == original_request.headers[field]
  150. end
  151. end
  152. end
  153. 9 module RequestMethods
  154. # points to a previously cached Response corresponding to this request.
  155. 9 attr_accessor :cached_response
  156. 9 def initialize(*)
  157. 756 super
  158. 756 @cached_response = nil
  159. end
  160. 9 def merge_headers(*)
  161. 369 super
  162. 369 @response_cache_key = nil
  163. end
  164. # returns whether this request is cacheable as per HTTP caching rules.
  165. 9 def cacheable_verb?
  166. 711 CACHEABLE_VERBS.include?(@verb)
  167. end
  168. # returns a unique cache key as a String identifying this request
  169. 9 def response_cache_key
  170. 1575 @response_cache_key ||= begin
  171. 567 keys = [@verb, @uri.merge(path)]
  172. 567 @options.supported_vary_headers.each do |field|
  173. 2835 value = @headers[field]
  174. 2835 keys << value if value
  175. end
  176. 567 Digest::SHA1.hexdigest("httpx-response-cache-#{keys.join("-")}")
  177. end
  178. end
  179. end
  180. 9 module ResponseMethods
  181. 9 attr_writer :original_request
  182. 9 def initialize(*)
  183. 603 super
  184. 603 @cached = false
  185. end
  186. # a copy of the request this response was originally cached from
  187. 9 def original_request
  188. 108 @original_request || @request
  189. end
  190. # whether this Response was duplicated from a previously {RequestMethods#cached_response}.
  191. 9 def cached?
  192. 696 @cached
  193. end
  194. # sets this Response as being duplicated from a previously cached response.
  195. 9 def mark_as_cached!
  196. 270 @cached = true
  197. end
  198. # eager-copies the response headers and body from {RequestMethods#cached_response}.
  199. 9 def copy_from_cached!
  200. 36 cached_response = @request.cached_response
  201. 36 return unless cached_response
  202. # 304 responses do not have content-type, which are needed for decoding.
  203. 36 @headers = @headers.class.new(cached_response.headers.merge(@headers))
  204. 36 @body = cached_response.body.dup
  205. 36 @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. 9 def fresh?
  211. 342 if cache_control
  212. 126 return false if cache_control.include?("no-cache")
  213. 90 return true if cache_control.include?("immutable")
  214. # check age: max-age
  215. 216 max_age = cache_control.find { |directive| directive.start_with?("s-maxage") }
  216. 216 max_age ||= cache_control.find { |directive| directive.start_with?("max-age") }
  217. 90 max_age = max_age[/age=(\d+)/, 1] if max_age
  218. 90 max_age = max_age.to_i if max_age
  219. 90 return max_age > age if max_age
  220. end
  221. # check age: expires
  222. 216 if @headers.key?("expires")
  223. 5 begin
  224. 54 expires = Time.httpdate(@headers["expires"])
  225. rescue ArgumentError
  226. 18 return false
  227. end
  228. 32 return (expires - Time.now).to_i.positive?
  229. end
  230. 162 false
  231. end
  232. # returns the "cache-control" directives as an Array of String(s).
  233. 9 def cache_control
  234. 954 return @cache_control if defined?(@cache_control)
  235. 39 @cache_control = begin
  236. 351 @headers["cache-control"].split(/ *, */) if @headers.key?("cache-control")
  237. end
  238. end
  239. # returns the "vary" header value as an Array of (String) headers.
  240. 9 def vary
  241. 342 return @vary if defined?(@vary)
  242. 30 @vary = begin
  243. 270 @headers["vary"].split(/ *, */).map(&:downcase) if @headers.key?("vary")
  244. end
  245. end
  246. 9 private
  247. # returns the value of the "age" header as an Integer (time since epoch).
  248. # if no "age" of header exists, it returns the number of seconds since {#date}.
  249. 9 def age
  250. 90 return @headers["age"].to_i if @headers.key?("age")
  251. 90 (Time.now - date).to_i
  252. end
  253. # returns the value of the "date" header as a Time object
  254. 9 def date
  255. 90 @date ||= Time.httpdate(@headers["date"])
  256. rescue NoMethodError, ArgumentError
  257. 18 Time.now
  258. end
  259. end
  260. 9 module ResponseBodyMethods
  261. 9 def decode_chunk(chunk)
  262. 570 return chunk if @response.cached?
  263. 358 super
  264. end
  265. end
  266. end
  267. 9 register_plugin :response_cache, ResponseCache
  268. end
  269. end

lib/httpx/plugins/response_cache/file_store.rb

100.0% lines covered

73 relevant lines. 73 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 require "pathname"
  3. 9 module HTTPX::Plugins
  4. 9 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. 9 class FileStore
  11. 9 CRLF = HTTPX::Connection::HTTP1::CRLF
  12. 9 attr_reader :dir
  13. 9 def initialize(dir = Dir.tmpdir)
  14. 99 @dir = Pathname.new(dir).join("httpx-response-cache")
  15. 99 FileUtils.mkdir_p(@dir)
  16. end
  17. 9 def clear
  18. 81 FileUtils.rm_rf(@dir)
  19. end
  20. 9 def get(request)
  21. 378 path = file_path(request)
  22. 378 return unless File.exist?(path)
  23. 189 File.open(path, mode: File::RDONLY | File::BINARY) do |f|
  24. 189 f.flock(File::Constants::LOCK_SH)
  25. 189 read_from_file(request, f)
  26. end
  27. end
  28. 9 def set(request, response)
  29. 117 path = file_path(request)
  30. 117 file_exists = File.exist?(path)
  31. 117 mode = file_exists ? File::RDWR : File::CREAT | File::Constants::WRONLY
  32. 117 File.open(path, mode: mode | File::BINARY) do |f|
  33. 117 f.flock(File::Constants::LOCK_EX)
  34. 117 if file_exists
  35. 9 cached_response = read_from_file(request, f)
  36. 9 if cached_response
  37. 9 next if cached_response == request.cached_response
  38. 9 cached_response.close
  39. 9 f.truncate(0)
  40. 9 f.rewind
  41. end
  42. end
  43. # cache the request headers
  44. 117 f << request.verb << CRLF
  45. 117 f << request.uri << CRLF
  46. 117 request.headers.each do |field, value|
  47. 351 f << field << ":" << value << CRLF
  48. end
  49. 117 f << CRLF
  50. # cache the response
  51. 117 f << response.status << CRLF
  52. 117 f << response.version << CRLF
  53. 117 response.headers.each do |field, value|
  54. 333 f << field << ":" << value << CRLF
  55. end
  56. 117 f << CRLF
  57. 117 response.body.rewind
  58. 117 IO.copy_stream(response.body, f)
  59. end
  60. end
  61. 9 private
  62. 9 def file_path(request)
  63. 495 @dir.join(request.response_cache_key)
  64. end
  65. 9 def read_from_file(request, f)
  66. # if it's an empty file
  67. 198 return if f.eof?
  68. # read request data
  69. 198 verb = f.readline.delete_suffix!(CRLF)
  70. 198 uri = f.readline.delete_suffix!(CRLF)
  71. 198 request_headers = {}
  72. 880 while (line = f.readline) != CRLF
  73. 594 line.delete_suffix!(CRLF)
  74. 594 sep_index = line.index(":")
  75. 594 field = line.byteslice(0..(sep_index - 1))
  76. 594 value = line.byteslice((sep_index + 1)..-1)
  77. 528 request_headers[field] = value
  78. end
  79. 198 status = f.readline.delete_suffix!(CRLF)
  80. 198 version = f.readline.delete_suffix!(CRLF)
  81. 198 response_headers = {}
  82. 856 while (line = f.readline) != CRLF
  83. 567 line.delete_suffix!(CRLF)
  84. 567 sep_index = line.index(":")
  85. 567 field = line.byteslice(0..(sep_index - 1))
  86. 567 value = line.byteslice((sep_index + 1)..-1)
  87. 504 response_headers[field] = value
  88. end
  89. 198 original_request = request.options.request_class.new(verb, uri, request.options)
  90. 198 original_request.merge_headers(request_headers)
  91. 198 response = request.options.response_class.new(request, status, version, response_headers)
  92. 198 response.original_request = original_request
  93. 198 response.finish!
  94. 198 response.mark_as_cached!
  95. 198 IO.copy_stream(f, response.body)
  96. 198 response
  97. end
  98. end
  99. end
  100. 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. 9 module HTTPX::Plugins
  3. 9 module ResponseCache
  4. # Implementation of a thread-safe in-memory cache store.
  5. 9 class Store
  6. 9 def initialize
  7. 360 @store = {}
  8. 360 @store_mutex = Thread::Mutex.new
  9. end
  10. 9 def clear
  11. 180 @store_mutex.synchronize { @store.clear }
  12. end
  13. 9 def get(request)
  14. 549 @store_mutex.synchronize do
  15. 549 @store[request.response_cache_key]
  16. end
  17. end
  18. 9 def set(request, response)
  19. 234 @store_mutex.synchronize do
  20. 234 cached_response = @store[request.response_cache_key]
  21. 234 cached_response.close if cached_response
  22. 208 @store[request.response_cache_key] = response
  23. end
  24. end
  25. end
  26. end
  27. end

lib/httpx/plugins/retries.rb

97.35% lines covered

113 relevant lines. 110 lines covered and 3 lines missed.
    
  1. # frozen_string_literal: true
  2. 19 module HTTPX
  3. 19 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. 19 module Retries
  15. 19 MAX_RETRIES = 3
  16. # TODO: pass max_retries in a configure/load block
  17. 19 IDEMPOTENT_METHODS = %w[GET OPTIONS HEAD PUT DELETE].freeze
  18. # subset of retryable errors which are safe to retry when reconnecting
  19. 2 RECONNECTABLE_ERRORS = [
  20. 17 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. 19 RETRYABLE_ERRORS = (RECONNECTABLE_ERRORS + [
  32. Parser::Error,
  33. TimeoutError,
  34. ]).freeze
  35. 19 DEFAULT_JITTER = ->(interval) { interval * ((rand + 1) * 0.5) }.freeze
  36. # list of supported backoff algorithms
  37. 19 BACKOFF_ALGORITHMS = %i[exponential_backoff polynomial_backoff].freeze
  38. 19 class << self
  39. 19 if ENV.key?("HTTPX_NO_JITTER")
  40. 18 def extra_options(options)
  41. 981 options.merge(max_retries: MAX_RETRIES)
  42. end
  43. else
  44. 1 def extra_options(options)
  45. 7 options.merge(max_retries: MAX_RETRIES, retry_jitter: DEFAULT_JITTER)
  46. end
  47. end
  48. # returns the time to wait before resending +request+ as per the polynomial backoff retry strategy.
  49. 19 def retry_after_polynomial_backoff(request, _)
  50. 36 offset = request.options.max_retries - request.retries
  51. 36 2 * (offset - 1)
  52. end
  53. # returns the time to wait before resending +request+ as per the exponential backoff retry strategy.
  54. 19 def retry_after_exponential_backoff(request, _)
  55. 36 offset = request.options.max_retries - request.retries
  56. 36 (offset - 1) * 2
  57. end
  58. end
  59. # adds support for the following options:
  60. #
  61. # :max_retries :: max number of times a request will be retried (defaults to <tt>3</tt>).
  62. # :retry_change_requests :: whether idempotent requests are retried (defaults to <tt>false</tt>).
  63. # :retry_after:: seconds after which a request is retried; can also be a callable object (i.e. <tt>->(req, res) { ... } </tt>)
  64. # or the name of a supported backoff algorithm (i.e. <tt>:exponential_backoff</tt>).
  65. # :retry_jitter :: number of seconds applied to *:retry_after* (must be a callable, i.e. <tt>->(retry_after) { ... } </tt>).
  66. # :retry_on :: callable which alternatively defines a different rule for when a response is to be retried
  67. # (i.e. <tt>->(res) { ... }</tt>).
  68. 19 module OptionsMethods
  69. 19 private
  70. 19 def option_retry_after(value)
  71. 342 if value.respond_to?(:call)
  72. 198 value1 = value
  73. 198 value1 = value1.method(:call) unless value1.respond_to?(:arity)
  74. # allow ->(*) arity as well, which is < 0
  75. 198 raise TypeError, "`:retry_after` proc has invalid number of parameters" unless value1.arity.negative? || value1.arity.between?(
  76. 1, 2
  77. )
  78. else
  79. 128 case value
  80. when Symbol
  81. 36 raise TypeError, "`retry_after`: `#{value}` is not a supported backoff algorithm" unless BACKOFF_ALGORITHMS.include?(value)
  82. 36 value = Retries.method(:"retry_after_#{value}")
  83. else
  84. 108 value = Float(value)
  85. 108 raise TypeError, "`:retry_after` must be positive" unless value.positive?
  86. end
  87. end
  88. 342 value
  89. end
  90. 19 def option_retry_jitter(value)
  91. # return early if callable
  92. 68 raise TypeError, ":retry_jitter must be callable" unless value.respond_to?(:call)
  93. 68 value
  94. end
  95. 19 def option_max_retries(value)
  96. 3181 num = Integer(value)
  97. 3181 raise TypeError, ":max_retries must be positive" unless num >= 0
  98. 3181 num
  99. end
  100. 19 def option_retry_change_requests(v)
  101. 153 v
  102. end
  103. 19 def option_retry_on(value)
  104. 394 raise TypeError, ":retry_on must be called with the response" unless value.respond_to?(:call)
  105. 394 value
  106. end
  107. end
  108. 19 module InstanceMethods
  109. # returns a `:retries` plugin enabled session with +n+ maximum retries per request setting.
  110. 19 def max_retries(n)
  111. 144 with(max_retries: n)
  112. end
  113. 19 private
  114. 19 def fetch_response(request, selector, options)
  115. 6766 response = super
  116. 6766 if response &&
  117. request.retries.positive? &&
  118. repeatable_request?(request, options) &&
  119. (
  120. 115 (
  121. 564 response.is_a?(ErrorResponse) && retryable_error?(response.error)
  122. ) ||
  123. options.retry_on&.call(response)
  124. )
  125. 677 try_partial_retry(request, response)
  126. 677 log { "failed to get response, #{request.retries} tries to go..." }
  127. 677 prepare_to_retry(request, response)
  128. 677 retry_after = options.retry_after
  129. 677 retry_after = retry_after.call(request, response) if retry_after.respond_to?(:call)
  130. 677 if retry_after
  131. # apply jitter
  132. 180 if (jitter = request.options.retry_jitter)
  133. 18 retry_after = jitter.call(retry_after)
  134. end
  135. 180 retry_start = Utils.now
  136. 180 log { "retrying after #{retry_after} secs..." }
  137. 180 selector.after(retry_after) do
  138. 180 if (response = request.response)
  139. response.finish!
  140. # request has terminated abruptly meanwhile
  141. request.emit(:response, response)
  142. else
  143. 180 log { "retrying (elapsed time: #{Utils.elapsed_time(retry_start)})!!" }
  144. 180 send_request(request, selector, options)
  145. end
  146. end
  147. else
  148. 497 send_request(request, selector, options)
  149. end
  150. 607 return
  151. end
  152. 6089 response
  153. end
  154. # returns whether +request+ can be retried.
  155. 19 def repeatable_request?(request, options)
  156. 1461 IDEMPOTENT_METHODS.include?(request.verb) || options.retry_change_requests
  157. end
  158. # returns whether the +ex+ exception happend for a retriable request.
  159. 19 def retryable_error?(ex)
  160. 5178 RETRYABLE_ERRORS.any? { |klass| ex.is_a?(klass) }
  161. end
  162. 19 def proxy_error?(request, response, _)
  163. 72 super && !request.retries.positive?
  164. end
  165. 19 def prepare_to_retry(request, _response)
  166. 677 request.retries -= 1 unless request.ping? # do not exhaust retries on connection liveness probes
  167. 677 request.transition(:idle)
  168. end
  169. #
  170. # Attempt to set the request to perform a partial range request.
  171. # This happens if the peer server accepts byte-range requests, and
  172. # the last response contains some body payload.
  173. #
  174. 19 def try_partial_retry(request, response)
  175. 677 response = response.response if response.is_a?(ErrorResponse)
  176. 677 return unless response
  177. 311 unless response.headers.key?("accept-ranges") &&
  178. response.headers["accept-ranges"] == "bytes" && # there's nothing else supported though...
  179. 18 (original_body = response.body)
  180. 293 response.body.close
  181. 262 return
  182. end
  183. 18 request.partial_response = response
  184. 18 size = original_body.bytesize
  185. 16 request.headers["range"] = "bytes=#{size}-"
  186. end
  187. end
  188. 19 module RequestMethods
  189. # number of retries left.
  190. 19 attr_accessor :retries
  191. # a response partially received before.
  192. 19 attr_writer :partial_response
  193. # initializes the request instance, sets the number of retries for the request.
  194. 19 def initialize(*args)
  195. 1093 super
  196. 1093 @retries = @options.max_retries
  197. end
  198. 19 def response=(response)
  199. 1797 if @partial_response
  200. 18 if response.is_a?(Response) && response.status == 206
  201. 18 response.from_partial_response(@partial_response)
  202. else
  203. @partial_response.close
  204. end
  205. 18 @partial_response = nil
  206. end
  207. 1797 super
  208. end
  209. end
  210. 19 module ResponseMethods
  211. 19 def from_partial_response(response)
  212. 18 @status = response.status
  213. 18 @headers = response.headers
  214. 18 @body = response.body
  215. end
  216. end
  217. end
  218. 19 register_plugin :retries, Retries
  219. end
  220. 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. 9 module HTTPX
  3. 9 class ServerSideRequestForgeryError < Error; end
  4. 9 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. 9 module SsrfFilter
  11. 9 module IPAddrExtensions
  12. 9 refine IPAddr do
  13. 9 def prefixlen
  14. 144 mask_addr = @mask_addr
  15. 144 raise "Invalid mask" if mask_addr.zero?
  16. 403 mask_addr >>= 1 while mask_addr.nobits?(0x1)
  17. 144 length = 0
  18. 397 while mask_addr & 0x1 == 0x1
  19. 2024 length += 1
  20. 2024 mask_addr >>= 1
  21. end
  22. 144 length
  23. end
  24. end
  25. end
  26. 9 using IPAddrExtensions
  27. # https://en.wikipedia.org/wiki/Reserved_IP_addresses
  28. 2 IPV4_BLACKLIST = [
  29. 7 IPAddr.new("0.0.0.0/8"), # Current network (only valid as source address)
  30. IPAddr.new("10.0.0.0/8"), # Private network
  31. IPAddr.new("100.64.0.0/10"), # Shared Address Space
  32. IPAddr.new("127.0.0.0/8"), # Loopback
  33. IPAddr.new("169.254.0.0/16"), # Link-local
  34. IPAddr.new("172.16.0.0/12"), # Private network
  35. IPAddr.new("192.0.0.0/24"), # IETF Protocol Assignments
  36. IPAddr.new("192.0.2.0/24"), # TEST-NET-1, documentation and examples
  37. IPAddr.new("192.88.99.0/24"), # IPv6 to IPv4 relay (includes 2002::/16)
  38. IPAddr.new("192.168.0.0/16"), # Private network
  39. IPAddr.new("198.18.0.0/15"), # Network benchmark tests
  40. IPAddr.new("198.51.100.0/24"), # TEST-NET-2, documentation and examples
  41. IPAddr.new("203.0.113.0/24"), # TEST-NET-3, documentation and examples
  42. IPAddr.new("224.0.0.0/4"), # IP multicast (former Class D network)
  43. IPAddr.new("240.0.0.0/4"), # Reserved (former Class E network)
  44. IPAddr.new("255.255.255.255"), # Broadcast
  45. ].freeze
  46. 3 IPV6_BLACKLIST = ([
  47. 7 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. 144 prefixlen = ipaddr.prefixlen
  60. 144 ipv4_compatible = ipaddr.ipv4_compat.mask(96 + prefixlen)
  61. 144 ipv4_mapped = ipaddr.ipv4_mapped.mask(80 + prefixlen)
  62. 144 [ipv4_compatible, ipv4_mapped]
  63. end).freeze
  64. 9 class << self
  65. 9 def extra_options(options)
  66. 79 options.merge(allowed_schemes: %w[https http])
  67. end
  68. 9 def unsafe_ip_address?(ipaddr)
  69. 88 range = ipaddr.to_range
  70. 88 return true if range.first != range.last
  71. 106 return IPV6_BLACKLIST.any? { |r| r.include?(ipaddr) } if ipaddr.ipv6?
  72. 760 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. 9 module OptionsMethods
  79. 9 private
  80. 9 def option_allowed_schemes(value)
  81. 88 Array(value)
  82. end
  83. end
  84. 9 module InstanceMethods
  85. 9 def send_requests(*requests)
  86. 97 responses = requests.map do |request|
  87. 97 next if @options.allowed_schemes.include?(request.uri.scheme)
  88. 9 error = ServerSideRequestForgeryError.new("#{request.uri} URI scheme not allowed")
  89. 9 error.set_backtrace(caller)
  90. 9 response = ErrorResponse.new(request, error)
  91. 9 request.emit(:response, response)
  92. 9 response
  93. end
  94. 194 allowed_requests = requests.select { |req| responses[requests.index(req)].nil? }
  95. 97 allowed_responses = super(*allowed_requests)
  96. 97 allowed_responses.each_with_index do |res, idx|
  97. 88 req = allowed_requests[idx]
  98. 78 responses[requests.index(req)] = res
  99. end
  100. 97 responses
  101. end
  102. end
  103. 9 module ConnectionMethods
  104. 9 def initialize(*)
  105. begin
  106. 88 super
  107. 8 rescue ServerSideRequestForgeryError => e
  108. # may raise when IPs are passed as options via :addresses
  109. 18 throw(:resolve_error, e)
  110. end
  111. end
  112. 9 def addresses=(addrs)
  113. 88 addrs.reject!(&SsrfFilter.method(:unsafe_ip_address?))
  114. 88 raise ServerSideRequestForgeryError, "#{@origin.host} has no public IP addresses" if addrs.empty?
  115. 18 super
  116. end
  117. end
  118. end
  119. 9 register_plugin :ssrf_filter, SsrfFilter
  120. end
  121. end

lib/httpx/plugins/stream.rb

97.32% lines covered

112 relevant lines. 109 lines covered and 3 lines missed.
    
  1. # frozen_string_literal: true
  2. 19 module HTTPX
  3. 19 class StreamResponse
  4. 19 attr_reader :request
  5. 19 def initialize(request, session)
  6. 243 @request = request
  7. 243 @options = @request.options
  8. 243 @session = session
  9. 243 @response_enum = nil
  10. 243 @buffered_chunks = []
  11. end
  12. 19 def each(&block)
  13. 419 return enum_for(__method__) unless block
  14. 261 if (response_enum = @response_enum)
  15. 18 @response_enum = nil
  16. # streaming already started, let's finish it
  17. 48 while (chunk = @buffered_chunks.shift)
  18. 18 block.call(chunk)
  19. end
  20. # consume enum til the end
  21. 1 begin
  22. 60 while (chunk = response_enum.next)
  23. 32 block.call(chunk)
  24. end
  25. rescue StopIteration
  26. 18 return
  27. end
  28. end
  29. 243 @request.stream = self
  30. 20 begin
  31. 243 @on_chunk = block
  32. 243 response = @session.request(@request)
  33. 216 response.raise_for_status
  34. ensure
  35. 216 @on_chunk = nil
  36. end
  37. end
  38. 19 def each_line
  39. 122 return enum_for(__method__) unless block_given?
  40. 61 line = "".b
  41. 61 each do |chunk|
  42. 55 line << chunk
  43. 155 while (idx = line.index("\n"))
  44. 61 yield line.byteslice(0..(idx - 1))
  45. 61 line = line.byteslice((idx + 1)..-1)
  46. end
  47. end
  48. 25 yield line unless line.empty?
  49. end
  50. # This is a ghost method. It's to be used ONLY internally, when processing streams
  51. 19 def on_chunk(chunk)
  52. 502 raise NoMethodError unless @on_chunk
  53. 502 @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. 19 def to_s
  61. 18 if @request.response
  62. @request.response.to_s
  63. else
  64. 18 @buffered_chunks.join
  65. end
  66. end
  67. 19 private
  68. 19 def response
  69. 469 @request.response || begin
  70. 50 response_enum = each
  71. 90 while (chunk = response_enum.next)
  72. 45 @buffered_chunks << chunk
  73. 45 break if @request.response
  74. end
  75. 45 @response_enum = response_enum
  76. 45 @request.response
  77. end
  78. end
  79. 19 def respond_to_missing?(meth, include_private)
  80. 37 if (response = @request.response)
  81. response.respond_to_missing?(meth, include_private)
  82. else
  83. 37 @options.response_class.method_defined?(meth) || (include_private && @options.response_class.private_method_defined?(meth))
  84. end || super
  85. end
  86. 19 def method_missing(meth, *args, **kwargs, &block)
  87. 237 return super unless response.respond_to?(meth)
  88. 232 response.__send__(meth, *args, **kwargs, &block)
  89. end
  90. end
  91. 19 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. 19 module Stream
  98. 19 STREAM_REQUEST_OPTIONS = { timeout: { read_timeout: Float::INFINITY, operation_timeout: 60 }.freeze }.freeze
  99. 19 def self.extra_options(options)
  100. 437 options.merge(
  101. stream: false,
  102. timeout: { read_timeout: Float::INFINITY, operation_timeout: 60 },
  103. stream_response_class: Class.new(StreamResponse, &Options::SET_TEMPORARY_NAME).freeze
  104. )
  105. end
  106. # adds support for the following options:
  107. #
  108. # :stream :: whether the request to process should be handled as a stream (defaults to <tt>false</tt>).
  109. # :stream_response_class :: Class used to build the stream response object.
  110. 19 module OptionsMethods
  111. 19 def option_stream(val)
  112. 327 val
  113. end
  114. 19 def option_stream_response_class(value)
  115. 1067 value
  116. end
  117. 19 def extend_with_plugin_classes(pl)
  118. 238 return super unless defined?(pl::StreamResponseMethods)
  119. 166 @stream_response_class = @stream_response_class.dup
  120. 166 Options::SET_TEMPORARY_NAME[@stream_response_class, pl]
  121. 166 @stream_response_class.__send__(:include, pl::StreamResponseMethods) if defined?(pl::StreamResponseMethods)
  122. 166 super
  123. end
  124. end
  125. 19 module InstanceMethods
  126. 19 def request(*args, **options)
  127. 650 if args.first.is_a?(Request)
  128. 435 requests = args
  129. 435 request = requests.first
  130. 435 unless request.options.stream && !request.stream
  131. 362 if options[:stream]
  132. warn "passing `stream: true` with a request object is not supported anymore. " \
  133. "You can instead build the request object with `stream :true`"
  134. end
  135. 362 return super
  136. end
  137. else
  138. 215 return super unless options[:stream]
  139. 188 requests = build_requests(*args, options)
  140. 188 request = requests.first
  141. end
  142. 261 raise Error, "only 1 response at a time is supported for streaming requests" unless requests.size == 1
  143. 243 @options.stream_response_class.new(request, self)
  144. end
  145. 19 def build_request(verb, uri, params = EMPTY_HASH, options = @options)
  146. 459 return super unless params[:stream]
  147. 288 super(verb, uri, params, options.merge(STREAM_REQUEST_OPTIONS.merge(stream: true)))
  148. end
  149. end
  150. 19 module RequestMethods
  151. 19 attr_accessor :stream
  152. end
  153. 19 module ResponseMethods
  154. 19 def stream
  155. 386 request = @request.root_request if @request.respond_to?(:root_request)
  156. 386 request ||= @request
  157. 386 request.stream
  158. end
  159. end
  160. 19 module ResponseBodyMethods
  161. 19 def initialize(*)
  162. 386 super
  163. 386 @stream = @response.stream
  164. end
  165. 19 def write(chunk)
  166. 699 return super unless @stream
  167. 583 return 0 if chunk.empty?
  168. 502 chunk = decode_chunk(chunk)
  169. 502 @stream.on_chunk(chunk.dup)
  170. 475 chunk.bytesize
  171. end
  172. 19 private
  173. 19 def transition(*)
  174. 153 return if @stream
  175. 144 super
  176. end
  177. end
  178. end
  179. 19 register_plugin :stream, Stream
  180. end
  181. end

lib/httpx/plugins/stream_bidi.rb

94.25% lines covered

174 relevant lines. 164 lines covered and 10 lines missed.
    
  1. # frozen_string_literal: true
  2. 9 module HTTPX
  3. 9 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. 9 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. 9 module HTTP2Methods
  19. 9 def initialize(*)
  20. 63 super
  21. 63 @lock = Thread::Mutex.new
  22. end
  23. 9 %i[close empty? exhausted? send <<].each do |lock_meth|
  24. 45 class_eval(<<-METH, __FILE__, __LINE__ + 1)
  25. 5 # lock.aware version of +#{lock_meth}+
  26. 5 def #{lock_meth}(*) # def close(*)
  27. return super unless @options.stream
  28. return super if @lock.owned?
  29. # small race condition between
  30. # checking for ownership and
  31. # acquiring lock.
  32. # TODO: fix this at the parser.
  33. @lock.synchronize { super }
  34. end
  35. METH
  36. end
  37. 9 private
  38. 9 %i[join_headers join_trailers join_body].each do |lock_meth|
  39. 27 class_eval(<<-METH, __FILE__, __LINE__ + 1)
  40. 3 # lock.aware version of +#{lock_meth}+
  41. 3 private def #{lock_meth}(*) # private def join_headers(*)
  42. return super unless @options.stream
  43. return super if @lock.owned?
  44. # small race condition between
  45. # checking for ownership and
  46. # acquiring lock.
  47. # TODO: fix this at the parser.
  48. @lock.synchronize { super }
  49. end
  50. METH
  51. end
  52. 9 def handle_stream(stream, request)
  53. 63 return super unless @options.stream
  54. 54 request.on(:body) do
  55. 243 next unless request.headers_sent
  56. 180 handle(request, stream)
  57. 180 emit(:flush_buffer)
  58. end
  59. 54 super
  60. end
  61. # when there ain't more chunks, it makes the buffer as full.
  62. 9 def send_chunk(request, stream, chunk, next_chunk)
  63. 252 return super unless @options.stream
  64. 252 super
  65. 252 return if next_chunk
  66. 234 request.transition(:waiting_for_chunk)
  67. 234 throw(:buffer_full)
  68. end
  69. # sets end-stream flag when the request is closed.
  70. 9 def end_stream?(request, next_chunk)
  71. 252 return super unless @options.stream
  72. 252 request.closed? && next_chunk.nil?
  73. end
  74. end
  75. # BidiBuffer is a thread-safe Buffer which can receive data from any thread.
  76. #
  77. # It uses a dual-buffer strategy with mutex protection:
  78. # - +@buffer+ is the main buffer, protected by +@buffer_mutex+
  79. # - +@oob_buffer+ receives data when +@buffer_mutex+ is contended
  80. #
  81. # This allows non-blocking writes from any thread while maintaining thread safety.
  82. 9 class BidiBuffer < Buffer
  83. 9 def initialize(*)
  84. 36 super
  85. 36 @buffer_mutex = Thread::Mutex.new
  86. 36 @oob_mutex = Thread::Mutex.new
  87. 36 @oob_buffer = "".b
  88. end
  89. # buffers the +chunk+ to be sent (thread-safe, non-blocking)
  90. 9 def <<(chunk)
  91. if @buffer_mutex.try_lock
  92. begin
  93. super
  94. ensure
  95. @buffer_mutex.unlock
  96. end
  97. else
  98. # another thread holds the lock, use OOB buffer to avoid blocking
  99. @oob_mutex.synchronize { @oob_buffer << chunk }
  100. end
  101. end
  102. # reconciles the main and secondary buffer (thread-safe, callable from any thread).
  103. 9 def rebuffer
  104. 2520 @buffer_mutex.synchronize do
  105. 2520 @oob_mutex.synchronize do
  106. 2520 return if @oob_buffer.empty?
  107. @buffer << @oob_buffer
  108. @oob_buffer.clear
  109. end
  110. end
  111. end
  112. 9 Buffer.instance_methods - Object.instance_methods - %i[<<].each do |meth|
  113. 9 class_eval(<<-MOD, __FILE__, __LINE__ + 1)
  114. 1 def #{meth}(*) # def empty?
  115. @buffer_mutex.synchronize { super }
  116. end
  117. MOD
  118. end
  119. end
  120. # Proxy to wake up the session main loop when one
  121. # of the connections has buffered data to write. It abides by the HTTPX::_Selectable API,
  122. # which allows it to be registered in the selector alongside actual HTTP-based
  123. # HTTPX::Connection objects.
  124. 9 class Signal
  125. 9 attr_reader :error
  126. 9 def initialize
  127. 72 @closed = false
  128. 72 @error = nil
  129. 72 @pipe_read, @pipe_write = IO.pipe
  130. end
  131. 9 def state
  132. 493 @closed ? :closed : :open
  133. end
  134. # noop
  135. 9 def log(**, &_); end
  136. 9 def to_io
  137. 912 @pipe_read.to_io
  138. end
  139. 9 def wakeup
  140. 180 return if @closed
  141. 135 @pipe_write.write("\0")
  142. end
  143. 9 def call
  144. 127 return if @closed
  145. 127 @pipe_read.readpartial(1)
  146. end
  147. 9 def interests
  148. 493 return if @closed
  149. 484 :r
  150. end
  151. 9 def timeout; end
  152. 9 def inflight?
  153. !@closed
  154. end
  155. 9 def terminate
  156. 63 return if @closed
  157. 45 @pipe_write.close
  158. 45 @pipe_read.close
  159. 45 @closed = true
  160. end
  161. 9 def on_error(error)
  162. @error = error
  163. terminate
  164. end
  165. # noop (the owner connection will take of it)
  166. 9 def handle_socket_timeout(interval); end
  167. end
  168. 9 class << self
  169. 9 def load_dependencies(klass)
  170. 63 klass.plugin(:stream)
  171. end
  172. 9 def extra_options(options)
  173. 63 options.merge(fallback_protocol: "h2")
  174. end
  175. end
  176. 9 module InstanceMethods
  177. 9 def initialize(*)
  178. 72 @signal = Signal.new
  179. 72 super
  180. end
  181. 9 def close(selector = Selector.new)
  182. 63 @signal.terminate
  183. 63 selector.deregister(@signal)
  184. 63 super
  185. end
  186. 9 def select_connection(connection, selector)
  187. 99 return super unless connection.options.stream
  188. 90 super
  189. 90 selector.register(@signal)
  190. 90 connection.signal = @signal
  191. end
  192. 9 def deselect_connection(connection, *)
  193. 54 return super unless connection.options.stream
  194. 45 super
  195. 45 connection.signal = nil
  196. end
  197. end
  198. # Adds synchronization to request operations which may buffer payloads from different
  199. # threads.
  200. 9 module RequestMethods
  201. 9 attr_accessor :headers_sent
  202. 9 def initialize(*)
  203. 63 super
  204. 54 @headers_sent = false
  205. 54 @closed = false
  206. 54 @mutex = Thread::Mutex.new
  207. end
  208. 9 def closed?
  209. 252 return super unless @options.stream
  210. 252 @closed
  211. end
  212. 9 def can_buffer?
  213. 549 return super unless @options.stream
  214. 532 super && @state != :waiting_for_chunk
  215. end
  216. # overrides state management transitions to introduce an intermediate
  217. # +:waiting_for_chunk+ state, which the request transitions to once payload
  218. # is buffered.
  219. 9 def transition(nextstate)
  220. 944 return super unless @options.stream
  221. 908 headers_sent = @headers_sent
  222. 804 case nextstate
  223. when :idle
  224. 9 headers_sent = false
  225. when :waiting_for_chunk
  226. 234 return unless @state == :body
  227. when :body
  228. 377 case @state
  229. when :headers
  230. 54 headers_sent = true
  231. when :waiting_for_chunk
  232. # HACK: to allow super to pass through
  233. 180 @state = :headers
  234. end
  235. end
  236. 908 super.tap do
  237. # delay setting this up until after the first transition to :body
  238. 908 @headers_sent = headers_sent
  239. end
  240. end
  241. 9 def <<(chunk)
  242. 189 @mutex.synchronize do
  243. 189 if @drainer
  244. 180 @body.clear if @body.respond_to?(:clear)
  245. 180 @drainer = nil
  246. end
  247. 189 @body << chunk
  248. 189 transition(:body)
  249. end
  250. end
  251. 9 def close
  252. 45 return super unless @options.stream
  253. 45 @mutex.synchronize do
  254. 45 return if @closed
  255. 45 @closed = true
  256. end
  257. # last chunk to send which ends the stream
  258. 45 self << ""
  259. end
  260. end
  261. 9 module RequestBodyMethods
  262. 9 def initialize(*, **)
  263. 63 super
  264. 63 return unless @options.stream
  265. 54 @headers.delete("content-length")
  266. 54 return unless @body
  267. 54 return if @body.is_a?(Transcoder::Body::Encoder)
  268. 9 raise Error, "bidirectional streams only allow the usage of the `:body` param to set request bodies." \
  269. "You must encode it yourself if you wish to do so."
  270. end
  271. 9 def empty?
  272. 326 return super unless @options.stream
  273. 299 false
  274. end
  275. end
  276. # overrides the declaration of +@write_buffer+, which is now a thread-safe buffer
  277. # responding to the same API.
  278. 9 module ConnectionMethods
  279. 9 attr_writer :signal
  280. 9 def initialize(*)
  281. 45 super
  282. 45 return unless @options.stream
  283. 36 @write_buffer = BidiBuffer.new(@options.buffer_size)
  284. end
  285. # rebuffers the +@write_buffer+ before calculating interests.
  286. 9 def interests
  287. 2694 return super unless @options.stream
  288. 2520 @write_buffer.rebuffer
  289. 2520 super
  290. end
  291. 9 def call
  292. 483 return super unless @options.stream && (error = @signal.error)
  293. on_error(error)
  294. end
  295. 9 private
  296. 9 def set_parser_callbacks(parser)
  297. 63 return super unless @options.stream
  298. 54 super
  299. 54 parser.on(:flush_buffer) do
  300. 180 @signal.wakeup if @signal
  301. end
  302. end
  303. end
  304. end
  305. 9 register_plugin :stream_bidi, StreamBidi
  306. end
  307. 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. 9 module HTTPX
  3. 9 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. 9 module Upgrade
  11. 9 class << self
  12. 9 def configure(klass)
  13. 35 klass.plugin(:"upgrade/h2")
  14. end
  15. 9 def extra_options(options)
  16. 35 options.merge(upgrade_handlers: {})
  17. end
  18. end
  19. 9 module OptionsMethods
  20. 9 private
  21. 9 def option_upgrade_handlers(value)
  22. 115 raise TypeError, ":upgrade_handlers must be a Hash" unless value.is_a?(Hash)
  23. 115 value
  24. end
  25. end
  26. 9 module InstanceMethods
  27. 9 def fetch_response(request, selector, options)
  28. 303 response = super
  29. 303 if response
  30. 111 return response unless response.is_a?(Response)
  31. 111 return response unless response.headers.key?("upgrade")
  32. 49 upgrade_protocol = response.headers["upgrade"].split(/ *, */).first
  33. 49 return response unless upgrade_protocol && options.upgrade_handlers.key?(upgrade_protocol)
  34. 49 protocol_handler = options.upgrade_handlers[upgrade_protocol]
  35. 49 return response unless protocol_handler
  36. 49 log { "upgrading to #{upgrade_protocol}..." }
  37. 49 connection = find_connection(request.uri, selector, options)
  38. # do not upgrade already upgraded connections
  39. 49 return if connection.upgrade_protocol == upgrade_protocol
  40. 35 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. 35 return if response.status == 101 && !connection.hijacked
  45. end
  46. 209 response
  47. end
  48. end
  49. 9 module ConnectionMethods
  50. 9 attr_reader :upgrade_protocol, :hijacked
  51. 9 def initialize(*)
  52. 44 super
  53. 44 @upgrade_protocol = nil
  54. end
  55. 9 def hijack_io
  56. 9 @hijacked = true
  57. # connection is taken away from selector and not given back to the pool.
  58. 9 @current_session.deselect_connection(self, @current_selector, true)
  59. end
  60. end
  61. end
  62. 9 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. 9 module HTTPX
  3. 9 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. 9 module H2
  11. 9 class << self
  12. 9 def extra_options(options)
  13. 35 options.merge(upgrade_handlers: options.upgrade_handlers.merge("h2" => self))
  14. end
  15. 9 def call(connection, _request, _response)
  16. 8 connection.upgrade_to_h2
  17. end
  18. end
  19. 9 module ConnectionMethods
  20. 9 using URIExtensions
  21. 9 def interests
  22. 952 return super unless connecting? && @parser
  23. 15 connect
  24. 15 return @io.interests if connecting?
  25. super
  26. end
  27. 9 def upgrade_to_h2
  28. 8 prev_parser = @parser
  29. 8 if prev_parser
  30. 8 prev_parser.reset
  31. 7 @inflight -= prev_parser.requests.size
  32. end
  33. 8 @parser = @options.http2_class.new(@write_buffer, @options)
  34. 8 set_parser_callbacks(@parser)
  35. 8 @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. 8 purge_after_closed
  42. 8 transition(:idle)
  43. 8 prev_parser.requests.each do |req|
  44. req.transition(:idle)
  45. send(req)
  46. end
  47. end
  48. end
  49. end
  50. 9 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. 9 module HTTPX
  3. 9 module Plugins
  4. #
  5. # This plugin implements convenience methods for performing WEBDAV requests.
  6. #
  7. # https://gitlab.com/os85/httpx/wikis/WebDav
  8. #
  9. 9 module WebDav
  10. 9 def self.configure(klass)
  11. 108 klass.plugin(:xml)
  12. end
  13. 9 module InstanceMethods
  14. 9 def copy(src, dest)
  15. 18 request("COPY", src, headers: { "destination" => @options.origin.merge(dest) })
  16. end
  17. 9 def move(src, dest)
  18. 18 request("MOVE", src, headers: { "destination" => @options.origin.merge(dest) })
  19. end
  20. 9 def lock(path, timeout: nil, &blk)
  21. 54 headers = {}
  22. 48 headers["timeout"] = if timeout && timeout.positive?
  23. 18 "Second-#{timeout}"
  24. else
  25. 36 "Infinite, Second-4100000000"
  26. end
  27. 54 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. 54 response = request("LOCK", path, headers: headers, xml: xml)
  34. 54 return response unless response.is_a?(Response)
  35. 54 return response unless blk && response.status == 200
  36. 18 lock_token = response.headers["lock-token"]
  37. 1 begin
  38. 18 blk.call(response)
  39. ensure
  40. 18 unlock(path, lock_token)
  41. end
  42. 18 response
  43. end
  44. 9 def unlock(path, lock_token)
  45. 36 request("UNLOCK", path, headers: { "lock-token" => lock_token })
  46. end
  47. 9 def mkcol(dir)
  48. 18 request("MKCOL", dir)
  49. end
  50. 9 def propfind(path, xml = nil)
  51. 72 body = case xml
  52. when :acl
  53. 18 '<?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. 36 '<?xml version="1.0" encoding="utf-8"?><DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
  57. else
  58. 18 xml
  59. end
  60. 72 request("PROPFIND", path, headers: { "depth" => "1" }, xml: body)
  61. end
  62. 9 def proppatch(path, xml)
  63. 8 body = "<?xml version=\"1.0\"?>" \
  64. 12 "<D:propertyupdate xmlns:D=\"DAV:\" xmlns:Z=\"http://ns.example.com/standards/z39.50/\">#{xml}</D:propertyupdate>"
  65. 18 request("PROPPATCH", path, xml: body)
  66. end
  67. # %i[ orderpatch acl report search]
  68. end
  69. end
  70. 9 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. 9 module HTTPX
  3. 9 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. 9 module XML
  10. 9 MIME_TYPES = %r{\b(application|text)/(.+\+)?xml\b}.freeze
  11. 9 module Transcoder
  12. 9 module_function
  13. 9 class Encoder
  14. 9 def initialize(xml)
  15. 180 @raw = xml
  16. end
  17. 9 def content_type
  18. 180 charset = @raw.respond_to?(:encoding) && @raw.encoding ? @raw.encoding.to_s.downcase : "utf-8"
  19. 180 "application/xml; charset=#{charset}"
  20. end
  21. 9 def bytesize
  22. 576 @raw.to_s.bytesize
  23. end
  24. 9 def to_s
  25. 180 @raw.to_s
  26. end
  27. end
  28. 9 def encode(xml)
  29. 180 Encoder.new(xml)
  30. end
  31. 9 def decode(response)
  32. 27 content_type = response.content_type.mime_type
  33. 27 raise HTTPX::Error, "invalid form mime type (#{content_type})" unless MIME_TYPES.match?(content_type)
  34. 27 Nokogiri::XML.method(:parse)
  35. end
  36. end
  37. 9 class << self
  38. 9 def load_dependencies(*)
  39. 162 require "nokogiri"
  40. end
  41. end
  42. 9 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. 9 def xml
  46. 18 decode(Transcoder)
  47. end
  48. end
  49. 9 module RequestBodyClassMethods
  50. # ..., xml: Nokogiri::XML::Node #=> xml encoder
  51. 9 def initialize_body(params)
  52. 666 if (xml = params.delete(:xml))
  53. # @type var xml: Nokogiri::XML::Node | String
  54. 160 return Transcoder.encode(xml)
  55. end
  56. 486 super
  57. end
  58. end
  59. end
  60. 9 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. 30 module HTTPX
  3. 30 module ResponsePatternMatchExtensions
  4. 30 def deconstruct
  5. 46 [@status, @headers, @body]
  6. end
  7. 30 def deconstruct_keys(_keys)
  8. 80 { status: @status, headers: @headers, body: @body }
  9. end
  10. end
  11. 30 module ErrorResponsePatternMatchExtensions
  12. 30 def deconstruct
  13. 12 [@error]
  14. end
  15. 30 def deconstruct_keys(_keys)
  16. 40 { error: @error }
  17. end
  18. end
  19. 30 module HeadersPatternMatchExtensions
  20. 30 def deconstruct
  21. 8 to_a
  22. end
  23. end
  24. 30 Headers.include HeadersPatternMatchExtensions
  25. 30 Response.include ResponsePatternMatchExtensions
  26. 30 ErrorResponse.include ErrorResponsePatternMatchExtensions
  27. end

lib/httpx/pool.rb

100.0% lines covered

109 relevant lines. 109 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "httpx/selector"
  3. 30 require "httpx/connection"
  4. 30 require "httpx/connection/http2"
  5. 30 require "httpx/connection/http1"
  6. 30 require "httpx/resolver"
  7. 30 module HTTPX
  8. 30 class Pool
  9. 30 using URIExtensions
  10. 30 POOL_TIMEOUT = 5
  11. # Sets up the connection pool with the given +options+, which can be the following:
  12. #
  13. # :max_connections:: the maximum number of connections held in the pool.
  14. # :max_connections_per_origin :: the maximum number of connections held in the pool pointing to a given origin.
  15. # :pool_timeout :: the number of seconds to wait for a connection to a given origin (before raising HTTPX::PoolTimeoutError)
  16. #
  17. 30 def initialize(options)
  18. 14026 @max_connections = options.fetch(:max_connections, Float::INFINITY)
  19. 14026 @max_connections_per_origin = options.fetch(:max_connections_per_origin, Float::INFINITY)
  20. 14026 @pool_timeout = options.fetch(:pool_timeout, POOL_TIMEOUT)
  21. 21704 @resolvers = Hash.new { |hs, resolver_type| hs[resolver_type] = [] }
  22. 14026 @resolver_mtx = Thread::Mutex.new
  23. 14026 @connections = []
  24. 14026 @connection_mtx = Thread::Mutex.new
  25. 14026 @connections_counter = 0
  26. 14026 @max_connections_cond = ConditionVariable.new
  27. 14026 @origin_counters = Hash.new(0)
  28. 21004 @origin_conds = Hash.new { |hs, orig| hs[orig] = ConditionVariable.new }
  29. end
  30. # connections returned by this function are not expected to return to the connection pool.
  31. 30 def pop_connection
  32. 14567 @connection_mtx.synchronize do
  33. 14567 drop_connection
  34. end
  35. end
  36. # opens a connection to the IP reachable through +uri+.
  37. # Many hostnames are reachable through the same IP, so we try to
  38. # maximize pipelining by opening as few connections as possible.
  39. #
  40. 30 def checkout_connection(uri, options)
  41. 9994 return checkout_new_connection(uri, options) if options.io
  42. 9919 @connection_mtx.synchronize do
  43. 9919 acquire_connection(uri, options) || begin
  44. 9044 if @connections_counter == @max_connections
  45. # this takes precedence over per-origin
  46. 18 expires_at = Utils.now + @pool_timeout
  47. 18 loop do
  48. 19 @max_connections_cond.wait(@connection_mtx, @pool_timeout)
  49. 19 if (conn = acquire_connection(uri, options))
  50. 6 return conn
  51. end
  52. # if one can afford to create a new connection, do it
  53. 13 break unless @connections_counter == @max_connections
  54. # if no matching usable connection was found, the pool will make room and drop a closed connection.
  55. 15 if (conn = @connections.find { |c| c.state == :closed })
  56. 2 drop_connection(conn)
  57. 2 break
  58. end
  59. # happens when a condition was signalled, but another thread snatched the available connection before
  60. # context was passed back here.
  61. 10 next if Utils.now < expires_at
  62. 9 raise PoolTimeoutError.new(@pool_timeout,
  63. 1 "Timed out after #{@pool_timeout} seconds while waiting for a connection")
  64. end
  65. end
  66. 9029 if @origin_counters[uri.origin] == @max_connections_per_origin
  67. 18 expires_at = Utils.now + @pool_timeout
  68. 18 loop do
  69. 18 @origin_conds[uri.origin].wait(@connection_mtx, @pool_timeout)
  70. 18 if (conn = acquire_connection(uri, options))
  71. 9 return conn
  72. end
  73. # happens when a condition was signalled, but another thread snatched the available connection before
  74. # context was passed back here.
  75. 9 next if Utils.now < expires_at
  76. 9 raise(PoolTimeoutError.new(@pool_timeout,
  77. 1 "Timed out after #{@pool_timeout} seconds while waiting for a connection to #{uri.origin}"))
  78. end
  79. end
  80. 8154 @connections_counter += 1
  81. 9011 @origin_counters[uri.origin] += 1
  82. 9011 checkout_new_connection(uri, options)
  83. end
  84. end
  85. end
  86. 30 def checkin_connection(connection)
  87. 10171 return if connection.options.io
  88. 10096 @connection_mtx.synchronize do
  89. 10096 if connection.coalesced? || connection.state == :idle
  90. # when connections coalesce
  91. 57 drop_connection(connection)
  92. 57 return
  93. end
  94. 10039 @connections << connection
  95. 10039 @max_connections_cond.signal
  96. 10039 @origin_conds[connection.origin.to_s].signal
  97. # Observed situations where a session handling multiple requests in a loop
  98. # across multiple threads checks the same connection in and out, while another
  99. # thread which is waiting on the same connection never gets the chance to pick
  100. # it up, because ruby's thread scheduler never switched on to it in the process.
  101. 10039 Thread.pass
  102. end
  103. end
  104. 30 def checkout_mergeable_connection(connection)
  105. 8976 return if connection.options.io
  106. 8976 @connection_mtx.synchronize do
  107. 8976 idx = @connections.find_index do |ch|
  108. 338 ch != connection && ch.mergeable?(connection)
  109. end
  110. 8976 @connections.delete_at(idx) if idx
  111. end
  112. end
  113. 30 def reset_resolvers
  114. 17596 @resolver_mtx.synchronize { @resolvers.clear }
  115. end
  116. 30 def checkout_resolver(options)
  117. 8770 resolver_type = options.resolver_class
  118. 8770 @resolver_mtx.synchronize do
  119. 8770 resolvers = @resolvers[resolver_type]
  120. 8770 idx = resolvers.find_index do |res|
  121. 36 res.options == options
  122. end
  123. 8770 resolvers.delete_at(idx) if idx
  124. end || checkout_new_resolver(resolver_type, options)
  125. end
  126. 30 def checkin_resolver(resolver)
  127. 610 resolver_class = resolver.class
  128. 610 resolver = resolver.multi
  129. # a multi requires all sub-resolvers being closed in order to be
  130. # correctly checked back in.
  131. 610 return unless resolver.closed?
  132. 589 @resolver_mtx.synchronize do
  133. 589 resolvers = @resolvers[resolver_class]
  134. 589 resolvers << resolver unless resolvers.include?(resolver)
  135. end
  136. end
  137. skipped # :nocov:
  138. skipped def inspect
  139. skipped "#<#{self.class}:#{object_id} " \
  140. skipped "@max_connections=#{@max_connections} " \
  141. skipped "@max_connections_per_origin=#{@max_connections_per_origin} " \
  142. skipped "@pool_timeout=#{@pool_timeout} " \
  143. skipped "@connections=#{@connections.size}>"
  144. skipped end
  145. skipped # :nocov:
  146. 30 private
  147. 30 def acquire_connection(uri, options)
  148. 9956 idx = @connections.find_index do |connection|
  149. 1196 connection.match?(uri, options)
  150. end
  151. 9956 return unless idx
  152. 890 @connections.delete_at(idx)
  153. end
  154. 30 def checkout_new_connection(uri, options)
  155. 9095 connection = options.connection_class.new(uri, options)
  156. 9163 connection.log(level: 2) { "created connection##{connection.object_id} in pool##{object_id}" }
  157. 9077 connection
  158. end
  159. 30 def checkout_new_resolver(resolver_type, options)
  160. 8739 resolver = if resolver_type.multi?
  161. 8561 Resolver::Multi.new(resolver_type, options)
  162. else
  163. 178 resolver_type.new(options)
  164. end
  165. 8825 resolver.log(level: 2) { "created resolver##{resolver.object_id} in pool##{object_id}" }
  166. 8739 resolver
  167. end
  168. # drops and returns the +connection+ from the connection pool; if +connection+ is <tt>nil</tt> (default),
  169. # the first available connection from the pool will be dropped.
  170. 30 def drop_connection(connection = nil)
  171. 14626 if connection
  172. 59 @connections.delete(connection)
  173. else
  174. 14567 connection = @connections.shift
  175. 14567 return unless connection
  176. end
  177. 5269 @connections_counter -= 1
  178. 5828 @origin_conds.delete(connection.origin) if (@origin_counters[connection.origin.to_s] -= 1).zero?
  179. 5828 connection
  180. end
  181. end
  182. 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. 30 module HTTPX
  3. 30 module Punycode
  4. 30 module_function
  5. begin
  6. 30 require "idnx"
  7. 29 def encode_hostname(hostname)
  8. 36 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

138 relevant lines. 138 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "delegate"
  3. 30 require "forwardable"
  4. 30 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. 30 class Request
  8. 30 extend Forwardable
  9. 30 include Loggable
  10. 30 include Callbacks
  11. 30 using URIExtensions
  12. 30 ALLOWED_URI_SCHEMES = %w[https http].freeze
  13. # the upcased string HTTP verb for this request.
  14. 30 attr_reader :verb
  15. # the absolute URI object for this request.
  16. 30 attr_reader :uri
  17. # an HTTPX::Headers object containing the request HTTP headers.
  18. 30 attr_reader :headers
  19. # an HTTPX::Request::Body object containing the request body payload (or +nil+, whenn there is none).
  20. 30 attr_reader :body
  21. # a symbol describing which frame is currently being flushed.
  22. 30 attr_reader :state
  23. # an HTTPX::Options object containing request options.
  24. 30 attr_reader :options
  25. # the corresponding HTTPX::Response object, when there is one.
  26. 30 attr_reader :response
  27. # Exception raised during enumerable body writes.
  28. 30 attr_reader :drain_error
  29. # The IP address from the peer server.
  30. 30 attr_accessor :peer_address
  31. 30 attr_writer :persistent
  32. 30 attr_reader :active_timeouts
  33. # will be +true+ when request body has been completely flushed.
  34. 30 def_delegator :@body, :empty?
  35. # closes the body
  36. 30 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. 30 def initialize(verb, uri, options, params = EMPTY_HASH)
  52. 12405 @verb = verb.to_s.upcase
  53. 12405 @uri = Utils.to_uri(uri)
  54. 12404 @headers = options.headers.dup
  55. 12404 merge_headers(params.delete(:headers)) if params.key?(:headers)
  56. 12404 @query_params = params.delete(:params) if params.key?(:params)
  57. 12404 @body = options.request_body_class.new(@headers, options, **params)
  58. 12386 @options = @body.options
  59. 12386 if @uri.relative? || @uri.host.nil?
  60. 676 origin = @options.origin
  61. 676 raise(Error, "invalid URI: #{@uri}") unless origin
  62. 648 base_path = @options.base_path
  63. 648 @uri = origin.merge("#{base_path}#{@uri}")
  64. end
  65. 12358 raise UnsupportedSchemeError, "#{@uri}: #{@uri.scheme}: unsupported URI scheme" unless ALLOWED_URI_SCHEMES.include?(@uri.scheme)
  66. 12344 @state = :idle
  67. 12344 @response = @peer_address = @informational_status = nil
  68. 12344 @ping = false
  69. 12344 @persistent = @options.persistent
  70. 12344 @active_timeouts = []
  71. end
  72. # dupped initialization
  73. 30 def initialize_dup(orig)
  74. 1022 super
  75. 1022 @uri = orig.instance_variable_get(:@uri).dup
  76. 1022 @headers = orig.instance_variable_get(:@headers).dup
  77. 1022 @body = orig.instance_variable_get(:@body).dup
  78. end
  79. 30 def complete!(response = @response)
  80. 9870 emit(:complete, response)
  81. end
  82. # whether request has been buffered with a ping
  83. 30 def ping?
  84. 677 @ping
  85. end
  86. # marks the request as having been buffered with a ping
  87. 30 def ping!
  88. 54 @ping = true
  89. end
  90. # the read timeout defined for this request.
  91. 30 def read_timeout
  92. 20919 @options.timeout[:read_timeout]
  93. end
  94. # the write timeout defined for this request.
  95. 30 def write_timeout
  96. 20919 @options.timeout[:write_timeout]
  97. end
  98. # the request timeout defined for this request.
  99. 30 def request_timeout
  100. 20600 @options.timeout[:request_timeout]
  101. end
  102. 30 def persistent?
  103. 5836 @persistent
  104. end
  105. # if the request contains trailer headers
  106. 30 def trailers?
  107. 3632 defined?(@trailers)
  108. end
  109. # returns an instance of HTTPX::Headers containing the trailer headers
  110. 30 def trailers
  111. 99 @trailers ||= @options.headers_class.new
  112. end
  113. # returns +:r+ or +:w+, depending on whether the request is waiting for a response or flushing.
  114. 30 def interests
  115. 50023 return :r if @state == :done || @state == :expect
  116. 5824 :w
  117. end
  118. 30 def can_buffer?
  119. 32037 @state != :done
  120. end
  121. # merges +h+ into the instance of HTTPX::Headers of the request.
  122. 30 def merge_headers(h)
  123. 1379 @headers = @headers.merge(h)
  124. 1379 return unless @headers.key?("range")
  125. 18 @headers.delete("accept-encoding")
  126. end
  127. # the URI scheme of the request +uri+.
  128. 30 def scheme
  129. 4516 @uri.scheme
  130. end
  131. # sets the +response+ on this request.
  132. 30 def response=(response)
  133. 11542 return unless response
  134. 10477 case response
  135. when Response
  136. 10123 if response.status < 200
  137. # deal with informational responses
  138. 164 if response.status == 100 && @headers.key?("expect")
  139. 137 @informational_status = response.status
  140. 137 return
  141. end
  142. # 103 Early Hints advertises resources in document to browsers.
  143. # not very relevant for an HTTP client, discard.
  144. 27 return if response.status >= 103
  145. end
  146. when ErrorResponse
  147. 1419 response.error.connection = nil if response.error.respond_to?(:connection=)
  148. end
  149. 11405 @response = response
  150. 11405 emit(:response_started, response)
  151. end
  152. # returnns the URI path of the request +uri+.
  153. 30 def path
  154. 11076 path = uri.path.dup
  155. 11076 path = +"" if path.nil?
  156. 11076 path << "/" if path.empty?
  157. 11076 path << "?#{query}" unless query.empty?
  158. 11076 path
  159. end
  160. # returs the URI authority of the request.
  161. #
  162. # session.build_request("GET", "https://google.com/query").authority #=> "google.com"
  163. # session.build_request("GET", "http://internal:3182/a").authority #=> "internal:3182"
  164. 30 def authority
  165. 10622 @uri.authority
  166. end
  167. # returs the URI origin of the request.
  168. #
  169. # session.build_request("GET", "https://google.com/query").authority #=> "https://google.com"
  170. # session.build_request("GET", "http://internal:3182/a").authority #=> "http://internal:3182"
  171. 30 def origin
  172. 4882 @uri.origin
  173. end
  174. # returs the URI query string of the request (when available).
  175. #
  176. # session.build_request("GET", "https://search.com").query #=> ""
  177. # session.build_request("GET", "https://search.com?q=a").query #=> "q=a"
  178. # session.build_request("GET", "https://search.com", params: { q: "a"}).query #=> "q=a"
  179. # session.build_request("GET", "https://search.com?q=a", params: { foo: "bar"}).query #=> "q=a&foo&bar"
  180. 30 def query
  181. 12259 return @query if defined?(@query)
  182. 10148 query = []
  183. 10148 if (q = @query_params) && !q.empty?
  184. 190 query << Transcoder::Form.encode(q)
  185. end
  186. 10148 query << @uri.query if @uri.query
  187. 10148 @query = query.join("&")
  188. end
  189. # consumes and returns the next available chunk of request body that can be sent
  190. 30 def drain_body
  191. 11136 return nil if @body.nil?
  192. 11136 @drainer ||= @body.each
  193. 11136 chunk = @drainer.next.dup
  194. 7298 emit(:body_chunk, chunk)
  195. 7298 chunk
  196. rescue StopIteration
  197. 3810 nil
  198. rescue StandardError => e
  199. 28 @drain_error = e
  200. 28 nil
  201. end
  202. skipped # :nocov:
  203. skipped def inspect
  204. skipped "#<#{self.class}:#{object_id} " \
  205. skipped "#{@verb} " \
  206. skipped "#{uri} " \
  207. skipped "@headers=#{@headers} " \
  208. skipped "@body=#{@body}>"
  209. skipped end
  210. skipped # :nocov:
  211. # moves on to the +nextstate+ of the request state machine (when all preconditions are met)
  212. 30 def transition(nextstate)
  213. 45815 case nextstate
  214. when :idle
  215. 1007 @body.rewind
  216. 1007 @ping = false
  217. 1007 @response = nil
  218. 1007 @drainer = nil
  219. 1007 @active_timeouts.clear
  220. when :headers
  221. 13666 return unless @state == :idle
  222. when :body
  223. 13837 return unless @state == :headers ||
  224. @state == :expect
  225. 11155 if @headers.key?("expect")
  226. 522 if @informational_status && @informational_status == 100
  227. # check for 100 Continue response, and deallocate the var
  228. # if @informational_status == 100
  229. # @response = nil
  230. # end
  231. else
  232. 394 return if @state == :expect # do not re-set it
  233. 146 nextstate = :expect
  234. end
  235. end
  236. when :trailers
  237. 10923 return unless @state == :body
  238. when :done
  239. 10932 return if @state == :expect
  240. end
  241. 44050 log(level: 3) { "#{@state}] -> #{nextstate}" }
  242. 43794 @state = nextstate
  243. 43794 emit(@state, self)
  244. 20394 nil
  245. end
  246. # whether the request supports the 100-continue handshake and already processed the 100 response.
  247. 30 def expects?
  248. 9779 @headers["expect"] == "100-continue" && @informational_status == 100 && !@response
  249. end
  250. 30 def set_timeout_callback(event, &callback)
  251. 105083 clb = once(event, &callback)
  252. # reset timeout callbacks when requests get rerouted to a different connection
  253. 105083 once(:idle) do
  254. 4929 callbacks(event).delete(clb)
  255. end
  256. end
  257. end
  258. end
  259. 30 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. 30 module HTTPX
  3. # Implementation of the HTTP Request body as a delegator which iterates (responds to +each+) payload chunks.
  4. 30 class Request::Body < SimpleDelegator
  5. 30 class << self
  6. 30 def new(_, options, body: nil, **params)
  7. 12413 if body.is_a?(self)
  8. # request derives its options from body
  9. 18 body.options = options.merge(params)
  10. 16 return body
  11. end
  12. 12395 super
  13. end
  14. end
  15. 30 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. 30 def initialize(h, options, **params)
  25. 12395 @headers = h
  26. 12395 @body = self.class.initialize_body(params)
  27. 12395 @options = options.merge(params)
  28. 12395 if @body
  29. 3828 if @options.compress_request_body && @headers.key?("content-encoding")
  30. 109 @headers.get("content-encoding").each do |encoding|
  31. 109 @body = self.class.initialize_deflater_body(@body, encoding)
  32. end
  33. end
  34. 3828 @headers["content-type"] ||= @body.content_type
  35. 3828 @headers["content-length"] = @body.bytesize unless unbounded_body?
  36. end
  37. 12386 super(@body)
  38. end
  39. # consumes and yields the request payload in chunks.
  40. 30 def each(&block)
  41. 7951 return enum_for(__method__) unless block
  42. 3980 return if @body.nil?
  43. 3899 body = stream(@body)
  44. 3899 if body.respond_to?(:read)
  45. 6539 while (chunk = body.read(16_384))
  46. 4005 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. 2257 elsif body.respond_to?(:each)
  51. 730 body.each(&block)
  52. else
  53. 1528 block[body.to_s]
  54. end
  55. end
  56. 30 def close
  57. 531 @body.close if @body.respond_to?(:close)
  58. end
  59. # if the +@body+ is rewindable, it rewinnds it.
  60. 30 def rewind
  61. 1079 return if empty?
  62. 187 @body.rewind if @body.respond_to?(:rewind)
  63. end
  64. # return +true+ if the +body+ has been fully drained (or does nnot exist).
  65. 30 def empty?
  66. 23544 return true if @body.nil?
  67. 10172 return false if chunked?
  68. 10064 @body.bytesize.zero?
  69. end
  70. # returns the +@body+ payload size in bytes.
  71. 30 def bytesize
  72. 4163 return 0 if @body.nil?
  73. 144 @body.bytesize
  74. end
  75. # sets the body to yield using chunked trannsfer encoding format.
  76. 30 def stream(body)
  77. 3899 return body unless chunked?
  78. 108 Transcoder::Chunker.encode(body.enum_for(:each))
  79. end
  80. # returns whether the body yields infinitely.
  81. 30 def unbounded_body?
  82. 4437 return @unbounded_body if defined?(@unbounded_body)
  83. 3909 @unbounded_body = !@body.nil? && (chunked? || @body.bytesize == Float::INFINITY)
  84. end
  85. # returns whether the chunked transfer encoding header is set.
  86. 30 def chunked?
  87. 23965 @headers["transfer-encoding"] == "chunked"
  88. end
  89. # sets the chunked transfer encoding header.
  90. 30 def chunk!
  91. 36 @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. 30 class << self
  100. 30 def initialize_body(params)
  101. 12215 if (body = params.delete(:body))
  102. # @type var body: bodyIO
  103. 1742 Transcoder::Body.encode(body)
  104. 10473 elsif (form = params.delete(:form))
  105. 1804 if Transcoder::Multipart.multipart?(form)
  106. # @type var form: Transcoder::Multipart::multipart_input
  107. 1142 Transcoder::Multipart.encode(form)
  108. else
  109. # @type var form: Transcoder::urlencoded_input
  110. 662 Transcoder::Form.encode(form)
  111. end
  112. 8669 elsif (json = params.delete(:json))
  113. # @type var body: _ToJson
  114. 102 Transcoder::JSON.encode(json)
  115. end
  116. end
  117. # returns the +body+ wrapped with the correct deflater accordinng to the given +encodisng+.
  118. 30 def initialize_deflater_body(body, encoding)
  119. 100 case encoding
  120. when "gzip"
  121. 55 Transcoder::GZIP.encode(body)
  122. when "deflate"
  123. 27 Transcoder::Deflate.encode(body)
  124. when "identity"
  125. 18 body
  126. else
  127. 9 body
  128. end
  129. end
  130. end
  131. end
  132. end

lib/httpx/resolver.rb

93.22% lines covered

59 relevant lines. 55 lines covered and 4 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "socket"
  3. 30 require "resolv"
  4. 30 module HTTPX
  5. 30 module Resolver
  6. 30 extend self
  7. 30 RESOLVE_TIMEOUT = [2, 3].freeze
  8. 30 require "httpx/resolver/entry"
  9. 30 require "httpx/resolver/cache"
  10. 30 require "httpx/resolver/resolver"
  11. 30 require "httpx/resolver/system"
  12. 30 require "httpx/resolver/native"
  13. 30 require "httpx/resolver/https"
  14. 30 require "httpx/resolver/multi"
  15. 30 @identifier_mutex = Thread::Mutex.new
  16. 30 @identifier = 1
  17. 30 def supported_ip_families
  18. 9077 if Utils.in_ractor?
  19. Ractor.store_if_absent(:httpx_supported_ip_families) { find_supported_ip_families }
  20. else
  21. 9077 @supported_ip_families ||= find_supported_ip_families
  22. end
  23. end
  24. 30 def generate_id
  25. 1067 if Utils.in_ractor?
  26. identifier = Ractor.store_if_absent(:httpx_resolver_identifier) { -1 }
  27. Ractor.current[:httpx_resolver_identifier] = (identifier + 1) & 0xFFFF
  28. else
  29. 2134 id_synchronize { @identifier = (@identifier + 1) & 0xFFFF }
  30. end
  31. end
  32. 30 def encode_dns_query(hostname, type: Resolv::DNS::Resource::IN::A, message_id: generate_id)
  33. 1014 Resolv::DNS::Message.new(message_id).tap do |query|
  34. 1067 query.rd = 1
  35. 1067 query.add_question(hostname, type)
  36. 105 end.encode
  37. end
  38. 30 def decode_dns_answer(payload)
  39. 52 begin
  40. 821 message = Resolv::DNS::Message.decode(payload)
  41. rescue Resolv::DNS::DecodeError => e
  42. 9 return :decode_error, e
  43. end
  44. # no domain was found
  45. 812 return :no_domain_found if message.rcode == Resolv::DNS::RCode::NXDomain
  46. 368 return :message_truncated if message.tc == 1
  47. 354 if message.rcode != Resolv::DNS::RCode::NoError
  48. 14 case message.rcode
  49. when Resolv::DNS::RCode::ServFail
  50. 7 return :retriable_error, message.rcode
  51. else
  52. 7 return :dns_error, message.rcode
  53. end
  54. end
  55. 340 addresses = []
  56. 340 now = Utils.now
  57. 340 message.each_answer do |question, _, value|
  58. 1233 case value
  59. when Resolv::DNS::Resource::IN::CNAME
  60. 28 addresses << {
  61. "name" => question.to_s,
  62. 28 "TTL" => (now + value.ttl),
  63. "alias" => value.name.to_s,
  64. }
  65. when Resolv::DNS::Resource::IN::A,
  66. Resolv::DNS::Resource::IN::AAAA
  67. 1229 addresses << {
  68. "name" => question.to_s,
  69. 1229 "TTL" => (now + value.ttl),
  70. "data" => value.address.to_s,
  71. }
  72. end
  73. end
  74. 340 [:ok, addresses]
  75. end
  76. 30 private
  77. 30 def id_synchronize(&block)
  78. 1067 @identifier_mutex.synchronize(&block)
  79. end
  80. 30 def find_supported_ip_families
  81. 32 list = Socket.ip_address_list
  82. 3 begin
  83. 129 if list.any? { |a| a.ipv6? && !a.ipv6_loopback? && !a.ipv6_linklocal? }
  84. 1 [Socket::AF_INET6, Socket::AF_INET]
  85. else
  86. 31 [Socket::AF_INET]
  87. end
  88. rescue NotImplementedError
  89. [Socket::AF_INET]
  90. 11 end.freeze
  91. end
  92. end
  93. end

lib/httpx/resolver/cache.rb

100.0% lines covered

4 relevant lines. 4 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "httpx/resolver/cache/base"
  3. 30 require "httpx/resolver/cache/memory"
  4. 30 module HTTPX::Resolver
  5. # The internal resolvers cache adapters are defined under this namespace.
  6. #
  7. # Adapters must comply with the Resolver Cache Adapter API and implement the following methods:
  8. #
  9. # * #resolve: (String hostname) -> Array[HTTPX::Entry]? => resolves hostname to a list of cached IPs (if found in cache or system)
  10. # * #get: (String hostname) -> Array[HTTPX::Entry]? => resolves hostname to a list of cached IPs (if found in cache)
  11. # * #set: (String hostname, Integer ip_family, Array[dns_result]) -> void => stores the set of results in the cache indexes for
  12. # the hostname and the IP family
  13. # * #evict: (String hostname, _ToS ip) -> void => evicts the ip for the hostname from the cache (usually done when no longer reachable)
  14. 30 module Cache
  15. end
  16. end

lib/httpx/resolver/cache/base.rb

98.41% lines covered

63 relevant lines. 62 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "resolv"
  3. 30 module HTTPX
  4. 30 module Resolver::Cache
  5. # Base class of the Resolver Cache adapter implementations.
  6. #
  7. # While resolver caches are not required to inherit from this class, it nevertheless provides
  8. # common useful functions for desired functionality, such as singleton object ractor-safe access,
  9. # or a default #resolve implementation which deals with IPs and the system hosts file.
  10. #
  11. 30 class Base
  12. 30 MAX_CACHE_SIZE = 512
  13. 30 CACHE_MUTEX = Thread::Mutex.new
  14. 30 HOSTS = Resolv::Hosts.new
  15. 30 @cache = nil
  16. 30 class << self
  17. 30 attr_reader :hosts_resolver
  18. # returns the singleton instance to be used within the current ractor.
  19. 30 def cache(label)
  20. 14868 return Ractor.store_if_absent(:"httpx_resolver_cache_#{label}") { new } if Utils.in_ractor?
  21. 14868 @cache ||= CACHE_MUTEX.synchronize do
  22. 25 @cache || new
  23. end
  24. end
  25. end
  26. # resolves +hostname+ into an instance of HTTPX::Resolver::Entry if +hostname+ is an IP,
  27. # or can be found in the cache, or can be found in the system hosts file.
  28. 30 def resolve(hostname)
  29. 8407 ip_resolve(hostname) || get(hostname) || hosts_resolve(hostname)
  30. end
  31. 30 private
  32. # tries to convert +hostname+ into an IPAddr, returns <tt>nil</tt> otherwise.
  33. 30 def ip_resolve(hostname)
  34. 8407 [Resolver::Entry.new(hostname)]
  35. rescue ArgumentError
  36. end
  37. # matches +hostname+ to entries in the hosts file, returns <tt>nil</nil> if none is
  38. # found, or there is no hosts file.
  39. 30 def hosts_resolve(hostname)
  40. 737 ips = if Utils.in_ractor?
  41. Ractor.store_if_absent(:httpx_hosts_resolver) { Resolv::Hosts.new }
  42. else
  43. 737 HOSTS
  44. end.getaddresses(hostname)
  45. 737 return if ips.empty?
  46. 1014 ips.map { |ip| Resolver::Entry.new(ip) }
  47. rescue IOError
  48. end
  49. # not to be used directly!
  50. 30 def _get(hostname, lookups, hostnames, ttl)
  51. 7691 return unless lookups.key?(hostname)
  52. 6947 entries = lookups[hostname]
  53. 6947 return unless entries
  54. 6947 entries.delete_if do |address|
  55. 18176 address["TTL"] < ttl
  56. end
  57. 6947 if entries.empty?
  58. 20 lookups.delete(hostname)
  59. 20 hostnames.delete(hostname)
  60. end
  61. 6947 ips = entries.flat_map do |address|
  62. 18156 if (als = address["alias"])
  63. 9 _get(als, lookups, hostnames, ttl)
  64. else
  65. 18147 Resolver::Entry.new(address["data"], address["TTL"])
  66. end
  67. end.compact
  68. 6947 ips unless ips.empty?
  69. end
  70. 30 def _set(hostname, family, entries, lookups, hostnames)
  71. # lru cleanup
  72. 6736 while lookups.size >= MAX_CACHE_SIZE
  73. 1692 hs = hostnames.shift
  74. 1692 lookups.delete(hs)
  75. end
  76. 6548 hostnames << hostname
  77. 6548 lookups[hostname] ||= [] # when there's no default proc
  78. 5824 case family
  79. when Socket::AF_INET6
  80. 50 lookups[hostname].concat(entries)
  81. when Socket::AF_INET
  82. 6498 lookups[hostname].unshift(*entries)
  83. end
  84. 6548 entries.each do |entry|
  85. 6625 name = entry["name"]
  86. 6625 next unless name != hostname
  87. 221 lookups[name] ||= []
  88. 202 case family
  89. when Socket::AF_INET6
  90. 20 lookups[name] << entry
  91. when Socket::AF_INET
  92. 201 lookups[name].unshift(entry)
  93. end
  94. end
  95. end
  96. 30 def _evict(hostname, ip, lookups, hostnames)
  97. 31 return unless lookups.key?(hostname)
  98. 24 entries = lookups[hostname]
  99. 24 return unless entries
  100. 135 entries.delete_if { |entry| entry["data"] == ip }
  101. 24 return unless entries.empty?
  102. 9 lookups.delete(hostname)
  103. 9 hostnames.delete(hostname)
  104. end
  105. end
  106. end
  107. end

lib/httpx/resolver/cache/memory.rb

100.0% lines covered

22 relevant lines. 22 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 module HTTPX
  3. 30 module Resolver::Cache
  4. # Implementation of a thread-safe in-memory LRU resolver cache.
  5. 30 class Memory < Base
  6. 30 def initialize
  7. 44 super
  8. 44 @hostnames = []
  9. 5971 @lookups = Hash.new { |h, k| h[k] = [] }
  10. 44 @lookup_mutex = Thread::Mutex.new
  11. end
  12. 30 def get(hostname)
  13. 7682 now = Utils.now
  14. 7682 synchronize do |lookups, hostnames|
  15. 7682 _get(hostname, lookups, hostnames, now)
  16. end
  17. end
  18. 30 def set(hostname, family, entries)
  19. 6548 synchronize do |lookups, hostnames|
  20. 6548 _set(hostname, family, entries, lookups, hostnames)
  21. end
  22. end
  23. 30 def evict(hostname, ip)
  24. 31 ip = ip.to_s
  25. 31 synchronize do |lookups, hostnames|
  26. 31 _evict(hostname, ip, lookups, hostnames)
  27. end
  28. end
  29. 30 private
  30. 30 def synchronize
  31. 28522 @lookup_mutex.synchronize { yield(@lookups, @hostnames) }
  32. end
  33. end
  34. end
  35. 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. 30 require "ipaddr"
  3. 30 module HTTPX
  4. 30 module Resolver
  5. 30 class Entry < SimpleDelegator
  6. 30 attr_reader :address
  7. 30 def self.convert(address)
  8. 56 new(address, rescue_on_convert: true)
  9. end
  10. 30 def initialize(address, expires_in = Float::INFINITY, rescue_on_convert: false)
  11. 28845 @expires_in = expires_in
  12. 28845 @address = address.is_a?(IPAddr) ? address : IPAddr.new(address.to_s)
  13. 21238 super(@address)
  14. rescue IPAddr::InvalidAddressError
  15. 7607 raise unless rescue_on_convert
  16. 24 @address = address.to_s
  17. 24 super(@address)
  18. end
  19. 30 def expired?
  20. 2391 @expires_in < Utils.now
  21. end
  22. end
  23. end
  24. end

lib/httpx/resolver/https.rb

84.49% lines covered

187 relevant lines. 158 lines covered and 29 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "resolv"
  3. 30 require "uri"
  4. 30 require "forwardable"
  5. 30 require "httpx/base64"
  6. 30 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. 30 class Resolver::HTTPS < Resolver::Resolver
  12. 30 extend Forwardable
  13. 30 using URIExtensions
  14. 30 module DNSExtensions
  15. 30 refine Resolv::DNS do
  16. 30 def generate_candidates(name)
  17. 133 @config.generate_candidates(name)
  18. end
  19. end
  20. end
  21. 30 using DNSExtensions
  22. 30 NAMESERVER = "https://1.1.1.1/dns-query"
  23. 2 DEFAULTS = {
  24. 28 uri: NAMESERVER,
  25. use_get: false,
  26. }.freeze
  27. 30 def_delegators :@resolver_connection, :connecting?, :to_io, :call, :close,
  28. :closed?, :deactivate, :terminate, :inflight?, :handle_socket_timeout
  29. 30 def initialize(_, options)
  30. 149 super
  31. 149 @resolver_options = DEFAULTS.merge(@options.resolver_options)
  32. 149 @queries = {}
  33. 149 @requests = {}
  34. 149 @_timeouts = Array(@resolver_options[:timeouts])
  35. 296 @timeouts = Hash.new { |timeouts, host| timeouts[host] = @_timeouts.dup }
  36. 149 @uri = URI(@resolver_options[:uri])
  37. 149 @name = @uri_addresses = nil
  38. 149 @resolver = Resolv::DNS.new
  39. 149 @resolver.timeouts = @_timeouts.empty? ? Resolver::RESOLVE_TIMEOUT : @_timeouts
  40. 149 @resolver.lazy_initialize
  41. end
  42. 30 def state
  43. 28 @resolver_connection ? @resolver_connection.state : :idle
  44. end
  45. 30 def <<(connection)
  46. 140 return if @uri.origin == connection.peer.to_s
  47. 140 @uri_addresses ||= @options.resolver_cache.resolve(@uri.host) || @resolver.getaddresses(@uri.host)
  48. 140 if @uri_addresses.empty?
  49. 7 ex = ResolveError.new("Can't resolve DNS server #{@uri.host}")
  50. 7 ex.set_backtrace(caller)
  51. 7 connection.force_close
  52. 7 throw(:resolve_error, ex)
  53. end
  54. 133 resolve(connection)
  55. end
  56. 30 def resolver_connection
  57. # TODO: leaks connection object into the pool
  58. 154 @resolver_connection ||=
  59. @current_session.find_connection(
  60. @uri,
  61. @current_selector,
  62. @options.merge(resolver_class: :system, ssl: { alpn_protocols: %w[h2] })
  63. ).tap do |conn|
  64. 126 emit_addresses(conn, @family, @uri_addresses) unless conn.addresses
  65. 126 conn.on(:force_closed, &method(:force_close))
  66. end
  67. end
  68. 30 private
  69. 30 def resolve(connection = nil, hostname = nil)
  70. 161 @connections.shift until @connections.empty? || @connections.first.state != :closed
  71. 161 connection ||= @connections.first
  72. 161 return unless connection
  73. 161 hostname ||= @queries.key(connection)
  74. 161 if hostname.nil?
  75. 133 hostname = connection.peer.host
  76. log do
  77. "resolver #{FAMILY_TYPES[@record_type]}: resolve IDN #{connection.peer.non_ascii_hostname} as #{hostname}"
  78. 133 end if connection.peer.non_ascii_hostname
  79. 133 hostname = @resolver.generate_candidates(hostname).each do |name|
  80. 399 @queries[name.to_s] = connection
  81. end.first.to_s
  82. else
  83. 28 @queries[hostname] = connection
  84. end
  85. 161 @name = hostname
  86. 161 log { "resolver #{FAMILY_TYPES[@record_type]}: query for #{hostname}" }
  87. 161 send_request(hostname, connection)
  88. end
  89. 30 def send_request(hostname, connection)
  90. 161 request = build_request(hostname)
  91. 154 request.on(:response, &method(:on_response).curry(2)[request])
  92. 154 request.on(:promise, &method(:on_promise))
  93. 154 @requests[request] = hostname
  94. 154 resolver_connection.send(request)
  95. 154 @connections << connection
  96. rescue ResolveError, Resolv::DNS::EncodeError => e
  97. 7 reset_hostname(hostname)
  98. 7 throw(:resolve_error, e) if connection.pending.empty?
  99. emit_resolve_error(connection, connection.peer.host, e)
  100. close_or_resolve
  101. end
  102. 30 def on_response(request, response)
  103. 112 response.raise_for_status
  104. rescue StandardError => e
  105. 21 hostname = @requests.delete(request)
  106. 21 connection = reset_hostname(hostname)
  107. 21 emit_resolve_error(connection, connection.peer.host, e)
  108. 21 close_or_resolve
  109. else
  110. # @type var response: HTTPX::Response
  111. 91 if response.status.between?(300, 399) && response.headers.key?("location")
  112. hostname = @requests[request]
  113. connection = @queries[hostname]
  114. location_uri = URI(response.headers["location"])
  115. location_uri = response.uri.merge(location_uri) if location_uri.relative?
  116. # we assume that the DNS server URI changed permanently and move on
  117. @uri = location_uri
  118. send_request(hostname, connection)
  119. return
  120. end
  121. 91 parse(request, response)
  122. ensure
  123. 112 @requests.delete(request)
  124. end
  125. 30 def on_promise(_, stream)
  126. log(level: 2) { "#{stream.id}: refusing stream!" }
  127. stream.refuse
  128. end
  129. 30 def parse(request, response)
  130. 91 hostname = @name
  131. 91 @name = nil
  132. 91 code, result = decode_response_body(response)
  133. 91 case code
  134. when :ok
  135. 35 parse_addresses(result, request)
  136. when :no_domain_found
  137. # Indicates no such domain was found.
  138. 42 host = @requests.delete(request)
  139. 42 connection = reset_hostname(host, reset_candidates: false)
  140. 42 unless @queries.value?(connection)
  141. 14 emit_resolve_error(connection)
  142. 14 close_or_resolve
  143. 14 return
  144. end
  145. 28 resolve
  146. when :retriable_error
  147. timeouts = @timeouts[hostname]
  148. unless timeouts.empty?
  149. log { "resolver #{FAMILY_TYPES[@record_type]}: failed, but will retry..." }
  150. connection = @queries[hostname]
  151. resolve(connection, hostname)
  152. return
  153. end
  154. host = @requests.delete(request)
  155. connection = reset_hostname(host)
  156. emit_resolve_error(connection)
  157. close_or_resolve
  158. when :dns_error
  159. 7 host = @requests.delete(request)
  160. 7 connection = reset_hostname(host)
  161. 7 emit_resolve_error(connection)
  162. 7 close_or_resolve
  163. when :decode_error
  164. 7 host = @requests.delete(request)
  165. 7 connection = reset_hostname(host)
  166. 7 emit_resolve_error(connection, connection.peer.host, result)
  167. 7 close_or_resolve
  168. end
  169. end
  170. 30 def parse_addresses(answers, request)
  171. 35 if answers.empty?
  172. # no address found, eliminate candidates
  173. 7 host = @requests.delete(request)
  174. 7 connection = reset_hostname(host)
  175. 7 emit_resolve_error(connection)
  176. 7 close_or_resolve
  177. 7 return
  178. else
  179. 63 answers = answers.group_by { |answer| answer["name"] }
  180. 28 answers.each do |hostname, addresses|
  181. 35 addresses = addresses.flat_map do |address|
  182. 35 if address.key?("alias")
  183. 7 alias_address = answers[address["alias"]]
  184. 7 if alias_address.nil?
  185. reset_hostname(address["name"])
  186. if early_resolve(connection, hostname: address["alias"])
  187. @connections.delete(connection)
  188. else
  189. resolve(connection, address["alias"])
  190. return # rubocop:disable Lint/NonLocalExitFromIterator
  191. end
  192. else
  193. 7 alias_address
  194. end
  195. else
  196. 28 address
  197. end
  198. end.compact
  199. 35 next if addresses.empty?
  200. 35 hostname.delete_suffix!(".") if hostname.end_with?(".")
  201. 35 connection = reset_hostname(hostname, reset_candidates: false)
  202. 35 next unless connection # probably a retried query for which there's an answer
  203. 28 @connections.delete(connection)
  204. # eliminate other candidates
  205. 84 @queries.delete_if { |_, conn| connection == conn }
  206. 28 @options.resolver_cache.set(hostname, @family, addresses) if @resolver_options[:cache]
  207. 84 catch(:coalesced) { emit_addresses(connection, @family, addresses.map { |a| Resolver::Entry.new(a["data"], a["TTL"]) }) }
  208. end
  209. end
  210. 28 close_or_resolve(true)
  211. end
  212. 30 def build_request(hostname)
  213. 147 uri = @uri.dup
  214. 147 rklass = @options.request_class
  215. 147 payload = Resolver.encode_dns_query(hostname, type: @record_type)
  216. 147 timeouts = @timeouts[hostname]
  217. 147 request_timeout = timeouts.shift
  218. 147 options = @options.merge(timeout: { request_timeout: request_timeout })
  219. 147 if @resolver_options[:use_get]
  220. 7 params = URI.decode_www_form(uri.query.to_s)
  221. 7 params << ["type", FAMILY_TYPES[@record_type]]
  222. 7 params << ["dns", Base64.urlsafe_encode64(payload, padding: false)]
  223. 7 uri.query = URI.encode_www_form(params)
  224. 7 request = rklass.new("GET", uri, options)
  225. else
  226. 140 request = rklass.new("POST", uri, options, body: [payload])
  227. 140 request.headers["content-type"] = "application/dns-message"
  228. end
  229. 147 request.headers["accept"] = "application/dns-message"
  230. 147 request
  231. end
  232. 30 def decode_response_body(response)
  233. 77 case response.headers["content-type"]
  234. when "application/dns-udpwireformat",
  235. "application/dns-message"
  236. 77 Resolver.decode_dns_answer(response.to_s)
  237. else
  238. raise Error, "unsupported DNS mime-type (#{response.headers["content-type"]})"
  239. end
  240. end
  241. 30 def reset_hostname(hostname, reset_candidates: true)
  242. 126 @timeouts.delete(hostname)
  243. 126 connection = @queries.delete(hostname)
  244. 126 return connection unless connection && reset_candidates
  245. # eliminate other candidates
  246. 147 candidates = @queries.select { |_, conn| connection == conn }.keys
  247. 147 @queries.delete_if { |h, _| candidates.include?(h) }
  248. # reset timeouts
  249. 49 @timeouts.delete_if { |h, _| candidates.include?(h) }
  250. 49 connection
  251. end
  252. 30 def close_or_resolve(should_deactivate = false)
  253. # drop already closed connections
  254. 84 @connections.shift until @connections.empty? || @connections.first.state != :closed
  255. 84 if (@connections - @queries.values).empty?
  256. # the same resolver connection may be serving different https resolvers (AAAA and A).
  257. 84 return if inflight?
  258. 70 if should_deactivate
  259. 24 deactivate
  260. else
  261. 46 disconnect
  262. end
  263. else
  264. resolve
  265. end
  266. end
  267. end
  268. end

lib/httpx/resolver/multi.rb

100.0% lines covered

49 relevant lines. 49 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "forwardable"
  3. 30 require "resolv"
  4. 30 module HTTPX
  5. 30 class Resolver::Multi
  6. 30 attr_reader :resolvers, :options
  7. 30 def initialize(resolver_type, options)
  8. 8561 @current_selector = @current_session = nil
  9. 8561 @options = options
  10. 8561 @resolver_options = @options.resolver_options
  11. 8561 ip_families = options.ip_families || Resolver.supported_ip_families
  12. 8561 @resolvers = ip_families.map do |ip_family|
  13. 8628 resolver = resolver_type.new(ip_family, options)
  14. 8628 resolver.multi = self
  15. 8628 resolver
  16. end
  17. end
  18. 30 def state
  19. 86 @resolvers.map(&:state).uniq.join(",")
  20. end
  21. 30 def current_selector=(s)
  22. 8574 @current_selector = s
  23. 17217 @resolvers.each { |r| r.current_selector = s }
  24. end
  25. 30 def current_session=(s)
  26. 8574 @current_session = s
  27. 17217 @resolvers.each { |r| r.current_session = s }
  28. end
  29. 30 def log(*args, **kwargs, &blk)
  30. 34427 @resolvers.each { |r| r.log(*args, **kwargs, &blk) }
  31. end
  32. 30 def closed?
  33. 501 @resolvers.all?(&:closed?)
  34. end
  35. 30 def early_resolve(connection)
  36. 8581 hostname = connection.peer.host
  37. 8581 addresses = @resolver_options[:cache] && (connection.addresses || nolookup_resolve(hostname, connection.options))
  38. 8581 return false unless addresses
  39. 7965 ip_families = connection.options.ip_families
  40. 7965 resolved = false
  41. 8306 addresses.group_by(&:family).sort { |(f1, _), (f2, _)| f2 <=> f1 }.each do |family, addrs|
  42. 8287 next unless ip_families.nil? || ip_families.include?(family)
  43. # try to match the resolver by family. However, there are cases where that's not possible, as when
  44. # the system does not have IPv6 connectivity, but it does support IPv6 via loopback/link-local.
  45. 16598 resolver = @resolvers.find { |r| r.family == family } || @resolvers.first
  46. 8287 next unless resolver # this should ever happen
  47. # it does not matter which resolver it is, as early-resolve code is shared.
  48. 8287 resolver.emit_addresses(connection, family, addrs, true)
  49. 8251 resolved = true
  50. end
  51. 7929 resolved
  52. end
  53. 30 def lazy_resolve(connection)
  54. 617 @resolvers.each do |resolver|
  55. 669 conn_to_resolve = @current_session.try_clone_connection(connection, @current_selector, resolver.family)
  56. 669 resolver << conn_to_resolve
  57. 648 next if resolver.empty?
  58. # both the resolver and the connection it's resolving must be pineed to the session
  59. 522 @current_session.pin(conn_to_resolve, @current_selector)
  60. 522 @current_session.select_resolver(resolver, @current_selector)
  61. end
  62. end
  63. 30 private
  64. 30 def nolookup_resolve(hostname, options)
  65. 8263 options.resolver_cache.resolve(hostname)
  66. end
  67. end
  68. end

lib/httpx/resolver/native.rb

92.17% lines covered

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

lib/httpx/resolver/resolver.rb

96.74% lines covered

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

lib/httpx/resolver/system.rb

95.42% lines covered

153 relevant lines. 146 lines covered and 7 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "resolv"
  3. 30 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. 30 class Resolver::System < Resolver::Resolver
  14. 30 using URIExtensions
  15. 30 RESOLV_ERRORS = [Resolv::ResolvError,
  16. Resolv::DNS::Requester::RequestError,
  17. Resolv::DNS::EncodeError,
  18. Resolv::DNS::DecodeError].freeze
  19. 30 DONE = 1
  20. 30 ERROR = 2
  21. 30 class << self
  22. 30 def multi?
  23. 178 false
  24. end
  25. end
  26. 30 attr_reader :state
  27. 30 def initialize(options)
  28. 178 super(0, options)
  29. 178 @resolver_options = @options.resolver_options
  30. 178 resolv_options = @resolver_options.dup
  31. 178 timeouts = resolv_options.delete(:timeouts) || Resolver::RESOLVE_TIMEOUT
  32. 178 @_timeouts = Array(timeouts)
  33. 347 @timeouts = Hash.new { |tims, host| tims[host] = @_timeouts.dup }
  34. 178 resolv_options.delete(:cache)
  35. 178 @queries = []
  36. 178 @ips = []
  37. 178 @pipe_mutex = Thread::Mutex.new
  38. 178 @state = :idle
  39. end
  40. 30 def resolvers
  41. 56 return enum_for(__method__) unless block_given?
  42. 28 yield self
  43. end
  44. 30 def multi
  45. 109 self
  46. end
  47. 30 def empty?
  48. 169 @connections.empty?
  49. end
  50. 30 def close
  51. 169 transition(:closed)
  52. end
  53. 30 def force_close(*)
  54. 56 close
  55. 56 @queries.clear
  56. 56 @timeouts.clear
  57. 56 @ips.clear
  58. 56 super
  59. end
  60. 30 def closed?
  61. 226 @state == :closed
  62. end
  63. 30 def to_io
  64. 445 @pipe_read.to_io
  65. end
  66. 30 def call
  67. 96 case @state
  68. when :open
  69. 96 consume
  70. end
  71. 29 nil
  72. end
  73. 30 def interests
  74. 302 return if @queries.empty?
  75. 302 :r
  76. end
  77. 30 def timeout
  78. 302 _, connection = @queries.first
  79. 302 return unless connection
  80. 302 timeouts = @timeouts[connection.peer.host]
  81. 302 return if timeouts.empty?
  82. 302 log(level: 2) { "resolver #{FAMILY_TYPES[@record_type]}: next timeout #{timeouts.first} secs... (#{timeouts.size - 1} left)" }
  83. 302 timeouts.first
  84. end
  85. 30 def lazy_resolve(connection)
  86. 169 @connections << connection
  87. 169 resolve
  88. 169 return if empty?
  89. 166 @current_session.select_resolver(self, @current_selector)
  90. end
  91. 30 def early_resolve(connection, **); end
  92. 30 def handle_socket_timeout(interval)
  93. 14 error = HTTPX::ResolveTimeoutError.new(interval, "timed out while waiting on select")
  94. 14 error.set_backtrace(caller)
  95. 14 @queries.each do |_, connection| # rubocop:disable Style/HashEachMethods
  96. 14 emit_resolve_error(connection, connection.peer.host, error) if @connections.delete(connection)
  97. end
  98. 28 while (connection = @connections.shift)
  99. emit_resolve_error(connection, connection.peer.host, error)
  100. end
  101. 14 close_or_resolve
  102. end
  103. 30 private
  104. 30 def transition(nextstate)
  105. 338 case nextstate
  106. when :idle
  107. @timeouts.clear
  108. when :open
  109. 169 return unless @state == :idle
  110. 169 @pipe_read, @pipe_write = IO.pipe
  111. when :closed
  112. 169 return unless @state == :open
  113. 169 @pipe_write.close
  114. 169 @pipe_read.close
  115. end
  116. 338 @state = nextstate
  117. end
  118. 30 def consume
  119. 265 return if @connections.empty?
  120. 265 event = @pipe_read.read_nonblock(1, exception: false)
  121. 265 return if event == :wait_readable
  122. 99 raise ResolveError, "socket pipe closed unexpectedly" if event.nil?
  123. 99 case event.unpack1("C")
  124. when DONE
  125. 168 *pair, addrs = @pipe_mutex.synchronize { @ips.pop }
  126. 84 if pair
  127. 84 @queries.delete(pair)
  128. 84 family, connection = pair
  129. 84 @connections.delete(connection)
  130. 168 catch(:coalesced) { emit_addresses(connection, family, addrs) }
  131. end
  132. when ERROR
  133. 30 *pair, error = @pipe_mutex.synchronize { @ips.pop }
  134. 15 if pair && error
  135. 15 @queries.delete(pair)
  136. 15 _, connection = pair
  137. 15 @connections.delete(connection)
  138. 15 emit_resolve_error(connection, connection.peer.host, error)
  139. end
  140. end
  141. 99 return disconnect if @connections.empty?
  142. resolve
  143. rescue StandardError => e
  144. on_error(e)
  145. end
  146. 30 def resolve(connection = nil, hostname = nil)
  147. 169 @connections.shift until @connections.empty? || @connections.first.state != :closed
  148. 169 connection ||= @connections.first
  149. 169 raise Error, "no URI to resolve" unless connection
  150. 169 return unless @queries.empty?
  151. 169 hostname ||= connection.peer.host
  152. 169 scheme = connection.origin.scheme
  153. log do
  154. "resolver: resolve IDN #{connection.peer.non_ascii_hostname} as #{hostname}"
  155. 169 end if connection.peer.non_ascii_hostname
  156. 169 transition(:open)
  157. 169 ip_families = connection.options.ip_families || Resolver.supported_ip_families
  158. 169 ip_families.each do |family|
  159. 204 @queries << [family, connection]
  160. end
  161. 169 async_resolve(connection, hostname, scheme)
  162. 169 consume
  163. end
  164. 30 def async_resolve(connection, hostname, scheme)
  165. 169 families = connection.options.ip_families || Resolver.supported_ip_families
  166. 169 log { "resolver: query for #{hostname}" }
  167. 169 timeouts = @timeouts[connection.peer.host]
  168. 169 resolve_timeout = timeouts.first
  169. 169 Thread.start do
  170. 169 Thread.current.report_on_exception = false
  171. begin
  172. 169 addrs = if resolve_timeout
  173. 169 Timeout.timeout(resolve_timeout) do
  174. 169 __addrinfo_resolve(hostname, scheme)
  175. end
  176. else
  177. __addrinfo_resolve(hostname, scheme)
  178. end
  179. 154 addrs = addrs.sort_by(&:afamily).group_by(&:afamily)
  180. 154 families.each do |family|
  181. 189 addresses = addrs[family]
  182. 189 next unless addresses
  183. 154 addresses.map!(&:ip_address)
  184. 154 addresses.uniq!
  185. 154 @pipe_mutex.synchronize do
  186. 154 @ips.unshift([family, connection, addresses])
  187. 154 @pipe_write.putc(DONE) unless @pipe_write.closed?
  188. end
  189. end
  190. rescue StandardError => e
  191. 15 if e.is_a?(Timeout::Error)
  192. 1 timeouts.shift
  193. 1 retry unless timeouts.empty?
  194. 1 e = ResolveTimeoutError.new(resolve_timeout, e.message)
  195. 1 e.set_backtrace(e.backtrace)
  196. end
  197. 15 @pipe_mutex.synchronize do
  198. 15 families.each do |family|
  199. 15 @ips.unshift([family, connection, e])
  200. 15 @pipe_write.putc(ERROR) unless @pipe_write.closed?
  201. end
  202. end
  203. end
  204. end
  205. 169 Thread.pass
  206. end
  207. 30 def close_or_resolve
  208. # drop already closed connections
  209. 14 @connections.shift until @connections.empty? || @connections.first.state != :closed
  210. 14 if (@connections - @queries.map(&:last)).empty?
  211. 14 disconnect
  212. else
  213. resolve
  214. end
  215. end
  216. 30 def __addrinfo_resolve(host, scheme)
  217. 169 Addrinfo.getaddrinfo(host, scheme, Socket::AF_UNSPEC, Socket::SOCK_STREAM)
  218. end
  219. end
  220. end

lib/httpx/response.rb

100.0% lines covered

124 relevant lines. 124 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "objspace"
  3. 30 require "stringio"
  4. 30 require "tempfile"
  5. 30 require "fileutils"
  6. 30 require "forwardable"
  7. 30 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. 30 class Response
  21. 30 extend Forwardable
  22. 30 include Callbacks
  23. # the HTTP response status code
  24. 30 attr_reader :status
  25. # an HTTPX::Headers object containing the response HTTP headers.
  26. 30 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. 30 attr_reader :body
  35. # The HTTP protocol version used to fetch the response.
  36. 30 attr_reader :version
  37. # returns the response body buffered in a string.
  38. 30 def_delegator :@body, :to_s
  39. 30 def_delegator :@body, :to_str
  40. # implements the IO reader +#read+ interface.
  41. 30 def_delegator :@body, :read
  42. # copies the response body to a different location.
  43. 30 def_delegator :@body, :copy_to
  44. # the corresponding request uri.
  45. 30 def_delegator :@request, :uri
  46. # the IP address of the peer server.
  47. 30 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. 30 def initialize(request, status, version, headers)
  51. 11125 @request = request
  52. 11125 @options = request.options
  53. 11125 @version = version
  54. 11125 @status = Integer(status)
  55. 11125 @headers = @options.headers_class.new(headers)
  56. 11125 @body = @options.response_body_class.new(self, @options)
  57. 11125 @finished = complete?
  58. 11125 @content_type = nil
  59. end
  60. # dupped initialization
  61. 30 def initialize_dup(orig)
  62. 72 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. 72 @body = orig.body.dup
  66. end
  67. # closes the respective +@request+ and +@body+.
  68. 30 def close
  69. 522 @request.close
  70. 522 @body.close
  71. end
  72. # merges headers defined in +h+ into the response headers.
  73. 30 def merge_headers(h)
  74. 223 @headers = @headers.merge(h)
  75. end
  76. # writes +data+ chunk into the response body.
  77. 30 def <<(data)
  78. 15160 @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. 30 def content_type
  85. 11620 @content_type ||= ContentType.new(@headers["content-type"])
  86. end
  87. # returns whether the response has been fully fetched.
  88. 30 def finished?
  89. 17353 @finished
  90. end
  91. # marks the response as finished, freezes the headers.
  92. 30 def finish!
  93. 9874 @finished = true
  94. 9874 @headers.freeze
  95. end
  96. # returns whether the response contains body payload.
  97. 30 def bodyless?
  98. 11125 @request.verb == "HEAD" ||
  99. @status < 200 || # informational response
  100. @status == 204 ||
  101. @status == 205 ||
  102. @status == 304 || begin
  103. 10616 content_length = @headers["content-length"]
  104. 10616 return false if content_length.nil?
  105. 8960 content_length == "0"
  106. end
  107. end
  108. 30 def complete?
  109. 11125 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. 30 def error
  126. 790 return if @status < 400
  127. 68 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. 30 def raise_for_status
  134. 736 return self unless (err = error)
  135. 50 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. 30 def json(*args)
  142. 216 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. 30 def form
  147. 72 decode(Transcoder::Form)
  148. end
  149. 30 def xml
  150. # TODO: remove at next major version.
  151. 9 warn "DEPRECATION WARNING: calling `.#{__method__}` on plain HTTPX responses is deprecated. " \
  152. 1 "Use HTTPX.plugin(:xml) sessions and call `.#{__method__}` in its responses instead."
  153. 9 require "httpx/plugins/xml"
  154. 9 decode(Plugins::XML::Transcoder)
  155. end
  156. 30 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. 30 def decode(transcoder, *args)
  162. # TODO: check if content-type is a valid format, i.e. "application/json" for json parsing
  163. 315 decoder = transcoder.decode(self)
  164. 288 raise Error, "no decoder available for \"#{transcoder}\"" unless decoder
  165. 288 @body.rewind
  166. 288 decoder.call(self, *args)
  167. end
  168. end
  169. # Helper class which decodes the HTTP "content-type" header.
  170. 30 class ContentType
  171. 30 MIME_TYPE_RE = %r{^([^/]+/[^;]+)(?:$|;)}.freeze
  172. 30 CHARSET_RE = /;\s*charset=([^;]+)/i.freeze
  173. 30 def initialize(header_value)
  174. 11578 @header_value = header_value
  175. 11578 @mime_type = @charset = nil
  176. 11578 @initialized = false
  177. end
  178. # returns the mime type declared in the header.
  179. #
  180. # ContentType.new("application/json; charset=utf-8").mime_type #=> "application/json"
  181. 30 def mime_type
  182. 315 return @mime_type if @initialized
  183. 273 load
  184. 273 @mime_type
  185. end
  186. # returns the charset declared in the header.
  187. #
  188. # ContentType.new("application/json; charset=utf-8").charset #=> "utf-8"
  189. # ContentType.new("text/plain").charset #=> nil
  190. 30 def charset
  191. 11305 return @charset if @initialized
  192. 11305 load
  193. 11305 @charset
  194. end
  195. 30 private
  196. 30 def load
  197. 11578 m = @header_value.to_s[MIME_TYPE_RE, 1]
  198. 11578 m && @mime_type = m.strip.downcase
  199. 11578 c = @header_value.to_s[CHARSET_RE, 1]
  200. 11578 c && @charset = c.strip.delete('"')
  201. 11578 @initialized = true
  202. end
  203. end
  204. # Wraps an error which has happened while processing an HTTP Request. It has partial
  205. # public API parity with HTTPX::Response, so users should rely on it to infer whether
  206. # the returned response is one or the other.
  207. #
  208. # response = HTTPX.get("https://some-domain/path") #=> response is HTTPX::Response or HTTPX::ErrorResponse
  209. # response.raise_for_status #=> raises if it wraps an error
  210. 30 class ErrorResponse
  211. 30 include Loggable
  212. 30 extend Forwardable
  213. # the corresponding HTTPX::Request instance.
  214. 30 attr_reader :request
  215. # the HTTPX::Response instance, when there is one (i.e. error happens fetching the response).
  216. 30 attr_reader :response
  217. # the wrapped exception.
  218. 30 attr_reader :error
  219. # the request uri
  220. 30 def_delegator :@request, :uri
  221. # the IP address of the peer server.
  222. 30 def_delegator :@request, :peer_address
  223. 30 def initialize(request, error)
  224. 1543 @request = request
  225. 1543 @response = request.response if request.response.is_a?(Response)
  226. 1543 @error = error
  227. 1543 @options = request.options
  228. 1543 log_exception(@error)
  229. end
  230. # returns the exception full message.
  231. 30 def to_s
  232. 9 @error.full_message(highlight: false)
  233. end
  234. # closes the error resources.
  235. 30 def close
  236. 45 @response.close if @response
  237. end
  238. # always true for error responses.
  239. 30 def finished?
  240. 1385 true
  241. end
  242. 30 def finish!; end
  243. # raises the wrapped exception.
  244. 30 def raise_for_status
  245. 105 raise @error
  246. end
  247. # buffers lost chunks to error response
  248. 30 def <<(data)
  249. 9 return unless @response
  250. 9 @response << data
  251. end
  252. end
  253. end
  254. 30 require_relative "response/body"
  255. 30 require_relative "response/buffer"
  256. 30 require_relative "pmatch_extensions" if RUBY_VERSION >= "2.7.0"

lib/httpx/response/body.rb

100.0% lines covered

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

lib/httpx/response/buffer.rb

96.72% lines covered

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

lib/httpx/selector.rb

91.1% lines covered

146 relevant lines. 133 lines covered and 13 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "io/wait"
  3. 30 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. 30 class Selector
  20. 30 extend Forwardable
  21. 30 READABLE = %i[rw r].freeze
  22. 30 WRITABLE = %i[rw w].freeze
  23. 30 private_constant :READABLE
  24. 30 private_constant :WRITABLE
  25. 30 def_delegator :@timers, :after
  26. 30 def_delegator :@selectables, :empty?
  27. 30 def initialize
  28. 9388 @timers = Timers.new
  29. 9388 @selectables = []
  30. 9388 @is_timer_interval = false
  31. end
  32. 30 def each(&blk)
  33. @selectables.each(&blk)
  34. end
  35. 30 def next_tick
  36. 43460 catch(:jump_tick) do
  37. 43460 timeout = next_timeout
  38. 43460 if timeout && timeout.negative?
  39. @timers.fire
  40. throw(:jump_tick)
  41. end
  42. 2515 begin
  43. 43460 select(timeout) do |c|
  44. 32161 c.log(level: 2) { "[#{c.state}] selected from selector##{object_id} #{" after #{timeout} secs" unless timeout.nil?}..." }
  45. 31977 c.call
  46. end
  47. 43214 @timers.fire
  48. rescue TimeoutError => e
  49. @timers.fire(e)
  50. end
  51. end
  52. end
  53. 30 def terminate
  54. # array may change during iteration
  55. 9131 selectables = @selectables.reject(&:inflight?)
  56. 9131 selectables.delete_if do |sel|
  57. 3631 sel.terminate
  58. 3622 sel.state == :closed
  59. end
  60. 9122 until selectables.empty?
  61. 4 next_tick
  62. 4 selectables &= @selectables
  63. end
  64. end
  65. 30 def find_resolver(options)
  66. 8750 res = @selectables.find do |c|
  67. 65 c.is_a?(Resolver::Resolver) && options == c.options
  68. end
  69. 8750 res.multi if res
  70. end
  71. 30 def each_connection(&block)
  72. 41932 return enum_for(__method__) unless block
  73. 20966 @selectables.each do |c|
  74. 2781 case c
  75. when Resolver::Resolver
  76. 510 c.each_connection(&block)
  77. when Connection
  78. 2366 yield c
  79. end
  80. end
  81. end
  82. 30 def find_connection(request_uri, options)
  83. 11319 each_connection.find do |connection|
  84. 1419 connection.match?(request_uri, options)
  85. end
  86. end
  87. 30 def find_mergeable_connection(connection)
  88. 9009 each_connection.find do |ch|
  89. 641 ch != connection && ch.mergeable?(connection)
  90. end
  91. end
  92. # deregisters +io+ from selectables.
  93. 30 def deregister(io)
  94. 10910 @selectables.delete(io)
  95. end
  96. # register +io+.
  97. 30 def register(io)
  98. 11237 return if @selectables.include?(io)
  99. 10539 @selectables << io
  100. end
  101. 30 private
  102. 30 def select(interval, &block)
  103. # do not cause an infinite loop here.
  104. #
  105. # this may happen if timeout calculation actually triggered an error which causes
  106. # the connections to be reaped (such as the total timeout error) before #select
  107. # gets called.
  108. 43460 if @selectables.empty?
  109. 171 sleep(interval) if interval
  110. 153 return
  111. end
  112. # @type var r: (selectable | Array[selectable])?
  113. # @type var w: (selectable | Array[selectable])?
  114. 43289 r, w = nil
  115. 43289 @selectables.delete_if do |io|
  116. 44607 interests = io.interests
  117. 44607 is_closed = io.state == :closed
  118. 44607 next(is_closed) if is_closed
  119. 44504 io.log(level: 2) do
  120. 184 "[#{io.state}] registering in selector##{object_id} for select (#{interests})#{" for #{interval} seconds" unless interval.nil?}"
  121. end
  122. 44504 if READABLE.include?(interests)
  123. 21999 r = r.nil? ? io : (Array(r) << io)
  124. end
  125. 44504 if WRITABLE.include?(interests)
  126. 12234 w = w.nil? ? io : (Array(w) << io)
  127. end
  128. 44504 is_closed
  129. end
  130. 40836 case r
  131. when Array
  132. 627 w = Array(w) unless w.nil?
  133. 627 select_many(r, w, interval, &block)
  134. when nil
  135. 20906 case w
  136. when Array
  137. 57 select_many(r, w, interval, &block)
  138. when nil
  139. 10526 return unless interval && @selectables.any?
  140. # no selectables
  141. # TODO: replace with sleep?
  142. 72 select_many(r, w, interval, &block)
  143. else
  144. 11361 select_one(w, :w, interval, &block)
  145. end
  146. else
  147. 19350 case w
  148. when Array
  149. 4 select_many(Array(r), w, interval, &block)
  150. when nil
  151. 20030 select_one(r, :r, interval, &block)
  152. else
  153. 684 if r == w
  154. 483 select_one(r, :rw, interval, &block)
  155. else
  156. 201 select_many(Array(r), Array(w), interval, &block)
  157. end
  158. end
  159. end
  160. end
  161. 30 def select_many(r, w, interval, &block)
  162. 40 begin
  163. 961 readers, writers = ::IO.select(r, w, nil, interval)
  164. rescue IOError => e
  165. (Array(r) + Array(w)).each do |sel|
  166. # TODO: is there a way to cheaply find the IO associated with the error?
  167. sel.on_error(e)
  168. sel.force_close(true)
  169. end
  170. rescue StandardError => e
  171. (Array(r) + Array(w)).each do |sel|
  172. sel.on_error(e)
  173. end
  174. return
  175. rescue Exception => e # rubocop:disable Lint/RescueException
  176. 42 (Array(r) + Array(w)).each do |sel|
  177. 84 sel.force_close(true)
  178. end
  179. 42 raise e
  180. end
  181. 919 if readers.nil? && writers.nil? && interval
  182. 118 [*r, *w].each { |io| io.handle_socket_timeout(interval) }
  183. 83 return
  184. end
  185. 832 if writers
  186. 57 readers.each do |io|
  187. 632 yield io
  188. # so that we don't yield 2 times
  189. 623 writers.delete(io)
  190. 831 end if readers
  191. 823 writers.each(&block)
  192. else
  193. readers.each(&block) if readers
  194. end
  195. end
  196. 30 def select_one(io, interests, interval)
  197. 2452 begin
  198. 4840 result =
  199. 27034 case interests
  200. 20030 when :r then io.to_io.wait_readable(interval)
  201. 11361 when :w then io.to_io.wait_writable(interval)
  202. 483 when :rw then rw_wait(io, interval)
  203. end
  204. rescue IOError => e
  205. io.on_error(e)
  206. io.force_close(true)
  207. rescue StandardError => e
  208. 14 io.on_error(e)
  209. 14 return
  210. rescue Exception => e # rubocop:disable Lint/RescueException
  211. 42 io.force_close(true)
  212. 42 raise e
  213. end
  214. 31818 unless result || interval.nil?
  215. 752 io.handle_socket_timeout(interval) unless @is_timer_interval
  216. 672 return
  217. end
  218. 31066 yield io
  219. end
  220. 30 def next_timeout
  221. 43460 @is_timer_interval = false
  222. 43460 timer_interval = @timers.wait_interval
  223. 43460 connection_interval = @selectables.filter_map(&:timeout).min
  224. 43460 return connection_interval unless timer_interval
  225. 13670 if connection_interval.nil? || timer_interval <= connection_interval
  226. 13612 @is_timer_interval = true
  227. 12729 return timer_interval
  228. end
  229. 58 connection_interval
  230. end
  231. 30 if RUBY_ENGINE == "jruby"
  232. 1 def rw_wait(io, interval)
  233. 69 io.to_io.wait(interval, :read_write)
  234. end
  235. 29 elsif IO.const_defined?(:READABLE)
  236. 27 def rw_wait(io, interval)
  237. 361 io.to_io.wait(IO::READABLE | IO::WRITABLE, interval)
  238. end
  239. else
  240. 2 def rw_wait(io, interval)
  241. 53 if interval
  242. 52 io.to_io.wait(interval, :read_write)
  243. else
  244. 1 io.to_io.wait(:read_write)
  245. end
  246. end
  247. end
  248. end
  249. end

lib/httpx/session.rb

95.27% lines covered

296 relevant lines. 282 lines covered and 14 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 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. 30 class Session
  8. 30 include Loggable
  9. 30 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. 30 def initialize(options = EMPTY_HASH, &blk)
  15. 13990 @options = self.class.default_options.merge(options)
  16. 13990 @persistent = @options.persistent
  17. 13990 @pool = @options.pool_class.new(@options.pool_options)
  18. 13990 @wrapped = false
  19. 13990 @closing = false
  20. 13990 INSTANCES[self] = self if @persistent && @options.close_on_fork && INSTANCES
  21. 13990 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. 30 def wrap
  29. 819 prev_wrapped = @wrapped
  30. 819 @wrapped = true
  31. 819 was_initialized = false
  32. 819 current_selector = get_current_selector do
  33. 819 selector = Selector.new
  34. 819 set_current_selector(selector)
  35. 819 was_initialized = true
  36. 819 selector
  37. end
  38. 58 begin
  39. 819 yield self
  40. ensure
  41. 819 unless prev_wrapped
  42. 819 if @persistent
  43. 1 deactivate(current_selector)
  44. else
  45. 818 close(current_selector)
  46. end
  47. end
  48. 819 @wrapped = prev_wrapped
  49. 819 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. 30 def close(selector = Selector.new)
  58. # throw resolvers away from the pool
  59. 8798 @pool.reset_resolvers
  60. # preparing to throw away connections
  61. 21089 while (connection = @pool.pop_connection)
  62. 5769 next if connection.state == :closed
  63. 247 select_connection(connection, selector)
  64. end
  65. 8798 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. 30 def request(*args, **params)
  88. 9184 raise ArgumentError, "must perform at least one request" if args.empty?
  89. 9184 requests = args.first.is_a?(Request) ? args : build_requests(*args, params)
  90. 9141 responses = send_requests(*requests)
  91. 8872 return responses.first if responses.size == 1
  92. 254 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. 30 def build_request(verb, uri, params = EMPTY_HASH, options = @options)
  101. 11069 rklass = options.request_class
  102. 11069 request = rklass.new(verb, uri, options, params)
  103. 11017 request.persistent = @persistent
  104. 11017 set_request_callbacks(request)
  105. 11017 request
  106. end
  107. 30 def select_connection(connection, selector)
  108. 11147 pin(connection, selector)
  109. 11147 connection.log(level: 2) do
  110. 100 "registering into selector##{selector.object_id}"
  111. end
  112. 11147 selector.register(connection)
  113. end
  114. 30 def pin(conn_or_resolver, selector)
  115. 29193 conn_or_resolver.current_session = self
  116. 29193 conn_or_resolver.current_selector = selector
  117. end
  118. 30 alias_method :select_resolver, :select_connection
  119. 30 def deselect_connection(connection, selector, cloned = false)
  120. 10214 connection.log(level: 2) do
  121. 86 "deregistering connection##{connection.object_id}(#{connection.state}) from selector##{selector.object_id}"
  122. end
  123. 10214 selector.deregister(connection)
  124. 10214 return if cloned
  125. 10181 return if @closing && connection.state == :closed
  126. 10249 connection.log(level: 2) { "check-in connection##{connection.object_id}(#{connection.state}) in pool##{@pool.object_id}" }
  127. 10163 @pool.checkin_connection(connection)
  128. end
  129. 30 def deselect_resolver(resolver, selector)
  130. 633 resolver.log(level: 2) do
  131. "deregistering resolver##{resolver.object_id}(#{resolver.state}) from selector##{selector.object_id}"
  132. end
  133. 633 selector.deregister(resolver)
  134. 633 return if @closing && resolver.closed?
  135. 610 resolver.log(level: 2) { "check-in resolver##{resolver.object_id}(#{resolver.state}) in pool##{@pool.object_id}" }
  136. 610 @pool.checkin_resolver(resolver)
  137. end
  138. 30 def try_clone_connection(connection, selector, family)
  139. 669 connection.family ||= family
  140. 669 return connection if connection.family == family
  141. 52 new_connection = connection.class.new(connection.origin, connection.options)
  142. 52 new_connection.family = family
  143. 52 connection.sibling = new_connection
  144. 52 do_init_connection(new_connection, selector)
  145. 52 new_connection
  146. end
  147. # returns the HTTPX::Connection through which the +request+ should be sent through.
  148. 30 def find_connection(request_uri, selector, options)
  149. 11319 log(level: 2) { "finding connection for #{request_uri}..." }
  150. 11319 if (connection = selector.find_connection(request_uri, options))
  151. 1325 connection.idling if connection.state == :closed
  152. 1325 connection.log(level: 2) { "found connection##{connection.object_id}(#{connection.state}) in selector##{selector.object_id}" }
  153. 1257 return connection
  154. end
  155. 9994 connection = @pool.checkout_connection(request_uri, options)
  156. 10044 connection.log(level: 2) { "found connection##{connection.object_id}(#{connection.state}) in pool##{@pool.object_id}" }
  157. 9001 case connection.state
  158. when :idle
  159. 8993 do_init_connection(connection, selector)
  160. when :open
  161. 75 if options.io
  162. 75 select_connection(connection, selector)
  163. else
  164. pin(connection, selector)
  165. end
  166. when :closing, :closed
  167. 859 connection.idling
  168. 859 if connection.addresses?
  169. 851 select_connection(connection, selector)
  170. else
  171. # if addresses expired, resolve again
  172. 8 resolve_connection(connection, selector)
  173. end
  174. else
  175. 31 pin(connection, selector)
  176. end
  177. 9901 connection
  178. end
  179. 30 private
  180. 30 def selector_close(selector)
  181. begin
  182. 9131 @closing = true
  183. 9131 selector.terminate
  184. ensure
  185. 9131 @closing = false
  186. end
  187. end
  188. # tries deactivating connections in the +selector+, deregistering the ones that have been deactivated.
  189. 30 def deactivate(selector)
  190. 638 selector.each_connection.to_a.each(&:deactivate)
  191. end
  192. # callback executed when an HTTP/2 promise frame has been received.
  193. 30 def on_promise(_, stream)
  194. 9 log(level: 2) { "#{stream.id}: refusing stream!" }
  195. 9 stream.refuse
  196. end
  197. # returns the corresponding HTTP::Response to the given +request+ if it has been received.
  198. 30 def fetch_response(request, _selector, _options)
  199. 53326 response = request.response
  200. 53326 return unless response && response.finished?
  201. 10952 log(level: 2) { "response fetched" }
  202. 10952 response
  203. end
  204. # sends the +request+ to the corresponding HTTPX::Connection
  205. 30 def send_request(request, selector, options = request.options)
  206. 2032 error = begin
  207. 11144 catch(:resolve_error) do
  208. 11144 connection = find_connection(request.uri, selector, options)
  209. 11024 connection.send(request)
  210. end
  211. rescue StandardError => e
  212. 45 e
  213. end
  214. 11137 return unless error && error.is_a?(Exception)
  215. 120 raise error unless error.is_a?(Error)
  216. 113 response = ErrorResponse.new(request, error)
  217. 113 request.response = response
  218. 113 request.emit(:response, response)
  219. end
  220. # returns a set of HTTPX::Request objects built from the given +args+ and +options+.
  221. 30 def build_requests(*args, params)
  222. 8421 requests = if args.size == 1
  223. 88 reqs = args.first
  224. 88 reqs.map do |verb, uri, ps = EMPTY_HASH|
  225. 176 request_params = params
  226. 176 request_params = request_params.merge(ps) unless ps.empty?
  227. 176 build_request(verb, uri, request_params)
  228. end
  229. else
  230. 8333 verb, uris = args
  231. 8333 if uris.respond_to?(:each)
  232. 8063 uris.enum_for(:each).map do |uri, ps = EMPTY_HASH|
  233. 8871 request_params = params
  234. 8871 request_params = request_params.merge(ps) unless ps.empty?
  235. 8871 build_request(verb, uri, request_params)
  236. end
  237. else
  238. 270 [build_request(verb, uris, params)]
  239. end
  240. end
  241. 8378 raise ArgumentError, "wrong number of URIs (given 0, expect 1..+1)" if requests.empty?
  242. 8378 requests
  243. end
  244. 30 def set_request_callbacks(request)
  245. 10873 request.on(:promise, &method(:on_promise))
  246. end
  247. 30 def do_init_connection(connection, selector)
  248. 9045 resolve_connection(connection, selector) unless connection.family
  249. end
  250. # sends an array of HTTPX::Request +requests+, returns the respective array of HTTPX::Response objects.
  251. 30 def send_requests(*requests)
  252. 17459 selector = get_current_selector { Selector.new }
  253. 877 begin
  254. 9251 _send_requests(requests, selector)
  255. 9237 receive_requests(requests, selector)
  256. ensure
  257. 9224 unless @wrapped
  258. 8256 if @persistent
  259. 637 deactivate(selector)
  260. else
  261. 7619 close(selector)
  262. end
  263. end
  264. end
  265. end
  266. # sends an array of HTTPX::Request objects
  267. 30 def _send_requests(requests, selector)
  268. 9251 requests.each do |request|
  269. 10130 send_request(request, selector)
  270. end
  271. end
  272. # returns the array of HTTPX::Response objects corresponding to the array of HTTPX::Request +requests+.
  273. 30 def receive_requests(requests, selector)
  274. 9237 responses = [] # : Array[response]
  275. # guarantee ordered responses
  276. 9237 loop do
  277. 10125 request = requests.first
  278. 10125 return responses unless request
  279. 54937 catch(:coalesced) { selector.next_tick } until (response = fetch_response(request, selector, request.options))
  280. 9870 request.complete!(response)
  281. 9870 responses << response
  282. 9870 requests.shift
  283. 9870 break if requests.empty?
  284. 888 next unless selector.empty?
  285. # in some cases, the pool of connections might have been drained because there was some
  286. # handshake error, and the error responses have already been emitted, but there was no
  287. # opportunity to traverse the requests, hence we're returning only a fraction of the errors
  288. # we were supposed to. This effectively fetches the existing responses and return them.
  289. exit_from_loop = true
  290. requests_to_remove = [] # : Array[Request]
  291. requests.each do |req|
  292. response = fetch_response(req, selector, request.options)
  293. if exit_from_loop && response
  294. req.complete!(response)
  295. responses << response
  296. requests_to_remove << req
  297. else
  298. # fetch_response may resend requests. when that happens, we need to go back to the initial
  299. # loop and process the selector. we still do a pass-through on the remainder of requests, so
  300. # that every request that need to be resent, is resent.
  301. exit_from_loop = false
  302. raise Error, "something went wrong, responses not found and requests not resent" if selector.empty?
  303. end
  304. end
  305. break if exit_from_loop
  306. requests -= requests_to_remove
  307. end
  308. 8982 responses
  309. end
  310. 30 def resolve_connection(connection, selector)
  311. 9029 if connection.addresses? || connection.open?
  312. #
  313. # there are two cases in which we want to activate initialization of
  314. # connection immediately:
  315. #
  316. # 1. when the connection already has addresses, i.e. it doesn't need to
  317. # resolve a name (not the same as name being an IP, yet)
  318. # 2. when the connection is initialized with an external already open IO.
  319. #
  320. 279 on_resolver_connection(connection, selector)
  321. 277 return
  322. end
  323. 8750 resolver = find_resolver_for(connection, selector)
  324. 8750 pin(connection, selector)
  325. 8750 resolver.early_resolve(connection) || resolver.lazy_resolve(connection)
  326. end
  327. 30 def on_resolver_connection(connection, selector)
  328. 9009 from_pool = false
  329. 9009 found_connection = selector.find_mergeable_connection(connection) || begin
  330. 8976 from_pool = true
  331. 8976 connection.log(level: 2) do
  332. 100 "try finding a mergeable connection in pool##{@pool.object_id}"
  333. end
  334. 8976 @pool.checkout_mergeable_connection(connection)
  335. end
  336. 9009 return select_connection(connection, selector) unless found_connection
  337. 55 connection.log(level: 2) do
  338. "try coalescing from #{from_pool ? "pool##{@pool.object_id}" : "selector##{selector.object_id}"} " \
  339. "(connection##{found_connection.object_id}[#{found_connection.origin}])"
  340. end
  341. 55 coalesce_connections(found_connection, connection, selector, from_pool)
  342. end
  343. 30 def find_resolver_for(connection, selector)
  344. 8750 if (resolver = selector.find_resolver(connection.options))
  345. 7 resolver.log(level: 2) { "found resolver##{resolver.object_id}(#{resolver.state}) in selector##{selector.object_id}" }
  346. 7 return resolver
  347. end
  348. 8743 resolver = @pool.checkout_resolver(connection.options)
  349. 8829 resolver.log(level: 2) { "found resolver##{resolver.object_id}(#{resolver.state}) in pool##{@pool.object_id}" }
  350. 8743 pin(resolver, selector)
  351. 8743 resolver
  352. end
  353. # coalesces +conn2+ into +conn1+. if +conn1+ was loaded from the connection pool
  354. # (it is known via +from_pool+), then it adds its to the +selector+.
  355. 30 def coalesce_connections(conn1, conn2, selector, from_pool)
  356. 55 unless conn1.coalescable?(conn2)
  357. 26 conn2.log(level: 2) { "not coalescing with conn##{conn1.object_id}[#{conn1.origin}])" }
  358. 26 select_connection(conn2, selector)
  359. 26 if from_pool
  360. 8 conn1.log(level: 2) { "check-in connection##{conn1.object_id}(#{conn1.state}) in pool##{@pool.object_id}" }
  361. 8 @pool.checkin_connection(conn1)
  362. end
  363. 26 return
  364. end
  365. 29 conn2.log(level: 2) { "coalescing with connection##{conn1.object_id}[#{conn1.origin}])" }
  366. 29 select_connection(conn1, selector) if from_pool
  367. 29 conn2.coalesce!(conn1)
  368. 29 conn2.disconnect
  369. end
  370. 30 def get_current_selector
  371. 10098 selector_store[self] || (yield if block_given?)
  372. end
  373. 30 def set_current_selector(selector)
  374. 2234 if selector
  375. 1311 selector_store[self] = selector
  376. else
  377. 819 selector_store.delete(self)
  378. end
  379. end
  380. 30 def selector_store
  381. 12332 th_current = Thread.current
  382. 12332 thread_selector_store(th_current) || begin
  383. 239 {}.compare_by_identity.tap do |store|
  384. 239 th_current.thread_variable_set(:httpx_persistent_selector_store, store)
  385. end
  386. end
  387. end
  388. 30 def thread_selector_store(th)
  389. 17033 th.thread_variable_get(:httpx_persistent_selector_store)
  390. end
  391. 30 Options.freeze
  392. 30 @default_options = Options.new
  393. 30 @default_options.freeze
  394. 30 @plugins = []
  395. 30 class << self
  396. 30 attr_reader :default_options
  397. 30 def inherited(klass)
  398. 7233 super
  399. 7233 klass.instance_variable_set(:@default_options, @default_options)
  400. 7233 klass.instance_variable_set(:@plugins, @plugins.dup)
  401. 7233 klass.instance_variable_set(:@callbacks, @callbacks.dup)
  402. end
  403. # returns a new HTTPX::Session instance, with the plugin pointed by +pl+ loaded.
  404. #
  405. # session_with_retries = session.plugin(:retries)
  406. # session_with_custom = session.plugin(CustomPlugin)
  407. #
  408. 30 def plugin(pl, options = nil, &block)
  409. 10931 label = pl
  410. 10931 pl = Plugins.load_plugin(pl) if pl.is_a?(Symbol)
  411. 10931 raise ArgumentError, "Invalid plugin type: #{pl.class.inspect}" unless pl.is_a?(Module)
  412. 10923 if !@plugins.include?(pl)
  413. 10612 @plugins << pl
  414. 10612 pl.load_dependencies(self, &block) if pl.respond_to?(:load_dependencies)
  415. 10612 @default_options = @default_options.dup
  416. 10612 include(pl::InstanceMethods) if defined?(pl::InstanceMethods)
  417. 10612 extend(pl::ClassMethods) if defined?(pl::ClassMethods)
  418. 10612 opts = @default_options
  419. 10612 opts.extend_with_plugin_classes(pl)
  420. 10612 if defined?(pl::OptionsMethods)
  421. # when a class gets dup'ed, the #initialize_dup callbacks isn't triggered.
  422. # moreover, and because #method_added does not get triggered on mixin include,
  423. # the callback is also forcefully manually called here.
  424. 4718 opts.options_class.instance_variable_set(:@options_names, opts.options_class.options_names.dup)
  425. 4718 (pl::OptionsMethods.instance_methods + pl::OptionsMethods.private_instance_methods - Object.instance_methods).each do |meth|
  426. 14461 opts.options_class.method_added(meth)
  427. end
  428. 4718 @default_options = opts.options_class.new(opts)
  429. end
  430. 10612 @default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
  431. 10612 @default_options = @default_options.merge(options) if options
  432. 10612 if pl.respond_to?(:subplugins)
  433. 1976 pl.subplugins.transform_keys(&Plugins.method(:load_plugin)).each do |main_pl, sub_pl|
  434. # in case the main plugin has already been loaded, then apply subplugin functionality
  435. # immediately
  436. 2591 next unless @plugins.include?(main_pl)
  437. 80 plugin(sub_pl, options, &block)
  438. end
  439. end
  440. 10612 pl.configure(self, &block) if pl.respond_to?(:configure)
  441. 10612 if label.is_a?(Symbol)
  442. # in case an already-loaded plugin complements functionality of
  443. # the plugin currently being loaded, loaded it now
  444. 7918 @plugins.each do |registered_pl|
  445. 21527 next if registered_pl == pl
  446. 13609 next unless registered_pl.respond_to?(:subplugins)
  447. 3840 sub_pl = registered_pl.subplugins[label]
  448. 3840 next unless sub_pl
  449. 203 plugin(sub_pl, options, &block)
  450. end
  451. end
  452. 10612 @default_options.freeze
  453. 10612 set_temporary_name("#{superclass}/#{pl}") if respond_to?(:set_temporary_name) # ruby 3.4 only
  454. 310 elsif options
  455. # this can happen when two plugins are loaded, an one of them calls the other under the hood,
  456. # albeit changing some default.
  457. 26 @default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
  458. 26 @default_options = @default_options.merge(options) if options
  459. 18 @default_options.freeze
  460. end
  461. 10915 self
  462. end
  463. end
  464. # setup of the support for close_on_fork sessions.
  465. # adapted from https://github.com/mperham/connection_pool/blob/main/lib/connection_pool.rb#L48
  466. 30 if Process.respond_to?(:fork)
  467. 28 INSTANCES = ObjectSpace::WeakMap.new
  468. 28 private_constant :INSTANCES
  469. 28 def self.after_fork
  470. 1 INSTANCES.each_value(&:close)
  471. 1 nil
  472. end
  473. 28 if ::Process.respond_to?(:_fork)
  474. 24 module ForkTracker
  475. 24 def _fork
  476. 1 pid = super
  477. 1 Session.after_fork if pid.zero?
  478. 1 pid
  479. end
  480. end
  481. 24 Process.singleton_class.prepend(ForkTracker)
  482. end
  483. else
  484. 2 INSTANCES = nil
  485. 2 private_constant :INSTANCES
  486. 2 def self.after_fork
  487. # noop
  488. end
  489. end
  490. end
  491. # session may be overridden by certain adapters.
  492. 30 S = Session
  493. 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. 30 module HTTPX
  3. 30 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.75% lines covered

64 relevant lines. 60 lines covered and 4 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 module HTTPX
  3. 30 class Timers
  4. 30 def initialize
  5. 9388 @intervals = []
  6. end
  7. 30 def after(interval_in_secs, cb = nil, &blk)
  8. 43071 callback = cb || blk
  9. 43071 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. 76810 unless (interval = @intervals.bsearch { |t| t.interval == interval_in_secs })
  15. 11467 interval = Interval.new(interval_in_secs)
  16. 11467 @intervals << interval
  17. 11467 @intervals.sort!
  18. end
  19. 43071 interval << callback
  20. 43071 @next_interval_at = nil
  21. 43071 Timer.new(interval, callback)
  22. end
  23. 30 def wait_interval
  24. 43460 return if @intervals.empty?
  25. 13670 first_interval = @intervals.first
  26. 13670 drop_elapsed!(0) if first_interval.elapsed?(0)
  27. 13670 @next_interval_at = Utils.now
  28. 13670 first_interval.interval
  29. end
  30. 30 def fire(error = nil)
  31. 43214 raise error if error && error.timeout != @intervals.first
  32. 43214 return if @intervals.empty? || !@next_interval_at
  33. 12478 elapsed_time = Utils.elapsed_time(@next_interval_at)
  34. 12478 drop_elapsed!(elapsed_time)
  35. 12478 @next_interval_at = nil if @intervals.empty?
  36. end
  37. 30 private
  38. 30 def drop_elapsed!(elapsed_time)
  39. 26844 @intervals = @intervals.drop_while { |interval| interval.elapse(elapsed_time) <= 0 }
  40. end
  41. 30 class Timer
  42. 30 def initialize(interval, callback)
  43. 43071 @interval = interval
  44. 43071 @callback = callback
  45. end
  46. 30 def cancel
  47. 62825 @interval.delete(@callback)
  48. end
  49. end
  50. 30 class Interval
  51. 30 include Comparable
  52. 30 attr_reader :interval
  53. 30 def initialize(interval)
  54. 11467 @interval = interval
  55. 11467 @callbacks = []
  56. end
  57. 30 def <=>(other)
  58. 1098 @interval <=> other.interval
  59. end
  60. 30 def ==(other)
  61. return @interval == other if other.is_a?(Numeric)
  62. @interval == other.to_f # rubocop:disable Lint/FloatComparison
  63. end
  64. 30 def to_f
  65. Float(@interval)
  66. end
  67. 30 def <<(callback)
  68. 43071 @callbacks << callback
  69. end
  70. 30 def delete(callback)
  71. 62825 @callbacks.delete(callback)
  72. end
  73. 30 def no_callbacks?
  74. @callbacks.empty?
  75. end
  76. 30 def elapsed?(elapsed = 0)
  77. 13670 (@interval - elapsed) <= 0 || @callbacks.empty?
  78. end
  79. 30 def elapse(elapsed)
  80. # same as elapsing
  81. 13801 return 0 if @callbacks.empty?
  82. 4217 @interval -= elapsed
  83. 4548 if @interval <= 0
  84. 931 cb = @callbacks.dup
  85. 931 cb.each(&:call)
  86. end
  87. 4548 @interval
  88. end
  89. end
  90. 30 private_constant :Interval
  91. end
  92. end

lib/httpx/transcoder.rb

100.0% lines covered

50 relevant lines. 50 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 module HTTPX
  3. 30 module Transcoder
  4. 30 module_function
  5. 30 def normalize_keys(key, value, transcoder = self, &block)
  6. 2846 if value.respond_to?(:to_ary)
  7. 511 if value.empty?
  8. 144 block.call("#{key}[]")
  9. else
  10. 367 value.to_ary.each do |element|
  11. 590 transcoder.normalize_keys("#{key}[]", element, transcoder, &block)
  12. end
  13. end
  14. 2334 elsif value.respond_to?(:to_hash)
  15. 648 value.to_hash.each do |child_key, child_value|
  16. 648 transcoder.normalize_keys("#{key}[#{child_key}]", child_value, transcoder, &block)
  17. end
  18. else
  19. 1687 block.call(key.to_s, value)
  20. end
  21. end
  22. # based on https://github.com/rack/rack/blob/d15dd728440710cfc35ed155d66a98dc2c07ae42/lib/rack/query_parser.rb#L82
  23. 30 def normalize_query(params, name, v, depth)
  24. 207 raise Error, "params depth surpasses what's supported" if depth <= 0
  25. 207 name =~ /\A[\[\]]*([^\[\]]+)\]*/
  26. 207 k = Regexp.last_match(1) || ""
  27. 207 after = Regexp.last_match ? Regexp.last_match.post_match : ""
  28. 207 if k.empty?
  29. 18 return Array(v) if !v.empty? && name == "[]"
  30. 8 return
  31. end
  32. 168 case after
  33. when ""
  34. 56 params[k] = v
  35. when "["
  36. 8 params[name] = v
  37. when "[]"
  38. 18 params[k] ||= []
  39. 18 raise Error, "expected Array (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Array)
  40. 18 params[k] << v
  41. when /^\[\]\[([^\[\]]+)\]$/, /^\[\](.+)$/
  42. 36 child_key = Regexp.last_match(1)
  43. 36 params[k] ||= []
  44. 36 raise Error, "expected Array (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Array)
  45. 36 if params[k].last.is_a?(Hash) && !params_hash_has_key?(params[k].last, child_key)
  46. 9 normalize_query(params[k].last, child_key, v, depth - 1)
  47. else
  48. 27 params[k] << normalize_query({}, child_key, v, depth - 1)
  49. end
  50. else
  51. 63 params[k] ||= {}
  52. 63 raise Error, "expected Hash (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Hash)
  53. 56 params[k] = normalize_query(params[k], after, v, depth - 1)
  54. end
  55. 189 params
  56. end
  57. 30 def params_hash_has_key?(hash, key)
  58. 18 return false if key.include?("[]")
  59. 18 key.split(/[\[\]]+/).inject(hash) do |h, part|
  60. 18 next h if part == ""
  61. 18 return false unless h.is_a?(Hash) && h.key?(part)
  62. 9 h[part]
  63. end
  64. 9 true
  65. end
  66. end
  67. end
  68. 30 require "httpx/transcoder/body"
  69. 30 require "httpx/transcoder/form"
  70. 30 require "httpx/transcoder/json"
  71. 30 require "httpx/transcoder/chunker"
  72. 30 require "httpx/transcoder/deflate"
  73. 30 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. 30 require "delegate"
  3. 30 module HTTPX::Transcoder
  4. 30 module Body
  5. 30 class Error < HTTPX::Error; end
  6. 30 module_function
  7. 30 class Encoder < SimpleDelegator
  8. 30 def initialize(body)
  9. 1742 body = body.open(File::RDONLY, encoding: Encoding::BINARY) if Object.const_defined?(:Pathname) && body.is_a?(Pathname)
  10. 1742 @body = body
  11. 1742 super
  12. end
  13. 30 def bytesize
  14. 6730 if @body.respond_to?(:bytesize)
  15. 2877 @body.bytesize
  16. 3852 elsif @body.respond_to?(:to_ary)
  17. 1426 @body.sum(&:bytesize)
  18. 2426 elsif @body.respond_to?(:size)
  19. 1689 @body.size || Float::INFINITY
  20. 737 elsif @body.respond_to?(:length)
  21. 405 @body.length || Float::INFINITY
  22. 332 elsif @body.respond_to?(:each)
  23. 324 Float::INFINITY
  24. else
  25. 9 raise Error, "cannot determine size of body: #{@body.inspect}"
  26. end
  27. end
  28. 30 def content_type
  29. 1627 "application/octet-stream"
  30. end
  31. end
  32. 30 def encode(body)
  33. 1742 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. 30 require "forwardable"
  3. 30 module HTTPX::Transcoder
  4. 30 module Chunker
  5. 30 class Error < HTTPX::Error; end
  6. 30 CRLF = "\r\n".b
  7. 30 class Encoder
  8. 30 extend Forwardable
  9. 30 def initialize(body)
  10. 108 @raw = body
  11. end
  12. 30 def each
  13. 108 return enum_for(__method__) unless block_given?
  14. 108 @raw.each do |chunk|
  15. 504 yield "#{chunk.bytesize.to_s(16)}#{CRLF}#{chunk}#{CRLF}"
  16. end
  17. 108 yield "0#{CRLF}"
  18. end
  19. 30 def respond_to_missing?(meth, *args)
  20. 120 @raw.respond_to?(meth, *args) || super
  21. end
  22. end
  23. 30 class Decoder
  24. 30 extend Forwardable
  25. 30 def_delegator :@buffer, :empty?
  26. 30 def_delegator :@buffer, :<<
  27. 30 def_delegator :@buffer, :clear
  28. 30 def initialize(buffer, trailers = false)
  29. 129 @buffer = buffer
  30. 129 @chunk_buffer = "".b
  31. 129 @finished = false
  32. 129 @state = :length
  33. 129 @trailers = trailers
  34. end
  35. 30 def to_s
  36. 120 @buffer
  37. end
  38. 30 def each
  39. 184 loop do
  40. 1155 case @state
  41. when :length
  42. 376 index = @buffer.index(CRLF)
  43. 376 return unless index && index.positive?
  44. # Read hex-length
  45. 376 hexlen = @buffer.byteslice(0, index)
  46. 376 @buffer = @buffer.byteslice(index..-1) || "".b
  47. 376 hexlen[/\h/] || raise(Error, "wrong chunk size line: #{hexlen}")
  48. 376 @chunk_length = hexlen.hex
  49. # check if is last chunk
  50. 376 @finished = @chunk_length.zero?
  51. 376 nextstate(:crlf)
  52. when :crlf
  53. 623 crlf_size = @finished && !@trailers ? 4 : 2
  54. # consume CRLF
  55. 623 return if @buffer.bytesize < crlf_size
  56. 623 raise Error, "wrong chunked encoding format" unless @buffer.start_with?(CRLF * (crlf_size / 2))
  57. 623 @buffer = @buffer.byteslice(crlf_size..-1)
  58. 623 if @chunk_length.nil?
  59. 247 nextstate(:length)
  60. else
  61. 376 return if @finished
  62. 256 nextstate(:data)
  63. end
  64. when :data
  65. 297 chunk = @buffer.byteslice(0, @chunk_length)
  66. 297 @buffer = @buffer.byteslice(@chunk_length..-1) || "".b
  67. 297 @chunk_buffer << chunk
  68. 265 @chunk_length -= chunk.bytesize
  69. 297 if @chunk_length.zero?
  70. 256 yield @chunk_buffer unless @chunk_buffer.empty?
  71. 247 @chunk_buffer.clear
  72. 247 @chunk_length = nil
  73. 247 nextstate(:crlf)
  74. end
  75. end
  76. 1167 break if @buffer.empty?
  77. end
  78. end
  79. 30 def finished?
  80. 175 @finished
  81. end
  82. 30 private
  83. 30 def nextstate(state)
  84. 1126 @state = state
  85. end
  86. end
  87. 30 module_function
  88. 30 def encode(chunks)
  89. 108 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. 30 require "zlib"
  3. 30 require_relative "utils/deflater"
  4. 30 module HTTPX
  5. 30 module Transcoder
  6. 30 module Deflate
  7. 30 class Deflater < Transcoder::Deflater
  8. 30 def deflate(chunk)
  9. 78 @deflater ||= Zlib::Deflate.new
  10. 78 unless chunk.nil?
  11. 27 chunk = @deflater.deflate(chunk)
  12. # deflate call may return nil, while still
  13. # retaining the last chunk in the deflater.
  14. 27 return chunk unless chunk.empty?
  15. end
  16. 54 return if @deflater.closed?
  17. 27 last = @deflater.finish
  18. 27 @deflater.close
  19. 27 last unless last.empty?
  20. end
  21. end
  22. 30 module_function
  23. 30 def encode(body)
  24. 27 Deflater.new(body)
  25. end
  26. 30 def decode(response, bytesize: nil)
  27. 18 bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
  28. 18 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. 30 require "forwardable"
  3. 30 require "uri"
  4. 30 require_relative "multipart"
  5. 30 module HTTPX
  6. 30 module Transcoder
  7. 30 module Form
  8. 30 module_function
  9. 30 PARAM_DEPTH_LIMIT = 32
  10. 30 class Encoder
  11. 30 extend Forwardable
  12. 30 def_delegator :@raw, :to_s
  13. 30 def_delegator :@raw, :to_str
  14. 30 def_delegator :@raw, :bytesize
  15. 30 def_delegator :@raw, :==
  16. 30 def initialize(form)
  17. 852 @raw = form.each_with_object("".b) do |(key, val), buf|
  18. 1464 HTTPX::Transcoder.normalize_keys(key, val) do |k, v|
  19. 1687 buf << "&" unless buf.empty?
  20. 1687 buf << URI.encode_www_form_component(k)
  21. 1687 buf << "=#{URI.encode_www_form_component(v.to_s)}" unless v.nil?
  22. end
  23. end
  24. end
  25. 30 def content_type
  26. 662 "application/x-www-form-urlencoded"
  27. end
  28. end
  29. 30 module Decoder
  30. 30 module_function
  31. 30 def call(response, *)
  32. 45 URI.decode_www_form(response.to_s).each_with_object({}) do |(field, value), params|
  33. 108 HTTPX::Transcoder.normalize_query(params, field, value, PARAM_DEPTH_LIMIT)
  34. end
  35. end
  36. end
  37. 30 def encode(form)
  38. 852 Encoder.new(form)
  39. end
  40. 30 def decode(response)
  41. 72 content_type = response.content_type.mime_type
  42. 64 case content_type
  43. when "application/x-www-form-urlencoded"
  44. 45 Decoder
  45. when "multipart/form-data"
  46. 18 Multipart::Decoder.new(response)
  47. else
  48. 9 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

44 relevant lines. 44 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "zlib"
  3. 30 module HTTPX
  4. 30 module Transcoder
  5. 30 module GZIP
  6. 30 class Deflater < Transcoder::Deflater
  7. 30 def initialize(body)
  8. 55 @compressed_chunk = "".b
  9. 55 @deflater = nil
  10. 55 super
  11. end
  12. 30 def deflate(chunk)
  13. 110 @deflater ||= Zlib::GzipWriter.new(self)
  14. 110 if chunk.nil?
  15. 55 unless @deflater.closed?
  16. 55 @deflater.flush
  17. 55 @deflater.close
  18. 55 compressed_chunk
  19. end
  20. else
  21. 55 @deflater.write(chunk)
  22. 55 compressed_chunk
  23. end
  24. end
  25. 30 private
  26. 30 def write(*chunks)
  27. 165 chunks.sum do |chunk|
  28. 165 chunk = chunk.to_s
  29. 165 @compressed_chunk << chunk
  30. 165 chunk.bytesize
  31. end
  32. end
  33. 30 def compressed_chunk
  34. 110 @compressed_chunk.dup
  35. ensure
  36. 110 @compressed_chunk.clear
  37. end
  38. end
  39. 30 class Inflater
  40. 30 def initialize(bytesize)
  41. 206 @inflater = Zlib::Inflate.new(Zlib::MAX_WBITS + 32)
  42. 206 @bytesize = bytesize
  43. end
  44. 30 def call(chunk)
  45. 695 buffer = @inflater.inflate(chunk)
  46. 643 @bytesize -= chunk.bytesize
  47. 695 if @bytesize <= 0
  48. 134 buffer << @inflater.finish
  49. 134 @inflater.close
  50. end
  51. 695 buffer
  52. end
  53. end
  54. 30 module_function
  55. 30 def encode(body)
  56. 55 Deflater.new(body)
  57. end
  58. 30 def decode(response, bytesize: nil)
  59. 188 bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
  60. 188 Inflater.new(bytesize)
  61. end
  62. end
  63. end
  64. 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. 30 require "forwardable"
  3. 30 module HTTPX::Transcoder
  4. 30 module JSON
  5. 30 module_function
  6. 30 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. 30 class Encoder
  20. 30 extend Forwardable
  21. 30 def_delegator :@raw, :to_s
  22. 30 def_delegator :@raw, :bytesize
  23. 30 def_delegator :@raw, :==
  24. 30 def initialize(json)
  25. 102 @raw = JSON.json_dump(json)
  26. 102 @charset = @raw.encoding.name.downcase
  27. end
  28. 30 def content_type
  29. 102 "application/json; charset=#{@charset}"
  30. end
  31. end
  32. 30 def encode(json)
  33. 102 Encoder.new(json)
  34. end
  35. 30 def decode(response)
  36. 216 content_type = response.content_type.mime_type
  37. 216 raise HTTPX::Error, "invalid json mime type (#{content_type})" unless JSON_REGEX.match?(content_type)
  38. 198 method(:json_load)
  39. end
  40. # rubocop:disable Style/SingleLineMethods
  41. 30 if defined?(MultiJson)
  42. 5 def json_load(*args); MultiJson.load(*args); end
  43. 3 def json_dump(*args); MultiJson.dump(*args); end
  44. 27 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. 25 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. 25 require "json"
  52. 193 def json_load(*args); ::JSON.parse(*args); end
  53. 113 def json_dump(*args); ::JSON.generate(*args); end
  54. end
  55. # rubocop:enable Style/SingleLineMethods
  56. end
  57. end

lib/httpx/transcoder/multipart.rb

100.0% lines covered

22 relevant lines. 22 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require_relative "multipart/encoder"
  3. 30 require_relative "multipart/decoder"
  4. 30 require_relative "multipart/part"
  5. 30 require_relative "multipart/mime_type_detector"
  6. 30 module HTTPX::Transcoder
  7. 30 module Multipart
  8. 30 module_function
  9. 30 def multipart?(form_data)
  10. 1804 form_data.any? do |_, v|
  11. 2344 multipart_value?(v) ||
  12. 2210 (v.respond_to?(:to_ary) && v.to_ary.any? { |av| multipart_value?(av) }) ||
  13. 2210 (v.respond_to?(:to_hash) && v.to_hash.any? { |_, e| multipart_value?(e) })
  14. end
  15. end
  16. 30 def multipart_value?(value)
  17. 5343 value.respond_to?(:read) ||
  18. 3798 (value.is_a?(Hash) &&
  19. value.key?(:body) &&
  20. 868 (value.key?(:filename) || value.key?(:content_type)))
  21. end
  22. 30 def normalize_keys(key, value, transcoder = self, &block)
  23. 1991 if multipart_value?(value)
  24. 1271 block.call(key.to_s, value)
  25. else
  26. 720 HTTPX::Transcoder.normalize_keys(key, value, transcoder, &block)
  27. end
  28. end
  29. 30 def encode(form_data)
  30. 1142 Encoder.new(form_data)
  31. end
  32. end
  33. end

lib/httpx/transcoder/multipart/decoder.rb

94.05% lines covered

84 relevant lines. 79 lines covered and 5 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "tempfile"
  3. 30 require "delegate"
  4. 30 module HTTPX
  5. 30 module Transcoder
  6. 30 module Multipart
  7. 30 class FilePart < SimpleDelegator
  8. 30 attr_reader :original_filename, :content_type
  9. 30 def initialize(filename, content_type)
  10. 36 @original_filename = filename
  11. 36 @content_type = content_type
  12. 36 @file = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
  13. 36 super(@file)
  14. end
  15. end
  16. 30 class Decoder
  17. 30 include HTTPX::Utils
  18. 30 CRLF = "\r\n"
  19. 30 BOUNDARY_RE = /;\s*boundary=([^;]+)/i.freeze
  20. 30 MULTIPART_CONTENT_TYPE = /Content-Type: (.*)#{CRLF}/ni.freeze
  21. 30 MULTIPART_CONTENT_DISPOSITION = /Content-Disposition:.*;\s*name=(#{VALUE})/ni.freeze
  22. 30 MULTIPART_CONTENT_ID = /Content-ID:\s*([^#{CRLF}]*)/ni.freeze
  23. 30 WINDOW_SIZE = 2 << 14
  24. 30 def initialize(response)
  25. 2 @boundary = begin
  26. 18 m = response.headers["content-type"].to_s[BOUNDARY_RE, 1]
  27. 18 raise Error, "no boundary declared in content-type header" unless m
  28. 18 m.strip
  29. end
  30. 18 @buffer = "".b
  31. 18 @parts = {}
  32. 18 @intermediate_boundary = "--#{@boundary}"
  33. 18 @state = :idle
  34. 18 @current = nil
  35. end
  36. 30 def call(response, *)
  37. 18 response.body.each do |chunk|
  38. 18 @buffer << chunk
  39. 18 parse
  40. end
  41. 18 raise Error, "invalid or unsupported multipart format" unless @buffer.empty?
  42. 18 @parts
  43. end
  44. 30 private
  45. 30 def parse
  46. 16 case @state
  47. when :idle
  48. 18 raise Error, "payload does not start with boundary" unless @buffer.start_with?("#{@intermediate_boundary}#{CRLF}")
  49. 18 @buffer = @buffer.byteslice((@intermediate_boundary.bytesize + 2)..-1)
  50. 18 @state = :part_header
  51. when :part_header
  52. 54 idx = @buffer.index("#{CRLF}#{CRLF}")
  53. # raise Error, "couldn't parse part headers" unless idx
  54. 54 return unless idx
  55. # @type var head: String
  56. 54 head = @buffer.byteslice(0..(idx + 4 - 1))
  57. 54 @buffer = @buffer.byteslice(head.bytesize..-1)
  58. 54 content_type = head[MULTIPART_CONTENT_TYPE, 1] || "text/plain"
  59. 96 if (name = head[MULTIPART_CONTENT_DISPOSITION, 1])
  60. 54 name = /\A"(.*)"\Z/ =~ name ? Regexp.last_match(1) : name.dup
  61. 54 name.gsub!(/\\(.)/, "\\1")
  62. 12 name
  63. else
  64. name = head[MULTIPART_CONTENT_ID, 1]
  65. end
  66. 54 filename = HTTPX::Utils.get_filename(head)
  67. 54 name = filename || +"#{content_type}[]" if name.nil? || name.empty?
  68. 54 @current = name
  69. 48 @parts[name] = if filename
  70. 36 FilePart.new(filename, content_type)
  71. else
  72. 18 "".b
  73. end
  74. 54 @state = :part_body
  75. when :part_body
  76. 54 part = @parts[@current]
  77. 54 body_separator = if part.is_a?(FilePart)
  78. 32 "#{CRLF}#{CRLF}"
  79. else
  80. 18 CRLF
  81. end
  82. 54 idx = @buffer.index(body_separator)
  83. 54 if idx
  84. 54 payload = @buffer.byteslice(0..(idx - 1))
  85. 54 @buffer = @buffer.byteslice((idx + body_separator.bytesize)..-1)
  86. 54 part << payload
  87. 54 part.rewind if part.respond_to?(:rewind)
  88. 54 @state = :parse_boundary
  89. else
  90. part << @buffer
  91. @buffer.clear
  92. end
  93. when :parse_boundary
  94. 54 raise Error, "payload does not start with boundary" unless @buffer.start_with?(@intermediate_boundary)
  95. 54 @buffer = @buffer.byteslice(@intermediate_boundary.bytesize..-1)
  96. 54 if @buffer == "--"
  97. 18 @buffer.clear
  98. 18 @state = :done
  99. 18 return
  100. 35 elsif @buffer.start_with?(CRLF)
  101. 36 @buffer = @buffer.byteslice(2..-1)
  102. 36 @state = :part_header
  103. else
  104. return
  105. end
  106. when :done
  107. raise Error, "parsing should have been over by now"
  108. 20 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. 30 module HTTPX
  3. 30 module Transcoder::Multipart
  4. 30 class Encoder
  5. 30 attr_reader :bytesize
  6. 30 def initialize(form)
  7. 1142 @boundary = ("-" * 21) << SecureRandom.hex(21)
  8. 1142 @part_index = 0
  9. 1142 @buffer = "".b
  10. 1142 @form = form
  11. 1142 @bytesize = 0
  12. 1142 @parts = to_parts(form)
  13. end
  14. 30 def content_type
  15. 1142 "multipart/form-data; boundary=#{@boundary}"
  16. end
  17. 30 def to_s
  18. 21 read || ""
  19. ensure
  20. 21 rewind
  21. end
  22. 30 def read(length = nil, outbuf = nil)
  23. 4245 data = String(outbuf).clear.force_encoding(Encoding::BINARY) if outbuf
  24. 4245 data ||= "".b
  25. 4245 read_chunks(data, length)
  26. 4245 data unless length && data.empty?
  27. end
  28. 30 def rewind
  29. 57 form = @form.each_with_object([]) do |(key, val), aux|
  30. 57 if val.respond_to?(:path) && val.respond_to?(:reopen) && val.respond_to?(:closed?) && val.closed?
  31. # @type var val: File
  32. 57 val = val.reopen(val.path, File::RDONLY)
  33. end
  34. 57 val.rewind if val.respond_to?(:rewind)
  35. 57 aux << [key, val]
  36. end
  37. 57 @form = form
  38. 57 @bytesize = 0
  39. 57 @parts = to_parts(form)
  40. 57 @part_index = 0
  41. end
  42. 30 private
  43. 30 def to_parts(form)
  44. 1199 params = form.each_with_object([]) do |(key, val), aux|
  45. 1415 Transcoder::Multipart.normalize_keys(key, val) do |k, v|
  46. 1415 next if v.nil?
  47. 1415 value, content_type, filename = Part.call(v)
  48. 1415 header = header_part(k, content_type, filename)
  49. 1263 @bytesize += header.size
  50. 1415 aux << header
  51. 1263 @bytesize += value.size
  52. 1415 aux << value
  53. 1415 delimiter = StringIO.new("\r\n")
  54. 1263 @bytesize += delimiter.size
  55. 1415 aux << delimiter
  56. end
  57. end
  58. 1199 final_delimiter = StringIO.new("--#{@boundary}--\r\n")
  59. 1071 @bytesize += final_delimiter.size
  60. 1199 params << final_delimiter
  61. 1199 params
  62. end
  63. 30 def header_part(key, content_type, filename)
  64. 1415 header = "--#{@boundary}\r\n".b
  65. 1415 header << "Content-Disposition: form-data; name=#{key.inspect}".b
  66. 1415 header << "; filename=#{filename.inspect}" if filename
  67. 1415 header << "\r\nContent-Type: #{content_type}\r\n\r\n"
  68. 1415 StringIO.new(header)
  69. end
  70. 30 def read_chunks(buffer, length = nil)
  71. 5409 while @part_index < @parts.size
  72. 12629 chunk = read_from_part(length)
  73. 12629 next unless chunk
  74. 7241 buffer << chunk.force_encoding(Encoding::BINARY)
  75. 7241 next unless length
  76. 6376 length -= chunk.bytesize
  77. 7164 break if length.zero?
  78. end
  79. end
  80. # if there's a current part to read from, tries to read a chunk.
  81. 30 def read_from_part(max_length = nil)
  82. 12629 part = @parts[@part_index]
  83. 12629 chunk = part.read(max_length, @buffer)
  84. 12629 return chunk if chunk && !chunk.empty?
  85. 5388 part.close if part.respond_to?(:close)
  86. 4804 @part_index += 1
  87. 2388 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. 30 module HTTPX
  3. 30 module Transcoder::Multipart
  4. 30 module MimeTypeDetector
  5. 30 module_function
  6. 30 DEFAULT_MIMETYPE = "application/octet-stream"
  7. # inspired by https://github.com/shrinerb/shrine/blob/master/lib/shrine/plugins/determine_mime_type.rb
  8. 30 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. 28 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. 27 elsif defined?(MimeMagic)
  24. 1 def call(file, _)
  25. 1 mime = MimeMagic.by_magic(file)
  26. 1 mime.type if mime
  27. end
  28. 26 elsif system("which file", out: File::NULL)
  29. 27 require "open3"
  30. 27 def call(file, _)
  31. 835 return if file.eof? # file command returns "application/x-empty" for empty files
  32. 785 Open3.popen3(*%w[file --mime-type --brief -]) do |stdin, stdout, stderr, thread|
  33. 83 begin
  34. 785 IO.copy_stream(file, stdin.binmode)
  35. rescue Errno::EPIPE
  36. end
  37. 785 file.rewind
  38. 785 stdin.close
  39. 785 status = thread.value
  40. # call to file command failed
  41. 785 if status.nil? || !status.success?
  42. $stderr.print(stderr.read)
  43. else
  44. 785 output = stdout.read.strip
  45. 785 if output.include?("cannot open")
  46. $stderr.print(output)
  47. else
  48. 785 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. 30 module HTTPX
  3. 30 module Transcoder::Multipart
  4. 30 module Part
  5. 30 module_function
  6. 30 def call(value)
  7. # take out specialized objects of the way
  8. 1415 if value.respond_to?(:filename) && value.respond_to?(:content_type) && value.respond_to?(:read)
  9. 128 return value, value.content_type, value.filename
  10. end
  11. 1271 content_type = filename = nil
  12. 1271 if value.is_a?(Hash)
  13. 434 content_type = value[:content_type]
  14. 434 filename = value[:filename]
  15. 434 value = value[:body]
  16. end
  17. 1271 value = value.open(File::RDONLY, encoding: Encoding::BINARY) if Object.const_defined?(:Pathname) && value.is_a?(Pathname)
  18. 1271 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. 839 filename ||= File.basename(value.path)
  21. 839 content_type ||= MimeTypeDetector.call(value, filename) || "application/octet-stream"
  22. 839 [value, content_type, filename]
  23. else
  24. 432 [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. 30 require "stringio"
  3. 30 module HTTPX
  4. 30 module Transcoder
  5. 30 class BodyReader
  6. 30 def initialize(body)
  7. 243 @body = if body.respond_to?(:read)
  8. 23 body.rewind if body.respond_to?(:rewind)
  9. 23 body
  10. 219 elsif body.respond_to?(:each)
  11. 42 body.enum_for(:each)
  12. else
  13. 178 StringIO.new(body.to_s)
  14. end
  15. end
  16. 30 def bytesize
  17. 525 return @body.bytesize if @body.respond_to?(:bytesize)
  18. 483 Float::INFINITY
  19. end
  20. 30 def read(length = nil, outbuf = nil)
  21. 538 return @body.read(length, outbuf) if @body.respond_to?(:read)
  22. begin
  23. 112 chunk = @body.next
  24. 56 if outbuf
  25. outbuf.replace(chunk)
  26. else
  27. 56 outbuf = chunk
  28. end
  29. 56 outbuf unless length && outbuf.empty?
  30. 32 rescue StopIteration
  31. end
  32. end
  33. 30 def close
  34. 55 @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. 30 require_relative "body_reader"
  3. 30 module HTTPX
  4. 30 module Transcoder
  5. 30 class Deflater
  6. 30 attr_reader :content_type
  7. 30 def initialize(body)
  8. 96 @content_type = body.content_type
  9. 96 @body = BodyReader.new(body)
  10. 96 @closed = false
  11. end
  12. 30 def bytesize
  13. 370 buffer_deflate!
  14. 370 @buffer.size
  15. end
  16. 30 def read(length = nil, outbuf = nil)
  17. 472 return @buffer.read(length, outbuf) if @buffer
  18. 271 return if @closed
  19. 216 chunk = @body.read(length)
  20. 216 compressed_chunk = deflate(chunk)
  21. 216 return unless compressed_chunk
  22. 175 if outbuf
  23. 166 outbuf.replace(compressed_chunk)
  24. else
  25. 9 compressed_chunk
  26. end
  27. end
  28. 30 def close
  29. 55 return if @closed
  30. 55 @buffer.close if @buffer
  31. 55 @body.close
  32. 55 @closed = true
  33. end
  34. 30 def rewind
  35. 32 return unless @buffer
  36. 18 @buffer.rewind
  37. end
  38. 30 private
  39. # rubocop:disable Naming/MemoizedInstanceVariableName
  40. 30 def buffer_deflate!
  41. 370 return @buffer if defined?(@buffer)
  42. 96 buffer = Response::Buffer.new(
  43. threshold_size: Options::MAX_BODY_THRESHOLD_SIZE
  44. )
  45. 96 IO.copy_stream(self, buffer)
  46. 96 buffer.rewind if buffer.respond_to?(:rewind)
  47. 96 @buffer = buffer
  48. end
  49. # rubocop:enable Naming/MemoizedInstanceVariableName
  50. end
  51. end
  52. end

lib/httpx/utils.rb

100.0% lines covered

44 relevant lines. 44 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 module HTTPX
  3. 30 module Utils
  4. 30 using URIExtensions
  5. 30 TOKEN = %r{[^\s()<>,;:\\"/\[\]?=]+}.freeze
  6. 30 VALUE = /"(?:\\"|[^"])*"|#{TOKEN}/.freeze
  7. 30 FILENAME_REGEX = /\s*filename=(#{VALUE})/.freeze
  8. 30 FILENAME_EXTENSION_REGEX = /\s*filename\*=(#{VALUE})/.freeze
  9. 30 module_function
  10. 30 def now
  11. 44753 Process.clock_gettime(Process::CLOCK_MONOTONIC)
  12. end
  13. 30 def elapsed_time(monotonic_timestamp)
  14. 13043 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. 30 def parse_retry_after(retry_after)
  19. # first: bet on it being an integer
  20. 72 Integer(retry_after)
  21. rescue ArgumentError
  22. # Then it's a datetime
  23. 18 time = Time.httpdate(retry_after)
  24. 18 time - Time.now
  25. end
  26. 30 def get_filename(header, _prefix_regex = nil)
  27. 99 filename = nil
  28. 88 case header
  29. when FILENAME_REGEX
  30. 63 filename = Regexp.last_match(1)
  31. 63 filename = Regexp.last_match(1) if filename =~ /^"(.*)"$/
  32. when FILENAME_EXTENSION_REGEX
  33. 18 filename = Regexp.last_match(1)
  34. 18 encoding, _, filename = filename.split("'", 3)
  35. end
  36. 99 return unless filename
  37. 153 filename = URI::DEFAULT_PARSER.unescape(filename) if filename.scan(/%.?.?/).all? { |s| /%[0-9a-fA-F]{2}/.match?(s) }
  38. 81 filename.scrub!
  39. 81 filename = filename.gsub(/\\(.)/, '\1') unless /\\[^\\"]/.match?(filename)
  40. 81 filename.force_encoding ::Encoding.find(encoding) if encoding
  41. 81 filename
  42. end
  43. 30 URIParser = URI::RFC2396_Parser.new
  44. 30 def to_uri(uri)
  45. 21905 return URI(uri) unless uri.is_a?(String) && !uri.ascii_only?
  46. 37 uri = URI(URIParser.escape(uri))
  47. 37 non_ascii_hostname = URIParser.unescape(uri.host)
  48. 37 non_ascii_hostname.force_encoding(Encoding::UTF_8)
  49. 37 idna_hostname = Punycode.encode_hostname(non_ascii_hostname)
  50. 37 uri.host = idna_hostname
  51. 36 uri.non_ascii_hostname = non_ascii_hostname
  52. 36 uri
  53. end
  54. 30 if defined?(Ractor) &&
  55. # no ractor support for 3.0
  56. RUBY_VERSION >= "3.1.0"
  57. 24 def in_ractor?
  58. 15035 Ractor.main != Ractor.current
  59. end
  60. else
  61. 6 def in_ractor?
  62. 10714 false
  63. end
  64. end
  65. end
  66. end