loading
Generated 2026-03-21T08:48:04+00:00

All Files ( 96.47% covered at 3877.45 hits/line )

111 files in total.
8624 relevant lines, 8320 lines covered and 304 lines missed. ( 96.47% )
File % covered Lines Relevant Lines Lines covered Lines missed Avg. Hits / Line
lib/httpx.rb 100.00 % 66 39 39 0 1475.21
lib/httpx/adapters/datadog.rb 85.81 % 319 155 133 22 36.12
lib/httpx/adapters/faraday.rb 98.77 % 303 163 161 2 153.13
lib/httpx/adapters/sentry.rb 100.00 % 121 62 62 0 113.16
lib/httpx/adapters/webmock.rb 98.95 % 183 95 94 1 140.55
lib/httpx/altsvc.rb 96.43 % 165 84 81 3 302.93
lib/httpx/buffer.rb 100.00 % 61 27 27 0 6522.11
lib/httpx/callbacks.rb 100.00 % 35 19 19 0 174710.32
lib/httpx/chainable.rb 95.65 % 106 46 44 2 1408.46
lib/httpx/connection.rb 94.99 % 1017 499 474 25 8868.77
lib/httpx/connection/http1.rb 89.78 % 404 225 202 23 4677.61
lib/httpx/connection/http2.rb 93.48 % 482 276 258 18 5064.15
lib/httpx/domain_name.rb 95.56 % 145 45 43 2 277.76
lib/httpx/errors.rb 97.67 % 111 43 42 1 134.77
lib/httpx/extensions.rb 95.24 % 45 21 20 1 645.24
lib/httpx/headers.rb 100.00 % 176 71 71 0 20009.72
lib/httpx/io.rb 100.00 % 11 5 5 0 30.00
lib/httpx/io/ssl.rb 97.67 % 163 86 84 2 3114.37
lib/httpx/io/tcp.rb 93.70 % 239 127 119 8 8562.90
lib/httpx/io/udp.rb 100.00 % 62 35 35 0 446.09
lib/httpx/io/unix.rb 97.14 % 71 35 34 1 23.60
lib/httpx/loggable.rb 100.00 % 68 29 29 0 55415.93
lib/httpx/options.rb 96.27 % 579 241 232 9 26035.45
lib/httpx/parser/http1.rb 100.00 % 187 110 110 0 9323.65
lib/httpx/plugins/auth.rb 100.00 % 153 72 72 0 323.75
lib/httpx/plugins/auth/basic.rb 100.00 % 20 10 10 0 113.50
lib/httpx/plugins/auth/digest.rb 98.80 % 143 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 % 78 41 41 0 14.56
lib/httpx/plugins/callbacks.rb 92.65 % 141 68 63 5 140.63
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.84
lib/httpx/plugins/cookies.rb 100.00 % 111 54 54 0 143.35
lib/httpx/plugins/cookies/cookie.rb 97.67 % 198 86 84 2 341.58
lib/httpx/plugins/cookies/jar.rb 100.00 % 170 73 73 0 296.19
lib/httpx/plugins/cookies/set_cookie_parser.rb 100.00 % 143 72 72 0 176.40
lib/httpx/plugins/digest_auth.rb 100.00 % 66 30 30 0 114.60
lib/httpx/plugins/expect.rb 100.00 % 150 71 71 0 81.87
lib/httpx/plugins/fiber_concurrency.rb 92.93 % 208 99 92 7 840.79
lib/httpx/plugins/follow_redirects.rb 100.00 % 239 110 110 0 267.10
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 91.04 % 282 134 122 12 85.22
lib/httpx/plugins/persistent.rb 100.00 % 80 30 30 0 501.97
lib/httpx/plugins/proxy.rb 94.86 % 359 175 166 9 384.19
lib/httpx/plugins/proxy/http.rb 94.87 % 215 117 111 6 163.22
lib/httpx/plugins/proxy/socks4.rb 97.47 % 135 79 77 2 213.41
lib/httpx/plugins/proxy/socks5.rb 99.12 % 194 113 112 1 347.93
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 % 60 21 21 0 41.57
lib/httpx/plugins/response_cache.rb 100.00 % 340 148 148 0 224.51
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.44 % 274 117 114 3 618.63
lib/httpx/plugins/ssrf_filter.rb 100.00 % 146 62 62 0 138.95
lib/httpx/plugins/stream.rb 97.32 % 234 112 109 3 182.95
lib/httpx/plugins/stream_bidi.rb 93.99 % 408 183 172 11 275.98
lib/httpx/plugins/tracing.rb 89.47 % 137 57 51 6 102.37
lib/httpx/plugins/upgrade.rb 100.00 % 86 38 38 0 57.18
lib/httpx/plugins/upgrade/h2.rb 89.66 % 64 29 26 3 41.90
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 5525.07
lib/httpx/punycode.rb 100.00 % 22 9 9 0 20.89
lib/httpx/request.rb 100.00 % 327 138 138 0 8109.64
lib/httpx/request/body.rb 100.00 % 158 68 68 0 3853.00
lib/httpx/resolver.rb 93.22 % 111 59 55 4 584.75
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 3304.87
lib/httpx/resolver/cache/memory.rb 100.00 % 42 22 22 0 3266.82
lib/httpx/resolver/entry.rb 100.00 % 30 16 16 0 5370.63
lib/httpx/resolver/https.rb 84.49 % 326 187 158 29 62.35
lib/httpx/resolver/multi.rb 100.00 % 84 45 45 0 6175.04
lib/httpx/resolver/native.rb 92.22 % 581 334 308 26 861.06
lib/httpx/resolver/resolver.rb 95.10 % 209 102 97 5 1615.82
lib/httpx/resolver/system.rb 95.45 % 281 154 147 7 113.43
lib/httpx/response.rb 100.00 % 320 124 124 0 2861.73
lib/httpx/response/body.rb 100.00 % 244 109 109 0 3475.64
lib/httpx/response/buffer.rb 96.72 % 115 61 59 2 1982.51
lib/httpx/selector.rb 92.36 % 308 144 133 11 8936.91
lib/httpx/session.rb 98.97 % 588 292 289 3 13147.09
lib/httpx/session_extensions.rb 100.00 % 30 15 15 0 6.87
lib/httpx/timers.rb 93.94 % 131 66 62 4 13855.52
lib/httpx/transcoder.rb 100.00 % 89 50 50 0 242.52
lib/httpx/transcoder/body.rb 100.00 % 43 26 26 0 1151.00
lib/httpx/transcoder/chunker.rb 100.00 % 115 66 66 0 242.42
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.51
lib/httpx/transcoder/gzip.rb 100.00 % 76 44 44 0 121.09
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.63
lib/httpx/transcoder/utils/deflater.rb 100.00 % 74 36 36 0 118.86
lib/httpx/utils.rb 100.00 % 88 44 44 0 2496.95

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. 10783 h = @plugins
  19. 10783 m = @plugins_mutex
  20. 21566 unless (plugin = m.synchronize { h[name] })
  21. 348 require "httpx/plugins/#{name}"
  22. 696 raise "Plugin #{name} hasn't been registered" unless (plugin = m.synchronize { h[name] })
  23. end
  24. 10783 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. 427 h = @plugins
  30. 427 m = @plugins_mutex
  31. 820 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

85.81% lines covered

155 relevant lines. 133 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. 7 def enabled?(request)
  39. 269 configuration(request).enabled
  40. end
  41. 7 def start(request)
  42. 112 request.datadog_span = initialize_span(request, request.init_time)
  43. end
  44. 7 def reset(request)
  45. 21 request.datadog_span = nil
  46. end
  47. 7 def finish(request, response)
  48. 112 request.datadog_span ||= initialize_span(request, request.init_time) if request.init_time
  49. 112 finish_span(response, request.datadog_span)
  50. end
  51. 7 def finish_span(response, span)
  52. 112 if response.is_a?(::HTTPX::ErrorResponse)
  53. 7 span.set_error(response.error)
  54. else
  55. 105 span.set_tag(TAG_STATUS_CODE, response.status.to_s)
  56. 105 span.set_error(::HTTPX::HTTPError.new(response)) if response.status.between?(400, 599)
  57. span.set_tags(
  58. Datadog.configuration.tracing.header_tags.response_tags(response.headers.to_h)
  59. 105 ) if Datadog.configuration.tracing.respond_to?(:header_tags)
  60. end
  61. 112 span.finish
  62. end
  63. # return a span initialized with the +@request+ state.
  64. 7 def initialize_span(request, start_time)
  65. 119 verb = request.verb
  66. 119 uri = request.uri
  67. 119 config = configuration(request)
  68. 119 span = create_span(request, config, start_time)
  69. 119 span.resource = verb
  70. # Tag original global service name if not used
  71. 119 span.set_tag(TAG_BASE_SERVICE, Datadog.configuration.service) if span.service != Datadog.configuration.service
  72. 119 span.set_tag(TAG_KIND, TAG_CLIENT)
  73. 119 span.set_tag(TAG_COMPONENT, "httpx")
  74. 119 span.set_tag(TAG_OPERATION, "request")
  75. 119 span.set_tag(TAG_URL, request.path)
  76. 119 span.set_tag(TAG_METHOD, verb)
  77. 119 span.set_tag(TAG_TARGET_HOST, uri.host)
  78. 119 span.set_tag(TAG_TARGET_PORT, uri.port)
  79. 119 span.set_tag(TAG_PEER_HOSTNAME, uri.host)
  80. # Tag as an external peer service
  81. # span.set_tag(TAG_PEER_SERVICE, span.service)
  82. 119 if config[:distributed_tracing]
  83. 112 propagate_trace_http(
  84. Datadog::Tracing.active_trace,
  85. request.headers
  86. )
  87. end
  88. # Set analytics sample rate
  89. 119 if Contrib::Analytics.enabled?(config[:analytics_enabled])
  90. 14 Contrib::Analytics.set_sample_rate(span, config[:analytics_sample_rate])
  91. end
  92. span.set_tags(
  93. Datadog.configuration.tracing.header_tags.request_tags(request.headers.to_h)
  94. 119 ) if Datadog.configuration.tracing.respond_to?(:header_tags)
  95. 119 span
  96. rescue StandardError => e
  97. Datadog.logger.error("error preparing span for http request: #{e}")
  98. Datadog.logger.error(e.backtrace)
  99. end
  100. 7 def configuration(request)
  101. 388 Datadog.configuration.tracing[:httpx, request.uri.host]
  102. end
  103. 7 if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("2.0.0")
  104. 4 def propagate_trace_http(trace, headers)
  105. 64 Datadog::Tracing::Contrib::HTTP.inject(trace, headers)
  106. end
  107. 4 def create_span(request, configuration, start_time)
  108. 68 Datadog::Tracing.trace(
  109. SPAN_REQUEST,
  110. service: service_name(request.uri.host, configuration),
  111. type: TYPE_OUTBOUND,
  112. start_time: start_time
  113. )
  114. end
  115. else
  116. 3 def propagate_trace_http(trace, headers)
  117. 48 Datadog::Tracing::Propagation::HTTP.inject!(trace.to_digest, headers)
  118. end
  119. 3 def create_span(request, configuration, start_time)
  120. 51 Datadog::Tracing.trace(
  121. SPAN_REQUEST,
  122. service: service_name(request.uri.host, configuration),
  123. span_type: TYPE_OUTBOUND,
  124. start_time: start_time
  125. )
  126. end
  127. end
  128. end
  129. 7 class << self
  130. 7 def load_dependencies(klass)
  131. 7 klass.plugin(:tracing)
  132. end
  133. 7 def extra_options(options)
  134. 7 options.merge(tracer: RequestTracer)
  135. end
  136. end
  137. 7 module RequestMethods
  138. 7 attr_accessor :datadog_span
  139. end
  140. end
  141. 7 module Configuration
  142. # Default settings for httpx
  143. #
  144. 7 class Settings < Datadog::Tracing::Contrib::Configuration::Settings
  145. 7 DEFAULT_ERROR_HANDLER = lambda do |response|
  146. Datadog::Ext::HTTP::ERROR_RANGE.cover?(response.status)
  147. end
  148. 7 option :service_name, default: "httpx"
  149. 7 option :distributed_tracing, default: true
  150. 7 option :split_by_domain, default: false
  151. 7 if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
  152. 7 option :enabled do |o|
  153. 7 o.type :bool
  154. 7 o.env "DD_TRACE_HTTPX_ENABLED"
  155. 7 o.default true
  156. end
  157. 7 option :analytics_enabled do |o|
  158. 7 o.type :bool
  159. 7 o.env "DD_TRACE_HTTPX_ANALYTICS_ENABLED"
  160. 7 o.default false
  161. end
  162. 7 option :analytics_sample_rate do |o|
  163. 7 o.type :float
  164. 7 o.env "DD_TRACE_HTTPX_ANALYTICS_SAMPLE_RATE"
  165. 7 o.default 1.0
  166. end
  167. else
  168. option :enabled do |o|
  169. o.default { env_to_bool("DD_TRACE_HTTPX_ENABLED", true) }
  170. o.lazy
  171. end
  172. option :analytics_enabled do |o|
  173. o.default { env_to_bool(%w[DD_TRACE_HTTPX_ANALYTICS_ENABLED DD_HTTPX_ANALYTICS_ENABLED], false) }
  174. o.lazy
  175. end
  176. option :analytics_sample_rate do |o|
  177. o.default { env_to_float(%w[DD_TRACE_HTTPX_ANALYTICS_SAMPLE_RATE DD_HTTPX_ANALYTICS_SAMPLE_RATE], 1.0) }
  178. o.lazy
  179. end
  180. end
  181. 7 if defined?(Datadog::Tracing::Contrib::SpanAttributeSchema)
  182. 7 option :service_name do |o|
  183. 7 o.default do
  184. 77 Datadog::Tracing::Contrib::SpanAttributeSchema.fetch_service_name(
  185. "DD_TRACE_HTTPX_SERVICE_NAME",
  186. "httpx"
  187. )
  188. end
  189. 7 o.lazy unless Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
  190. end
  191. else
  192. option :service_name do |o|
  193. o.default do
  194. ENV.fetch("DD_TRACE_HTTPX_SERVICE_NAME", "httpx")
  195. end
  196. o.lazy unless Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
  197. end
  198. end
  199. 7 option :distributed_tracing, default: true
  200. 7 if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.15.0")
  201. 7 option :error_handler do |o|
  202. 7 o.type :proc
  203. 7 o.default_proc(&DEFAULT_ERROR_HANDLER)
  204. end
  205. elsif Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
  206. option :error_handler do |o|
  207. o.type :proc
  208. o.experimental_default_proc(&DEFAULT_ERROR_HANDLER)
  209. end
  210. else
  211. option :error_handler, default: DEFAULT_ERROR_HANDLER
  212. end
  213. end
  214. end
  215. # Patcher enables patching of 'httpx' with datadog components.
  216. #
  217. 7 module Patcher
  218. 7 include Datadog::Tracing::Contrib::Patcher
  219. 7 module_function
  220. 7 def target_version
  221. 14 Integration.version
  222. end
  223. # loads a session instannce with the datadog plugin, and replaces the
  224. # base HTTPX::Session with the patched session class.
  225. 7 def patch
  226. 7 datadog_session = ::HTTPX.plugin(Plugin)
  227. 7 ::HTTPX.send(:remove_const, :Session)
  228. 7 ::HTTPX.send(:const_set, :Session, datadog_session.class)
  229. end
  230. end
  231. # Datadog Integration for HTTPX.
  232. #
  233. 7 class Integration
  234. 7 include Contrib::Integration
  235. 7 MINIMUM_VERSION = Gem::Version.new("0.10.2")
  236. 7 register_as :httpx
  237. 7 def self.version
  238. 287 Gem.loaded_specs["httpx"] && Gem.loaded_specs["httpx"].version
  239. end
  240. 7 def self.loaded?
  241. 91 defined?(::HTTPX::Request)
  242. end
  243. 7 def self.compatible?
  244. 91 super && version >= MINIMUM_VERSION
  245. end
  246. 7 def new_configuration
  247. 182 Configuration::Settings.new
  248. end
  249. 7 def patcher
  250. 182 Patcher
  251. end
  252. end
  253. end
  254. end
  255. 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. 148 sentry_span = start_sentry_span
  9. 148 return unless sentry_span
  10. 148 set_sentry_trace_header(request, sentry_span)
  11. 148 request.on(:response, &method(:finish_sentry_span).curry(3)[sentry_span, request])
  12. end
  13. 7 def start_sentry_span
  14. 148 return unless ::Sentry.initialized? && (span = ::Sentry.get_current_scope.get_span)
  15. 148 return if span.sampled == false
  16. 148 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. 148 return unless sentry_span
  20. 148 config = ::Sentry.configuration
  21. 148 url = request.uri.to_s
  22. 296 return unless config.propagate_traces && config.trace_propagation_targets.any? { |target| url.match?(target) }
  23. 148 trace = sentry_span.to_sentry_trace
  24. 148 request.headers[::Sentry::SENTRY_TRACE_HEADER_NAME] = trace if trace
  25. end
  26. 7 def finish_sentry_span(span, request, response)
  27. 156 return unless ::Sentry.initialized?
  28. 156 record_sentry_breadcrumb(request, response)
  29. 156 record_sentry_span(request, response, span)
  30. end
  31. 7 def record_sentry_breadcrumb(req, res)
  32. 156 return unless ::Sentry.configuration.breadcrumbs_logger.include?(:http_logger)
  33. 156 request_info = extract_request_info(req)
  34. 156 data = if res.is_a?(HTTPX::ErrorResponse)
  35. 16 { error: res.error.message, **request_info }
  36. else
  37. 140 { status: res.status, **request_info }
  38. end
  39. 156 crumb = ::Sentry::Breadcrumb.new(
  40. level: :info,
  41. category: "httpx",
  42. type: :info,
  43. data: data
  44. )
  45. 156 ::Sentry.add_breadcrumb(crumb)
  46. end
  47. 7 def record_sentry_span(req, res, sentry_span)
  48. 156 return unless sentry_span
  49. 156 request_info = extract_request_info(req)
  50. 156 sentry_span.set_description("#{request_info[:method]} #{request_info[:url]}")
  51. 156 if res.is_a?(HTTPX::ErrorResponse)
  52. 16 sentry_span.set_data(:error, res.error.message)
  53. else
  54. 140 sentry_span.set_data(:status, res.status)
  55. end
  56. 156 sentry_span.set_timestamp(::Sentry.utc_now.to_f)
  57. end
  58. 7 def extract_request_info(req)
  59. 312 uri = req.uri
  60. result = {
  61. 312 method: req.verb,
  62. }
  63. 312 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. 312 result[:url] = uri.to_s
  68. 312 result
  69. end
  70. end
  71. 7 module RequestMethods
  72. 7 def __sentry_enable_trace!
  73. 156 return if @__sentry_enable_trace
  74. 148 Tracer.call(self)
  75. 148 @__sentry_enable_trace = true
  76. end
  77. end
  78. 7 module ConnectionMethods
  79. 7 def send(request)
  80. 156 request.__sentry_enable_trace!
  81. 156 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

98.95% lines covered

95 relevant lines. 94 lines covered and 1 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. 227 @body.mock!
  71. end
  72. 9 def mocked?
  73. @mocked
  74. end
  75. end
  76. 9 module ResponseBodyMethods
  77. 9 def mock!
  78. 227 @inflaters = nil
  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. 296 return true if @mocked
  88. 40 super
  89. end
  90. 9 def interests
  91. 301 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. 48 @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. 32 other_uri = URI(other_uri) #: http_uri
  35. 32 uri.origin == other_uri.origin || begin
  36. 14 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. 16 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. 9624 return unless response.respond_to?(:headers)
  74. # Alt-Svc
  75. 9580 return unless response.headers.key?("alt-svc")
  76. 149 origin = request.origin
  77. 149 host = request.uri.host
  78. 149 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. 149 if altsvc == "clear"
  85. 9 @altsvc_mutex.synchronize do
  86. 9 @altsvcs[origin].clear
  87. end
  88. 8 return
  89. end
  90. 140 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. 266 return enum_for(__method__, altsvc) unless block_given?
  97. 203 scanner = StringScanner.new(altsvc)
  98. 210 until scanner.eos?
  99. 203 alt_service = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
  100. 203 alt_params = []
  101. 203 loop do
  102. 230 alt_param = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
  103. 230 alt_params << alt_param.strip if alt_param
  104. 230 scanner.skip(/;/)
  105. 230 break if scanner.eos? || scanner.scan(/ *, */)
  106. end
  107. 397 alt_params = Hash[alt_params.map { |field| field.split("=", 2) }]
  108. 203 alt_proto, alt_authority = alt_service.split("=", 2)
  109. 203 alt_origin = parse_altsvc_origin(alt_proto, alt_authority)
  110. 203 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. 210 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. 203 alt_scheme = parse_altsvc_scheme(alt_proto)
  124. 203 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. 19 def initialize(limit)
  23. 9055 @buffer = String.new("", encoding: Encoding::BINARY, capacity: limit)
  24. 9055 @limit = limit
  25. end
  26. 19 def <<(chunk)
  27. 29400 @buffer.append_as_bytes(chunk)
  28. end
  29. else
  30. 11 def initialize(limit)
  31. 18257 @buffer = "".b
  32. 18257 @limit = limit
  33. end
  34. 11 def_delegator :@buffer, :<<
  35. end
  36. 30 def full?
  37. 67451 @buffer.bytesize >= @limit
  38. end
  39. 30 def capacity
  40. 14 @limit - @buffer.bytesize
  41. end
  42. 30 def shift!(fin)
  43. 24098 @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. 358186 callbacks(type) << action
  6. 358186 action
  7. end
  8. 30 def once(type, &block)
  9. 218641 on(type) do |*args, &callback|
  10. 114773 block.call(*args, &callback)
  11. 114701 :delete
  12. end
  13. end
  14. 30 def emit(type, *args)
  15. 139613 log { "emit #{type.inspect} callbacks" } if respond_to?(:log)
  16. 284860 callbacks(type).delete_if { |pr| :delete == pr.call(*args) } # rubocop:disable Style/YodaCondition
  17. end
  18. 30 def callbacks_for?(type)
  19. 3915 @callbacks && @callbacks.key?(type) && @callbacks[type].any?
  20. end
  21. 30 protected
  22. 30 def callbacks(type = nil)
  23. 504050 return @callbacks unless type
  24. 718379 @callbacks ||= Hash.new { |h, k| h[k] = [] }
  25. 503952 @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. 7064 klass = is_a?(S) ? self.class : Session
  27. 7064 klass = Class.new(klass)
  28. 7064 klass.instance_variable_set(:@default_options, klass.default_options.merge(default_options))
  29. 7064 klass.plugin(pl, options, &blk).new
  30. end
  31. # returns a new instance loaded with +options+.
  32. 30 def with(options, &blk)
  33. 3615 branch(default_options.merge(options), &blk)
  34. end
  35. 30 private
  36. # returns default instance of HTTPX::Options.
  37. 30 def default_options
  38. 14024 @options || Session.default_options
  39. end
  40. # returns a default instance of HTTPX::Session.
  41. 30 def branch(options, &blk)
  42. 6877 return self.class.new(options, &blk) if is_a?(S)
  43. 3799 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. 59 case meth
  68. when /\Awith_(.+)/
  69. 47 option = Regexp.last_match(1)
  70. 47 default_options.respond_to?(option) || super
  71. when /\Aon_(.+)/
  72. 19 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. 6 ].include?(callback) || super
  79. else
  80. super
  81. end
  82. end
  83. end
  84. 30 extend Chainable
  85. end

lib/httpx/connection.rb

94.99% lines covered

499 relevant lines. 474 lines covered and 25 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. 1752 @current_session = @current_selector = @max_concurrent_requests =
  40. @parser = @sibling = @coalesced_connection = @altsvc_connection =
  41. @family = @io = @ssl_session = @timeout =
  42. 7543 @connected_at = @response_received_at = nil
  43. 9295 @exhausted = @cloned = @main_sibling = false
  44. 9295 @options = Options.new(options)
  45. 9295 @type = initialize_type(uri, @options)
  46. 9295 @origins = [uri.origin]
  47. 9295 @origin = Utils.to_uri(uri.origin)
  48. 9295 @window_size = @options.window_size
  49. 9295 @read_buffer = Buffer.new(@options.buffer_size)
  50. 9295 @write_buffer = Buffer.new(@options.buffer_size)
  51. 9295 @pending = []
  52. 9295 @inflight = 0
  53. 9295 @keep_alive_timeout = @options.timeout[:keep_alive_timeout]
  54. 9295 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. 9220 transition(:idle)
  62. end
  63. 9295 self.addresses = @options.addresses if @options.addresses
  64. end
  65. 30 def peer
  66. 19615 @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. 8928 if @io
  72. 421 @io.add_addresses(addrs)
  73. else
  74. 8507 @io = build_socket(addrs)
  75. end
  76. end
  77. 30 def addresses
  78. 17801 @io && @io.addresses
  79. end
  80. 30 def addresses?
  81. 10237 @io && @io.addresses?
  82. end
  83. 30 def match?(uri, options)
  84. 2869 return false if !used? && (@state == :closing || @state == :closed)
  85. 2707 @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. 2557 (@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. 511 return false if @state == :closing || @state == :closed || !@io
  95. 139 return false unless connection.addresses
  96. 2 (
  97. 139 (open? && @origin == connection.origin) ||
  98. 139 !(@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. 10199 @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. 57 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. 28 @origin == connection.origin
  120. end
  121. end
  122. 30 def merge(connection)
  123. 72 @origins |= connection.instance_variable_get(:@origins)
  124. 75 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. 75 connection.purge_pending do |req|
  131. 30 req.transition(:idle)
  132. 30 send(req)
  133. end
  134. end
  135. 30 def purge_pending(&block)
  136. 75 pendings = []
  137. 75 if @parser
  138. 27 pending = @parser.pending
  139. 24 @inflight -= pending.size
  140. 27 pendings << pending
  141. end
  142. 75 pendings << @pending
  143. 75 pendings.each do |pending|
  144. 102 pending.reject!(&block)
  145. end
  146. end
  147. 30 def io_connected?
  148. 25 return @coalesced_connection.io_connected? if @coalesced_connection
  149. 25 @io && @io.state == :connected
  150. end
  151. 30 def connecting?
  152. 216378 @state == :idle
  153. end
  154. 30 def inflight?
  155. 3660 @parser && (
  156. # parser may be dealing with other requests (possibly started from a different fiber)
  157. 3091 !@parser.empty? ||
  158. # connection may be doing connection termination handshake
  159. !@write_buffer.empty?
  160. )
  161. end
  162. 30 def interests
  163. # connecting
  164. 178251 if connecting?
  165. 14537 connect
  166. 14537 return @io.interests if connecting?
  167. end
  168. 164473 return @parser.interests if @parser
  169. 34 nil
  170. rescue StandardError => e
  171. on_error(e)
  172. nil
  173. end
  174. 30 def to_io
  175. 33469 @io.to_io
  176. end
  177. 30 def call
  178. 28722 case @state
  179. when :idle
  180. 13487 connect
  181. # when opening the tcp or ssl socket fails
  182. 13469 return if @state == :closed
  183. 13438 consume
  184. when :closed
  185. 4 return
  186. when :closing
  187. consume
  188. transition(:closed)
  189. when :open
  190. 17268 consume
  191. end
  192. 13762 nil
  193. rescue IOError => e
  194. @write_buffer.clear
  195. on_io_error(e)
  196. rescue StandardError => e
  197. 19 @write_buffer.clear
  198. 19 on_error(e)
  199. rescue Exception => e # rubocop:disable Lint/RescueException
  200. 117 force_close(true)
  201. 108 raise e
  202. end
  203. 30 def close
  204. 3394 transition(:active) if @state == :inactive
  205. 3394 @parser.close if @parser
  206. end
  207. 30 def terminate
  208. 3004 case @state
  209. when :idle
  210. purge_after_closed
  211. disconnect
  212. when :closed
  213. 18 @connected_at = nil
  214. end
  215. 3349 close
  216. end
  217. # bypasses state machine rules while setting the connection in the
  218. # :closed state.
  219. 30 def force_close(delete_pending = false)
  220. 460 force_purge
  221. 460 return unless @state == :closed
  222. 460 if delete_pending
  223. 285 @pending.clear
  224. 175 elsif (parser = @parser)
  225. enqueue_pending_requests_from_parser(parser)
  226. end
  227. 460 return unless @pending.empty?
  228. 460 disconnect
  229. 451 emit(:force_closed, delete_pending)
  230. end
  231. # bypasses the state machine to force closing of connections still connecting.
  232. # **only** used for Happy Eyeballs v2.
  233. 30 def force_reset(cloned = false)
  234. 252 @state = :closing
  235. 252 @cloned = cloned
  236. 252 transition(:closed)
  237. end
  238. 30 def reset
  239. 9786 return if @state == :closing || @state == :closed
  240. 9734 parser = @parser
  241. 9734 if parser && parser.respond_to?(:max_concurrent_requests)
  242. # if connection being reset has at some downgraded the number of concurrent
  243. # requests, such as in the case where an attempt to use HTTP/1 pipelining failed,
  244. # keep that information around.
  245. 5275 @max_concurrent_requests = parser.max_concurrent_requests
  246. end
  247. 9734 transition(:closing)
  248. 9734 transition(:closed)
  249. end
  250. 30 def send(request)
  251. 11424 return @coalesced_connection.send(request) if @coalesced_connection
  252. 11403 if @parser && !@write_buffer.full?
  253. 540 if @response_received_at && @keep_alive_timeout &&
  254. Utils.elapsed_time(@response_received_at) > @keep_alive_timeout
  255. # when pushing a request into an existing connection, we have to check whether there
  256. # is the possibility that the connection might have extended the keep alive timeout.
  257. # for such cases, we want to ping for availability before deciding to shovel requests.
  258. 22 log(level: 3) { "keep alive timeout expired, pinging connection..." }
  259. 22 @pending << request
  260. 22 transition(:active) if @state == :inactive
  261. 22 parser.ping
  262. 22 request.ping!
  263. 20 return
  264. end
  265. 518 send_request_to_parser(request)
  266. else
  267. 10863 @pending << request
  268. end
  269. end
  270. 30 def timeout
  271. 33023 return if @state == :closed || @state == :inactive
  272. 33020 return @timeout if @timeout
  273. 12315 return @options.timeout[:connect_timeout] if @state == :idle
  274. 12315 @options.timeout[:operation_timeout]
  275. end
  276. 30 def idling
  277. 1290 purge_after_closed
  278. 1290 @write_buffer.clear
  279. 1290 transition(:idle)
  280. 1290 return unless @parser
  281. 1290 enqueue_pending_requests_from_parser(parser)
  282. 1290 @parser = nil
  283. end
  284. 30 def used?
  285. 6673 @connected_at
  286. end
  287. 30 def deactivate
  288. 538 transition(:inactive)
  289. end
  290. 30 def open?
  291. 9337 @state == :open || @state == :inactive
  292. end
  293. 30 def handle_socket_timeout(interval)
  294. 54 error = OperationTimeoutError.new(interval, "timed out while waiting on select")
  295. 54 error.set_backtrace(caller)
  296. 54 on_error(error)
  297. end
  298. 30 def sibling=(connection)
  299. 134 @sibling = connection
  300. 134 return unless connection
  301. 106 @main_sibling = connection.sibling.nil?
  302. 106 return unless @main_sibling
  303. 53 connection.sibling = self
  304. end
  305. 30 def handle_connect_error(error)
  306. 408 return on_error(error) unless @sibling && @sibling.connecting?
  307. 18 @sibling.merge(self)
  308. 18 force_reset(true)
  309. end
  310. # disconnects from the current session it's attached to
  311. 30 def disconnect
  312. 10640 return if @exhausted # it'll reset
  313. 10640 return unless (current_session = @current_session) && (current_selector = @current_selector)
  314. 10491 @current_session = @current_selector = nil
  315. 10491 current_session.deselect_connection(self, current_selector, @cloned)
  316. end
  317. 30 def on_connect_error(e)
  318. # connect errors, exit gracefully
  319. 98 error = ConnectionError.new(e.message)
  320. 98 error.set_backtrace(e.backtrace)
  321. 98 handle_connect_error(error) if connecting?
  322. 98 force_close
  323. end
  324. 30 def on_io_error(e)
  325. on_error(e)
  326. force_close(true)
  327. end
  328. 30 def on_error(error, request = nil)
  329. 1399 if error.is_a?(OperationTimeoutError)
  330. # inactive connections do not contribute to the select loop, therefore
  331. # they should not fail due to such errors.
  332. 54 return if @state == :inactive
  333. 54 if @timeout
  334. 43 @timeout -= error.timeout
  335. 47 return unless @timeout <= 0
  336. end
  337. 49 error = error.to_connection_error if connecting?
  338. end
  339. 1394 handle_error(error, request)
  340. 1376 reset
  341. end
  342. skipped # :nocov:
  343. skipped def inspect
  344. skipped "#<#{self.class}:#{object_id} " \
  345. skipped "@origin=#{@origin} " \
  346. skipped "@state=#{@state} " \
  347. skipped "@pending=#{@pending.size} " \
  348. skipped "@io=#{@io}>"
  349. skipped end
  350. skipped # :nocov:
  351. 30 private
  352. 30 def connect
  353. 26809 transition(:open)
  354. end
  355. 30 def consume
  356. 34699 return unless @io
  357. 34699 catch(:called) do
  358. 34699 epiped = false
  359. 34699 loop do
  360. # connection may have
  361. 52513 return if @state == :idle
  362. 48213 parser.consume
  363. # we exit if there's no more requests to process
  364. #
  365. # this condition takes into account:
  366. #
  367. # * the number of inflight requests
  368. # * the number of pending requests
  369. # * whether the write buffer has bytes (i.e. for close handshake)
  370. 48195 if @pending.empty? && @inflight.zero? && @write_buffer.empty?
  371. 3465 log(level: 3) { "NO MORE REQUESTS..." } if @parser && @parser.pending.any?
  372. # terminate if an altsvc connection has been established
  373. 3465 terminate if @altsvc_connection
  374. 3465 return
  375. end
  376. 44730 @timeout = @current_timeout
  377. 44730 read_drained = false
  378. 44730 write_drained = nil
  379. #
  380. # tight read loop.
  381. #
  382. # read as much of the socket as possible.
  383. #
  384. # this tight loop reads all the data it can from the socket and pipes it to
  385. # its parser.
  386. #
  387. 11873 loop do
  388. 67589 siz = @io.read(@window_size, @read_buffer)
  389. 67789 log(level: 3, color: :cyan) { "IO READ: #{siz} bytes... (wsize: #{@window_size}, rbuffer: #{@read_buffer.bytesize})" }
  390. 67587 unless siz
  391. 20 @write_buffer.clear
  392. 20 ex = EOFError.new("descriptor closed")
  393. 20 ex.set_backtrace(caller)
  394. 20 on_error(ex)
  395. 20 return
  396. end
  397. # socket has been drained. mark and exit the read loop.
  398. 67567 if siz.zero?
  399. 16983 read_drained = @read_buffer.empty?
  400. 16983 epiped = false
  401. 16983 break
  402. end
  403. 50584 parser << @read_buffer.to_s
  404. # continue reading if possible.
  405. 45257 break if interests == :w && !epiped
  406. # exit the read loop if connection is preparing to be closed
  407. 39375 break if @state == :closing || @state == :closed
  408. # exit #consume altogether if all outstanding requests have been dealt with
  409. 39247 if @pending.empty? && @inflight.zero? && @write_buffer.empty? # rubocop:disable Style/Next
  410. 3785 log(level: 3) { "NO MORE REQUESTS..." } if @parser && @parser.pending.any?
  411. # terminate if an altsvc connection has been established
  412. 3785 terminate if @altsvc_connection
  413. 3785 return
  414. end
  415. 44730 end unless ((ints = interests).nil? || ints == :w || @state == :closing) && !epiped
  416. #
  417. # tight write loop.
  418. #
  419. # flush as many bytes as the sockets allow.
  420. #
  421. 8433 loop do
  422. # buffer has been drained, mark and exit the write loop.
  423. 26641 if @write_buffer.empty?
  424. # we only mark as drained on the first loop
  425. 3374 write_drained = write_drained.nil? && @inflight.positive?
  426. 3374 break
  427. end
  428. 2276 begin
  429. 23267 siz = @io.write(@write_buffer)
  430. rescue Errno::EPIPE
  431. # this can happen if we still have bytes in the buffer to send to the server, but
  432. # the server wants to respond immediately with some message, or an error. An example is
  433. # when one's uploading a big file to an unintended endpoint, and the server stops the
  434. # consumption, and responds immediately with an authorization of even method not allowed error.
  435. # at this point, we have to let the connection switch to read-mode.
  436. 14 log(level: 2) { "pipe broken, could not flush buffer..." }
  437. 14 epiped = true
  438. 14 read_drained = false
  439. 14 break
  440. end
  441. 23360 log(level: 3, color: :cyan) { "IO WRITE: #{siz} bytes..." }
  442. 23252 unless siz
  443. @write_buffer.clear
  444. ex = EOFError.new("descriptor closed")
  445. ex.set_backtrace(caller)
  446. on_error(ex)
  447. return
  448. end
  449. # socket closed for writing. mark and exit the write loop.
  450. 23252 if siz.zero?
  451. 18 write_drained = !@write_buffer.empty?
  452. 18 break
  453. end
  454. # exit write loop if marked to consume from peer, or is closing.
  455. 23234 break if interests == :r || @state == :closing || @state == :closed
  456. 3707 write_drained = false
  457. 35596 end unless (ints = interests) == :r
  458. 35595 send_pending if @state == :open
  459. # return if socket is drained
  460. 35595 next unless (ints != :r || read_drained) && (ints != :w || write_drained)
  461. # gotta go back to the event loop. It happens when:
  462. #
  463. # * the socket is drained of bytes or it's not the interest of the conn to read;
  464. # * theres nothing more to write, or it's not in the interest of the conn to write;
  465. 17863 log(level: 3) { "(#{ints}): WAITING FOR EVENTS..." }
  466. 17781 return
  467. end
  468. end
  469. end
  470. 30 def send_pending
  471. 94072 while !@write_buffer.full? && (request = @pending.shift)
  472. 20994 send_request_to_parser(request)
  473. end
  474. end
  475. 30 def parser
  476. 131980 @parser ||= build_parser
  477. end
  478. 30 def send_request_to_parser(request)
  479. 20458 @inflight += 1
  480. 21512 request.peer_address = @io.ip && @io.ip.address
  481. 21512 set_request_timeouts(request)
  482. 21512 parser.send(request)
  483. 21512 return unless @state == :inactive
  484. 32 transition(:active)
  485. # mark request as ping, as this inactive connection may have been
  486. # closed by the server, and we don't want that to influence retry
  487. # bookkeeping.
  488. 32 request.ping!
  489. end
  490. 30 def enqueue_pending_requests_from_parser(parser)
  491. 6196 parser.reset_requests # move sequential requests back to pending queue.
  492. 6196 parser_pending_requests = parser.pending
  493. 6196 return if parser_pending_requests.empty?
  494. # the connection will be reused, so parser requests must come
  495. # back to the pending list before the parser is reset.
  496. 394 @inflight -= parser_pending_requests.size
  497. 428 @pending.unshift(*parser_pending_requests)
  498. 428 parser.pending.clear
  499. end
  500. 30 def build_parser(protocol = @io.protocol)
  501. 9384 parser = parser_type(protocol).new(@write_buffer, @options)
  502. 9384 set_parser_callbacks(parser)
  503. 9384 parser.max_concurrent_requests = @max_concurrent_requests if @max_concurrent_requests && parser.respond_to?(:max_concurrent_requests=)
  504. 9384 parser
  505. end
  506. 30 def set_parser_callbacks(parser)
  507. 9508 parser.on(:response) do |request, response|
  508. 9615 AltSvc.emit(request, response) do |alt_origin, origin, alt_params|
  509. 18 build_altsvc_connection(alt_origin, origin, alt_params)
  510. end
  511. 9615 @response_received_at = Utils.now
  512. 8707 @inflight -= 1
  513. 9615 response.finish!
  514. 9615 request.emit(:response, response)
  515. end
  516. 9508 parser.on(:altsvc) do |alt_origin, origin, alt_params|
  517. build_altsvc_connection(alt_origin, origin, alt_params)
  518. end
  519. 9508 parser.on(:pong, &method(:send_pending))
  520. 9508 parser.on(:promise) do |request, stream|
  521. 27 request.emit(:promise, parser, stream)
  522. end
  523. 9508 parser.on(:exhausted) do
  524. 9 enqueue_pending_requests_from_parser(parser)
  525. 9 @exhausted = true
  526. 9 parser.close
  527. 9 idling
  528. 9 @exhausted = false
  529. end
  530. 9508 parser.on(:origin) do |origin|
  531. @origins |= [origin]
  532. end
  533. 9508 parser.on(:close) do
  534. 3486 reset
  535. end
  536. 9508 parser.on(:close_handshake) do
  537. 22 consume unless @state == :closed
  538. end
  539. 9508 parser.on(:reset) do
  540. 4888 enqueue_pending_requests_from_parser(parser)
  541. 4888 reset
  542. # :reset event only fired in http/1.1, so this guarantees
  543. # that the connection will be closed here.
  544. 4879 idling unless @pending.empty?
  545. end
  546. 9508 parser.on(:current_timeout) do
  547. 4108 @current_timeout = @timeout = parser.timeout
  548. end
  549. 9508 parser.on(:timeout) do |tout|
  550. 3385 @timeout = tout
  551. end
  552. 9508 parser.on(:error) do |request, error|
  553. 147 case error
  554. when :http_1_1_required
  555. 18 current_session = @current_session
  556. 18 current_selector = @current_selector
  557. 18 parser.close
  558. 18 other_connection = current_session.find_connection(@origin, current_selector,
  559. @options.merge(ssl: { alpn_protocols: %w[http/1.1] }))
  560. 18 other_connection.merge(self)
  561. 18 request.transition(:idle)
  562. 18 other_connection.send(request)
  563. 18 next
  564. when OperationTimeoutError
  565. # request level timeouts should take precedence
  566. next unless request.active_timeouts.empty?
  567. end
  568. 131 @inflight -= 1
  569. 144 response = ErrorResponse.new(request, error)
  570. 144 request.response = response
  571. 144 request.emit(:response, response)
  572. end
  573. end
  574. 30 def transition(nextstate)
  575. 59623 handle_transition(nextstate)
  576. rescue Errno::ECONNABORTED,
  577. Errno::ECONNREFUSED,
  578. Errno::ECONNRESET,
  579. Errno::EADDRNOTAVAIL,
  580. Errno::EHOSTUNREACH,
  581. Errno::EINVAL,
  582. Errno::ENETUNREACH,
  583. Errno::EPIPE,
  584. Errno::ENOENT,
  585. SocketError,
  586. IOError => e
  587. 98 on_connect_error(e)
  588. rescue TLSError, ::HTTP2::Error::ProtocolError, ::HTTP2::Error::HandshakeError => e
  589. # connect errors, exit gracefully
  590. 27 handle_error(e)
  591. 27 handle_connect_error(e) if connecting?
  592. 27 force_close
  593. end
  594. 30 def handle_transition(nextstate)
  595. 53700 case nextstate
  596. when :idle
  597. 10518 @timeout = @current_timeout = @options.timeout[:connect_timeout]
  598. 10518 @connected_at = @response_received_at = nil
  599. when :open
  600. 27206 return if @state == :closed
  601. 27206 @io.connect
  602. 27081 close_sibling if @io.state == :connected
  603. 27081 return unless @io.connected?
  604. 9415 @connected_at = Utils.now
  605. 9415 send_pending
  606. 9415 @timeout = @current_timeout = parser.timeout
  607. 9415 emit(:open)
  608. when :inactive
  609. 538 return unless @state == :open
  610. # @type ivar @parser: HTTP1 | HTTP2
  611. # do not deactivate connection in use
  612. 494 return if @inflight.positive? || @parser.waiting_for_ping?
  613. when :closing
  614. 9734 return unless connecting? || @state == :open
  615. 9734 unless @write_buffer.empty?
  616. # preset state before handshake, as error callbacks
  617. # may take it back here.
  618. 3398 @state = nextstate
  619. # handshakes, try sending
  620. 3398 consume
  621. 3398 @write_buffer.clear
  622. 3398 return
  623. end
  624. when :closed
  625. 9986 return unless @state == :closing
  626. 9986 return unless @write_buffer.empty?
  627. 9986 purge_after_closed
  628. when :already_open
  629. 75 nextstate = :open
  630. # the first check for given io readiness must still use a timeout.
  631. # connect is the reasonable choice in such a case.
  632. 75 @timeout = @options.timeout[:connect_timeout]
  633. 75 send_pending
  634. when :active
  635. 293 return unless @state == :inactive
  636. 293 nextstate = :open
  637. # activate
  638. 293 @current_session.select_connection(self, @current_selector)
  639. end
  640. 38071 log(level: 3) { "#{@state} -> #{nextstate}" }
  641. 37789 @state = nextstate
  642. # post state change
  643. 34090 case nextstate
  644. when :inactive
  645. 494 disconnect
  646. when :closed
  647. # TODO: should this raise an error instead?
  648. 9986 return unless @pending.empty?
  649. 9702 disconnect
  650. end
  651. end
  652. 30 def force_purge
  653. 460 return if @state == :closed
  654. 298 @state = :closed
  655. 298 @write_buffer.clear
  656. 15 begin
  657. 298 purge_after_closed
  658. rescue IOError
  659. # may be raised when closing the socket.
  660. # due to connection reuse / fiber scheduling, it may
  661. # have been reopened, to bail out in that case.
  662. end
  663. end
  664. 30 def close_sibling
  665. 12588 return unless @sibling
  666. 25 if @sibling.io_connected?
  667. reset
  668. # TODO: transition connection to closed
  669. end
  670. 25 unless @sibling.state == :closed
  671. 7 merge(@sibling) unless @main_sibling
  672. 7 @sibling.force_reset(true)
  673. end
  674. 25 @sibling = nil
  675. end
  676. 30 def purge_after_closed
  677. 11697 @io.close if @io
  678. 11697 @read_buffer.clear
  679. 11697 @timeout = nil
  680. end
  681. 30 def initialize_type(uri, options)
  682. 8875 options.transport || begin
  683. 8010 case uri.scheme
  684. when "http"
  685. 5010 "tcp"
  686. when "https"
  687. 3833 "ssl"
  688. else
  689. raise UnsupportedSchemeError, "#{uri}: #{uri.scheme}: unsupported URI scheme"
  690. end
  691. end
  692. end
  693. # returns an HTTPX::Connection for the negotiated Alternative Service (or none).
  694. 30 def build_altsvc_connection(alt_origin, origin, alt_params)
  695. 18 return if @altsvc_connection
  696. # do not allow security downgrades on altsvc negotiation
  697. 9 return if @origin.scheme == "https" && alt_origin.scheme != "https"
  698. 9 altsvc = AltSvc.cached_altsvc_set(origin, alt_params.merge("origin" => alt_origin))
  699. # altsvc already exists, somehow it wasn't advertised, probably noop
  700. 9 return unless altsvc
  701. 9 alt_options = @options.merge(ssl: @options.ssl.merge(hostname: URI(origin).host))
  702. 9 connection = @current_session.find_connection(alt_origin, @current_selector, alt_options)
  703. # advertised altsvc is the same origin being used, ignore
  704. 9 return if connection == self
  705. 9 connection.extend(AltSvc::ConnectionMixin) unless connection.is_a?(AltSvc::ConnectionMixin)
  706. 9 @altsvc_connection = connection
  707. 9 log(level: 1) { "#{origin}: alt-svc connection##{connection.object_id} established to #{alt_origin}" }
  708. 9 connection.merge(self)
  709. rescue UnsupportedSchemeError
  710. altsvc["noop"] = true
  711. nil
  712. end
  713. 30 def build_socket(addrs = nil)
  714. 7721 case @type
  715. when "tcp"
  716. 4949 TCP.new(peer, addrs, @options)
  717. when "ssl"
  718. 3601 SSL.new(peer, addrs, @options) do |sock|
  719. 3576 sock.ssl_session = @ssl_session
  720. 3576 sock.session_new_cb do |sess|
  721. 6420 @ssl_session = sess
  722. 6420 sock.ssl_session = sess
  723. end
  724. end
  725. when "unix"
  726. 32 path = Array(addrs).first
  727. 32 path = String(path) if path
  728. 32 UNIX.new(peer, path, @options)
  729. else
  730. raise Error, "unsupported transport (#{@type})"
  731. end
  732. end
  733. # recover internal state and emit all relevant error responses when +error+ was raised.
  734. # this takes an optiona +request+ which may have already been handled and can be opted out
  735. # in the state recovery process.
  736. 30 def handle_error(error, request = nil)
  737. 1421 parser.handle_error(error, request) if @parser && @parser.respond_to?(:handle_error)
  738. 3136 while (req = @pending.shift)
  739. 615 next if request && req == request
  740. 597 response = ErrorResponse.new(req, error)
  741. 597 req.response = response
  742. 579 req.emit(:response, response)
  743. end
  744. 1403 return unless request
  745. 680 @inflight -= 1
  746. 765 response = ErrorResponse.new(request, error)
  747. 765 request.response = response
  748. 765 request.emit(:response, response)
  749. end
  750. 30 def set_request_timeouts(request)
  751. 21512 set_request_write_timeout(request)
  752. 21512 set_request_read_timeout(request)
  753. 21512 set_request_request_timeout(request)
  754. end
  755. 30 def set_request_read_timeout(request)
  756. 21512 read_timeout = request.read_timeout
  757. 21512 return if read_timeout.nil? || read_timeout.infinite?
  758. 21064 set_request_timeout(:read_timeout, request, read_timeout, :done, :response) do
  759. 18 read_timeout_callback(request, read_timeout)
  760. end
  761. end
  762. 30 def set_request_write_timeout(request)
  763. 21512 write_timeout = request.write_timeout
  764. 21512 return if write_timeout.nil? || write_timeout.infinite?
  765. 21512 set_request_timeout(:write_timeout, request, write_timeout, :headers, %i[done response]) do
  766. 18 write_timeout_callback(request, write_timeout)
  767. end
  768. end
  769. 30 def set_request_request_timeout(request)
  770. 21193 request_timeout = request.request_timeout
  771. 21193 return if request_timeout.nil? || request_timeout.infinite?
  772. 1317 set_request_timeout(:request_timeout, request, request_timeout, :headers, :complete) do
  773. 972 read_timeout_callback(request, request_timeout, RequestTimeoutError)
  774. end
  775. end
  776. 30 def write_timeout_callback(request, write_timeout)
  777. 18 return if request.state == :done
  778. 18 @write_buffer.clear
  779. 18 error = WriteTimeoutError.new(request, nil, write_timeout)
  780. 18 on_error(error, request)
  781. end
  782. 30 def read_timeout_callback(request, read_timeout, error_type = ReadTimeoutError)
  783. 990 response = request.response
  784. 990 return if response && response.finished?
  785. 747 @write_buffer.clear
  786. 747 error = error_type.new(request, request.response, read_timeout)
  787. 747 on_error(error, request)
  788. end
  789. 30 def set_request_timeout(label, request, timeout, start_event, finish_events, &callback)
  790. 43967 request.set_timeout_callback(start_event) do
  791. 43713 unless @current_selector
  792. raise Error, "request has been resend to an out-of-session connection, and this " \
  793. "should never happen!!! Please report this error! " \
  794. "(state:#{@state}, " \
  795. "parser?:#{!!@parser}, " \
  796. "bytes in write buffer?:#{!@write_buffer.empty?}, " \
  797. "cloned?:#{@cloned}, " \
  798. "sibling?:#{!!@sibling}, " \
  799. "coalesced?:#{coalesced?})"
  800. end
  801. 43713 timer = @current_selector.after(timeout, callback)
  802. 43713 request.active_timeouts << label
  803. 43713 Array(finish_events).each do |event|
  804. # clean up request timeouts if the connection errors out
  805. 65185 request.set_timeout_callback(event) do
  806. 64022 timer.cancel
  807. 64022 request.active_timeouts.delete(label)
  808. end
  809. end
  810. end
  811. end
  812. 30 def parser_type(protocol)
  813. 8598 case protocol
  814. 4133 when "h2" then @options.http2_class
  815. 5429 when "http/1.1" then @options.http1_class
  816. else
  817. raise Error, "unsupported protocol (##{protocol})"
  818. end
  819. end
  820. end
  821. end

lib/httpx/connection/http1.rb

89.78% lines covered

225 relevant lines. 202 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. 5438 @options = options
  18. 5438 @max_concurrent_requests = @options.max_concurrent_requests || MAX_REQUESTS
  19. 5438 @max_requests = @options.max_requests
  20. 5438 @parser = Parser::HTTP1.new(self)
  21. 5438 @buffer = buffer
  22. 5438 @version = [1, 1]
  23. 5438 @pending = []
  24. 5438 @requests = []
  25. 5438 @handshake_completed = false
  26. end
  27. 30 def timeout
  28. 5299 @options.timeout[:operation_timeout]
  29. end
  30. 30 def interests
  31. 50822 request = @request || @requests.first
  32. 50822 return unless request
  33. 50810 return :w if request.interests == :w || !@buffer.empty?
  34. 33215 :r
  35. end
  36. 30 def reset
  37. 5039 @max_requests = @options.max_requests || MAX_REQUESTS
  38. 5039 @parser.reset!
  39. 5039 @handshake_completed = false
  40. 5039 reset_requests
  41. end
  42. 30 def reset_requests
  43. 10742 @pending.unshift(*@requests)
  44. 10742 @requests.clear
  45. end
  46. 30 def close
  47. 98 reset
  48. 98 emit(:close)
  49. end
  50. 30 def exhausted?
  51. 534 !@max_requests.positive?
  52. end
  53. 30 def empty?
  54. # this means that for every request there's an available
  55. # partial response, so there are no in-flight requests waiting.
  56. 36 @requests.empty? || (
  57. # checking all responses can be time-consuming. Alas, as in HTTP/1, responses
  58. # do not come out of order, we can get away with checking first and last.
  59. !@requests.first.response.nil? &&
  60. (@requests.size == 1 || !@requests.last.response.nil?)
  61. )
  62. end
  63. 30 def <<(data)
  64. 8363 @parser << data
  65. end
  66. 30 def send(request)
  67. 16842 unless @max_requests.positive?
  68. @pending << request
  69. return
  70. end
  71. 16842 return if @requests.include?(request)
  72. 16671 @requests << request
  73. 16671 @pipelining = true if @requests.size > 1
  74. end
  75. 30 def consume
  76. 19416 requests_limit = [@max_requests, @requests.size].min
  77. 19416 concurrent_requests_limit = [@max_concurrent_requests, requests_limit].min
  78. 19416 @requests.each_with_index do |request, idx|
  79. 22365 break if idx >= concurrent_requests_limit
  80. 19588 next unless request.can_buffer?
  81. 7454 handle(request)
  82. end
  83. end
  84. # HTTP Parser callbacks
  85. #
  86. # must be public methods, or else they won't be reachable
  87. 30 def on_start
  88. 5693 log(level: 2) { "parsing begins" }
  89. end
  90. 30 def on_headers(h)
  91. 5639 @request = @requests.first
  92. 5639 return if @request.response
  93. 5693 log(level: 2) { "headers received" }
  94. 5639 headers = @request.options.headers_class.new(h)
  95. 5639 response = @request.options.response_class.new(@request,
  96. @parser.status_code,
  97. @parser.http_version.join("."),
  98. headers)
  99. 5693 log(color: :yellow) { "-> HEADLINE: #{response.status} HTTP/#{@parser.http_version.join(".")}" }
  100. 6125 log(color: :yellow) { response.headers.each.map { |f, v| "-> HEADER: #{f}: #{log_redact_headers(v)}" }.join("\n") }
  101. 5639 @request.response = response
  102. 5630 on_complete if response.finished?
  103. end
  104. 30 def on_trailers(h)
  105. 9 return unless @request
  106. 9 response = @request.response
  107. 9 log(level: 2) { "trailer headers received" }
  108. 9 log(color: :yellow) { h.each.map { |f, v| "-> HEADER: #{f}: #{log_redact_headers(v.join(", "))}" }.join("\n") }
  109. 9 response.merge_headers(h)
  110. end
  111. 30 def on_data(chunk)
  112. 6556 request = @request
  113. 6556 return unless request
  114. 6610 log(color: :green) { "-> DATA: #{chunk.bytesize} bytes..." }
  115. 6610 log(level: 2, color: :green) { "-> #{log_redact_body(chunk.inspect)}" }
  116. 6556 response = request.response
  117. 6556 response << chunk
  118. rescue StandardError => e
  119. 16 error_response = ErrorResponse.new(request, e)
  120. 16 request.response = error_response
  121. 16 dispatch
  122. end
  123. 30 def on_complete
  124. 5596 request = @request
  125. 5596 return unless request
  126. 5650 log(level: 2) { "parsing complete" }
  127. 5596 dispatch
  128. end
  129. 30 def dispatch
  130. 5612 request = @request
  131. 5612 if request.expects?
  132. 73 @parser.reset!
  133. 65 return handle(request)
  134. end
  135. 5539 @request = nil
  136. 5539 @requests.shift
  137. 5539 response = request.response
  138. 5539 emit(:response, request, response)
  139. 5459 if @parser.upgrade?
  140. 37 response << @parser.upgrade_data
  141. 37 @parser.reset!
  142. 37 throw(:called)
  143. end
  144. 5422 @parser.reset!
  145. 4920 @max_requests -= 1
  146. 5422 if response.is_a?(ErrorResponse)
  147. 16 disable
  148. else
  149. 5406 manage_connection(request, response)
  150. end
  151. 534 if exhausted?
  152. @pending.unshift(*@requests)
  153. @requests.clear
  154. emit(:exhausted)
  155. else
  156. 534 send(@pending.shift) unless @pending.empty?
  157. end
  158. end
  159. 30 def handle_error(ex, request = nil)
  160. 387 if (ex.is_a?(EOFError) || ex.is_a?(TimeoutError)) && @request &&
  161. 18 (response = @request.response) && response.is_a?(Response) &&
  162. !response.headers.key?("content-length") &&
  163. !response.headers.key?("transfer-encoding")
  164. # if the response does not contain a content-length header, the server closing the
  165. # connnection is the indicator of response consumed.
  166. # https://greenbytes.de/tech/webdav/rfc2616.html#rfc.section.4.4
  167. 36 catch(:called) { on_complete }
  168. 16 return
  169. end
  170. 369 if @pipelining
  171. 36 catch(:called) { disable }
  172. else
  173. 351 @requests.each do |req|
  174. 342 next if request && request == req
  175. emit(:error, req, ex)
  176. end
  177. 351 @pending.each do |req|
  178. next if request && request == req
  179. emit(:error, req, ex)
  180. end
  181. end
  182. end
  183. 30 def ping
  184. reset
  185. emit(:reset)
  186. emit(:exhausted)
  187. end
  188. 30 def waiting_for_ping?
  189. 21 false
  190. end
  191. 30 private
  192. 30 def manage_connection(request, response)
  193. 5406 connection = response.headers["connection"]
  194. 4905 case connection
  195. when /keep-alive/i
  196. 525 if @handshake_completed
  197. if @max_requests.zero?
  198. @pending.unshift(*@requests)
  199. @requests.clear
  200. emit(:exhausted)
  201. end
  202. return
  203. end
  204. 525 keep_alive = response.headers["keep-alive"]
  205. 525 return unless keep_alive
  206. 109 parameters = Hash[keep_alive.split(/ *, */).map do |pair|
  207. 109 pair.split(/ *= */, 2)
  208. end]
  209. 109 @max_requests = parameters["max"].to_i - 1 if parameters.key?("max")
  210. 109 if parameters.key?("timeout")
  211. keep_alive_timeout = parameters["timeout"].to_i
  212. emit(:timeout, keep_alive_timeout)
  213. end
  214. 109 @handshake_completed = true
  215. when /close/i
  216. 4872 disable
  217. when nil
  218. # In HTTP/1.1, it's keep alive by default
  219. 9 return if response.version == "1.1" && request.headers["connection"] != "close"
  220. disable
  221. end
  222. end
  223. 30 def disable
  224. 4906 disable_pipelining
  225. 4906 reset
  226. 4906 emit(:reset)
  227. 4897 throw(:called)
  228. end
  229. 30 def disable_pipelining
  230. # do not disable pipelining if already set to 1 request at a time
  231. 4906 return if @max_concurrent_requests == 1
  232. 3900 @requests.each do |r|
  233. 109 r.transition(:idle)
  234. # when we disable pipelining, we still want to try keep-alive.
  235. # only when keep-alive with one request fails, do we fallback to
  236. # connection: close.
  237. 109 r.headers["connection"] = "close" if @max_concurrent_requests == 1
  238. end
  239. # server doesn't handle pipelining, and probably
  240. # doesn't support keep-alive. Fallback to send only
  241. # 1 keep alive request.
  242. 3900 @max_concurrent_requests = 1
  243. 3900 @pipelining = false
  244. end
  245. 30 def set_protocol_headers(request)
  246. 6017 if !request.headers.key?("content-length") &&
  247. request.body.bytesize == Float::INFINITY
  248. 36 request.body.chunk!
  249. end
  250. 6017 extra_headers = {}
  251. 6017 unless request.headers.key?("connection")
  252. 5990 connection_value = if request.persistent?
  253. # when in a persistent connection, the request can't be at
  254. # the edge of a renegotiation
  255. 160 if @requests.index(request) + 1 < @max_requests
  256. 160 "keep-alive"
  257. else
  258. "close"
  259. end
  260. else
  261. # when it's not a persistent connection, it sets "Connection: close" always
  262. # on the last request of the possible batch (either allowed max requests,
  263. # or if smaller, the size of the batch itself)
  264. 5830 requests_limit = [@max_requests, @requests.size].min
  265. 5830 if request == @requests[requests_limit - 1]
  266. 5202 "close"
  267. else
  268. 628 "keep-alive"
  269. end
  270. end
  271. 5427 extra_headers["connection"] = connection_value
  272. end
  273. 6017 extra_headers["host"] = request.authority unless request.headers.key?("host")
  274. 6017 extra_headers
  275. end
  276. 30 def handle(request)
  277. 7527 catch(:buffer_full) do
  278. 7527 request.transition(:headers)
  279. 7518 join_headers(request) if request.state == :headers
  280. 7518 request.transition(:body)
  281. 7518 join_body(request) if request.state == :body
  282. 6217 request.transition(:trailers)
  283. # HTTP/1.1 trailers should only work for chunked encoding
  284. 6217 join_trailers(request) if request.body.chunked? && request.state == :trailers
  285. 6217 request.transition(:done)
  286. end
  287. end
  288. 30 def join_headline(request)
  289. 5371 "#{request.verb} #{request.path} HTTP/#{@version.join(".")}"
  290. end
  291. 30 def join_headers(request)
  292. 6017 headline = join_headline(request)
  293. 6017 @buffer << headline << CRLF
  294. 6071 log(color: :yellow) { "<- HEADLINE: #{headline.chomp.inspect}" }
  295. 6017 extra_headers = set_protocol_headers(request)
  296. 6017 join_headers2(request.headers.each(extra_headers))
  297. 6071 log { "<- " }
  298. 6017 @buffer << CRLF
  299. end
  300. 30 def join_body(request)
  301. 7300 return if request.body.empty?
  302. 7832 while (chunk = request.drain_body)
  303. 3838 log(color: :green) { "<- DATA: #{chunk.bytesize} bytes..." }
  304. 3838 log(level: 2, color: :green) { "<- #{log_redact_body(chunk.inspect)}" }
  305. 3838 @buffer << chunk
  306. 3838 throw(:buffer_full, request) if @buffer.full?
  307. end
  308. 1826 return unless (error = request.drain_error)
  309. raise error
  310. end
  311. 30 def join_trailers(request)
  312. 108 return unless request.trailers? && request.callbacks_for?(:trailers)
  313. 36 join_headers2(request.trailers)
  314. 36 log { "<- " }
  315. 36 @buffer << CRLF
  316. end
  317. 30 def join_headers2(headers)
  318. 6053 headers.each do |field, value|
  319. 36941 field = capitalized(field)
  320. 37211 log(color: :yellow) { "<- HEADER: #{[field, log_redact_headers(value)].join(": ")}" }
  321. 36941 @buffer << "#{field}: #{value}#{CRLF}"
  322. end
  323. end
  324. 30 def capitalized(field)
  325. 36941 UPCASED[field] || field.split("-").map(&:capitalize).join("-")
  326. end
  327. end
  328. end

lib/httpx/connection/http2.rb

93.48% lines covered

276 relevant lines. 258 lines covered and 18 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 require "securerandom"
  3. 30 require "http/2"
  4. 30 module HTTPX
  5. 30 class Connection::HTTP2
  6. 30 include Callbacks
  7. 30 include Loggable
  8. 30 MAX_CONCURRENT_REQUESTS = ::HTTP2::DEFAULT_MAX_CONCURRENT_STREAMS
  9. 30 class Error < Error
  10. 30 def initialize(id, error)
  11. 93 super("stream #{id} closed with error: #{error}")
  12. end
  13. end
  14. 30 class PingError < Error
  15. 30 def initialize
  16. super(0, :ping_error)
  17. end
  18. end
  19. 30 class GoawayError < Error
  20. 30 def initialize(code = :no_error)
  21. 65 super(0, code)
  22. end
  23. end
  24. 30 attr_reader :streams, :pending
  25. 30 def initialize(buffer, options)
  26. 4168 @options = options
  27. 4168 @settings = @options.http2_settings
  28. 4168 @pending = []
  29. 4168 @streams = {}
  30. 4168 @drains = {}
  31. 4168 @pings = []
  32. 4168 @buffer = buffer
  33. 4168 @handshake_completed = false
  34. 4168 @wait_for_handshake = @settings.key?(:wait_for_handshake) ? @settings.delete(:wait_for_handshake) : true
  35. 4168 @max_concurrent_requests = @options.max_concurrent_requests || MAX_CONCURRENT_REQUESTS
  36. 4168 @max_requests = @options.max_requests
  37. 4168 init_connection
  38. end
  39. 30 def timeout
  40. 8224 return @options.timeout[:operation_timeout] if @handshake_completed
  41. 4116 @options.timeout[:settings_timeout]
  42. end
  43. 30 def interests
  44. 112975 if @connection.state == :closed
  45. 10510 return unless @handshake_completed
  46. 10431 return if @buffer.empty?
  47. 6082 return :w
  48. end
  49. 102465 unless @connection.state == :connected && @handshake_completed
  50. 22881 return @buffer.empty? ? :r : :rw
  51. end
  52. 77006 unless @connection.send_buffer.empty?
  53. 22 return :rw unless @buffer.empty?
  54. # waiting for WINDOW_UPDATE frames
  55. 4 return :r
  56. end
  57. 76984 return :w if !@pending.empty? && can_buffer_more_requests?
  58. 76984 return :w unless @drains.empty?
  59. 72416 if @buffer.empty?
  60. 60651 return if @streams.empty? && @pings.empty?
  61. 57052 :r
  62. else
  63. 11765 :w
  64. end
  65. end
  66. 30 def close
  67. 3394 unless @connection.state == :closed
  68. 3385 @connection.goaway
  69. 3385 emit(:timeout, @options.timeout[:close_handshake_timeout])
  70. end
  71. 3394 emit(:close)
  72. end
  73. 30 def empty?
  74. 3406 @connection.state == :closed || @streams.empty?
  75. end
  76. 30 def exhausted?
  77. 3992 !@max_requests.positive?
  78. end
  79. 30 def <<(data)
  80. 41879 @connection << data
  81. end
  82. 30 def send(request, head = false)
  83. 9136 unless can_buffer_more_requests?
  84. 4437 head ? @pending.unshift(request) : @pending << request
  85. 4437 return false
  86. end
  87. 4699 unless (stream = @streams[request])
  88. 4699 stream = @connection.new_stream
  89. 4699 handle_stream(stream, request)
  90. 4238 @streams[request] = stream
  91. 4238 @max_requests -= 1
  92. end
  93. 4699 handle(request, stream)
  94. 4681 true
  95. rescue ::HTTP2::Error::StreamLimitExceeded
  96. @pending.unshift(request)
  97. false
  98. end
  99. 30 def consume
  100. 27795 @streams.each do |request, stream|
  101. 12687 next unless request.can_buffer?
  102. 1310 handle(request, stream)
  103. end
  104. end
  105. 30 def handle_error(ex, request = nil)
  106. 511 if ex.is_a?(OperationTimeoutError) && !@handshake_completed && @connection.state != :closed
  107. 22 @connection.goaway(:settings_timeout, "closing due to settings timeout")
  108. 22 emit(:close_handshake)
  109. 22 settings_ex = SettingsTimeoutError.new(ex.timeout, ex.message)
  110. 22 settings_ex.set_backtrace(ex.backtrace)
  111. 22 ex = settings_ex
  112. end
  113. 511 @streams.each_key do |req|
  114. 441 next if request && request == req
  115. 54 emit(:error, req, ex)
  116. end
  117. 1002 while (req = @pending.shift)
  118. 90 next if request && request == req
  119. 90 emit(:error, req, ex)
  120. end
  121. end
  122. 30 def ping
  123. 22 ping = SecureRandom.gen_random(8)
  124. 22 @connection.ping(ping.dup)
  125. ensure
  126. 22 @pings << ping
  127. end
  128. 30 def waiting_for_ping?
  129. 473 @pings.any?
  130. end
  131. 30 def reset_requests; end
  132. 30 private
  133. 30 def can_buffer_more_requests?
  134. 10066 (@handshake_completed || !@wait_for_handshake) &&
  135. @streams.size < @max_concurrent_requests &&
  136. @streams.size < @max_requests
  137. end
  138. 30 def send_pending
  139. 11182 while (request = @pending.shift)
  140. 4280 break unless send(request, true)
  141. end
  142. end
  143. 30 def handle(request, stream)
  144. 6324 catch(:buffer_full) do
  145. 6324 request.transition(:headers)
  146. 6315 join_headers(stream, request) if request.state == :headers
  147. 6315 request.transition(:body)
  148. 6315 join_body(stream, request) if request.state == :body
  149. 4780 request.transition(:trailers)
  150. 4780 join_trailers(stream, request) if request.state == :trailers && !request.body.empty?
  151. 4780 request.transition(:done)
  152. end
  153. end
  154. 30 def init_connection
  155. 4168 @connection = ::HTTP2::Client.new(@settings)
  156. 4168 @connection.on(:frame, &method(:on_frame))
  157. 4168 @connection.on(:frame_sent, &method(:on_frame_sent))
  158. 4168 @connection.on(:frame_received, &method(:on_frame_received))
  159. 4168 @connection.on(:origin, &method(:on_origin))
  160. 4168 @connection.on(:promise, &method(:on_promise))
  161. 4168 @connection.on(:altsvc) { |frame| on_altsvc(frame[:origin], frame) }
  162. 4168 @connection.on(:settings_ack, &method(:on_settings))
  163. 4168 @connection.on(:ack, &method(:on_pong))
  164. 4168 @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. 4168 @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. 4717 request.on(:refuse, &method(:on_stream_refuse).curry(3)[stream, request])
  177. 4717 stream.on(:close, &method(:on_stream_close).curry(3)[stream, request])
  178. 9361 stream.on(:half_close) { on_stream_half_close(stream, request) }
  179. 4717 stream.on(:altsvc, &method(:on_altsvc).curry(2)[request.origin])
  180. 4717 stream.on(:headers, &method(:on_stream_headers).curry(3)[stream, request])
  181. 4717 stream.on(:data, &method(:on_stream_data).curry(3)[stream, request])
  182. end
  183. 30 def set_protocol_headers(request)
  184. 460 {
  185. 4229 ":scheme" => request.scheme,
  186. ":method" => request.verb,
  187. ":path" => request.path,
  188. ":authority" => request.authority,
  189. }
  190. end
  191. 30 def join_headers(stream, request)
  192. 4690 extra_headers = set_protocol_headers(request)
  193. 4690 if request.headers.key?("host")
  194. 9 log { "forbidden \"host\" header found (#{log_redact_headers(request.headers["host"])}), will use it as authority..." }
  195. 8 extra_headers[":authority"] = request.headers["host"]
  196. end
  197. 4690 log(level: 1, color: :yellow) do
  198. 146 "\n#{request.headers.merge(extra_headers).each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{log_redact_headers(v)}" }.join("\n")}"
  199. end
  200. 4690 stream.headers(request.headers.each(extra_headers), end_stream: request.body.empty?)
  201. end
  202. 30 def join_trailers(stream, request)
  203. 1778 unless request.trailers?
  204. 1769 stream.data("", end_stream: true) if request.callbacks_for?(:trailers)
  205. 1604 return
  206. end
  207. 9 log(level: 1, color: :yellow) do
  208. 17 request.trailers.each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{log_redact_headers(v)}" }.join("\n")
  209. end
  210. 9 stream.headers(request.trailers.each, end_stream: true)
  211. end
  212. 30 def join_body(stream, request)
  213. 6137 return if request.body.empty?
  214. 3315 chunk = @drains.delete(request) || request.drain_body
  215. 3514 while chunk
  216. 3597 next_chunk = request.drain_body
  217. 3597 send_chunk(request, stream, chunk, next_chunk)
  218. 3256 if next_chunk && (@buffer.full? || request.body.unbounded_body?)
  219. 1066 @drains[request] = next_chunk
  220. 1194 throw(:buffer_full)
  221. end
  222. 2062 chunk = next_chunk
  223. end
  224. 1780 return unless (error = request.drain_error)
  225. 28 on_stream_refuse(stream, request, error)
  226. end
  227. 30 def send_chunk(request, stream, chunk, next_chunk)
  228. 3621 log(level: 1, color: :green) { "#{stream.id}: -> DATA: #{chunk.bytesize} bytes..." }
  229. 3621 log(level: 2, color: :green) { "#{stream.id}: -> #{log_redact_body(chunk.inspect)}" }
  230. 3597 stream.data(chunk, end_stream: end_stream?(request, next_chunk))
  231. end
  232. 30 def end_stream?(request, next_chunk)
  233. 3224 !(next_chunk || request.trailers? || request.callbacks_for?(:trailers))
  234. end
  235. ######
  236. # HTTP/2 Callbacks
  237. ######
  238. 30 def on_stream_headers(stream, request, h)
  239. 4440 response = request.response
  240. 4440 if response.is_a?(Response) && response.version == "2.0"
  241. 133 on_stream_trailers(stream, response, h)
  242. 133 return
  243. end
  244. 4307 log(color: :yellow) do
  245. 146 h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{k == ":status" ? v : log_redact_headers(v)}" }.join("\n")
  246. end
  247. 4307 _, status = h.shift
  248. 4307 headers = request.options.headers_class.new(h)
  249. 4307 response = request.options.response_class.new(request, status, "2.0", headers)
  250. 4307 request.response = response
  251. 3878 @streams[request] = stream
  252. 4298 handle(request, stream) if request.expects?
  253. end
  254. 30 def on_stream_trailers(stream, response, h)
  255. 133 log(color: :yellow) do
  256. h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{log_redact_headers(v)}" }.join("\n")
  257. end
  258. 133 response.merge_headers(h)
  259. end
  260. 30 def on_stream_data(stream, request, data)
  261. 8090 log(level: 1, color: :green) { "#{stream.id}: <- DATA: #{data.bytesize} bytes..." }
  262. 8090 log(level: 2, color: :green) { "#{stream.id}: <- #{log_redact_body(data.inspect)}" }
  263. 8065 request.response << data
  264. end
  265. 30 def on_stream_refuse(stream, request, error)
  266. 28 on_stream_close(stream, request, error)
  267. 28 stream.close
  268. end
  269. 30 def on_stream_half_close(stream, _request)
  270. 4644 unless stream.send_buffer.empty?
  271. 1 stream.send_buffer.clear
  272. 1 stream.data("", end_stream: true)
  273. end
  274. # TODO: omit log line if response already here
  275. 4660 log(level: 2) { "#{stream.id}: waiting for response..." }
  276. end
  277. 30 def on_stream_close(stream, request, error)
  278. 4202 return if error == :stream_closed && !@streams.key?(request)
  279. 4190 log(level: 2) { "#{stream.id}: closing stream" }
  280. 4174 teardown(request)
  281. 4174 if error
  282. 28 case error
  283. when :http_1_1_required
  284. emit(:error, request, error)
  285. else
  286. 28 ex = Error.new(stream.id, error)
  287. 28 ex.set_backtrace(caller)
  288. 28 response = ErrorResponse.new(request, ex)
  289. 28 request.response = response
  290. 28 emit(:response, request, response)
  291. end
  292. else
  293. 4146 response = request.response
  294. 4146 if response && response.is_a?(Response) && response.status == 421
  295. 9 emit(:error, request, :http_1_1_required)
  296. else
  297. 4137 emit(:response, request, response)
  298. end
  299. end
  300. 4165 send(@pending.shift) unless @pending.empty?
  301. 4165 return unless @streams.empty? && exhausted?
  302. 9 if @pending.empty?
  303. close
  304. else
  305. 9 emit(:exhausted)
  306. end
  307. end
  308. 30 def on_frame(bytes)
  309. 25640 @buffer << bytes
  310. end
  311. 30 def on_settings(*)
  312. 4108 @handshake_completed = true
  313. 4108 emit(:current_timeout)
  314. 4108 @max_concurrent_requests = [@max_concurrent_requests, @connection.remote_settings[:settings_max_concurrent_streams]].min
  315. 4108 send_pending
  316. end
  317. 30 def on_close(_last_frame, error, _payload)
  318. 74 is_connection_closed = @connection.state == :closed
  319. 74 if error
  320. 74 @buffer.clear if is_connection_closed
  321. 66 case error
  322. when :http_1_1_required
  323. 24 while (request = @pending.shift)
  324. 9 emit(:error, request, error)
  325. end
  326. else
  327. 65 ex = GoawayError.new(error)
  328. 65 ex.set_backtrace(caller)
  329. 65 @pending.unshift(*@streams.keys)
  330. 65 teardown
  331. 65 handle_error(ex)
  332. end
  333. end
  334. 74 return unless is_connection_closed && @streams.empty?
  335. 74 emit(:close) if is_connection_closed
  336. end
  337. 30 def on_frame_sent(frame)
  338. 21560 log(level: 2) { "#{frame[:stream]}: frame was sent!" }
  339. 21560 log(level: 2, color: :blue) { "#{frame[:stream]}: #{frame_with_extra_info(frame)}" }
  340. end
  341. 30 def on_frame_received(frame)
  342. 22464 log(level: 2) { "#{frame[:stream]}: frame was received!" }
  343. 22464 log(level: 2, color: :magenta) { "#{frame[:stream]}: #{frame_with_extra_info(frame)}" }
  344. end
  345. 30 def frame_with_extra_info(frame)
  346. 189 case frame[:type]
  347. when :data
  348. 54 frame.merge(payload: frame[:payload].bytesize)
  349. when :headers, :ping
  350. 45 frame.merge(payload: log_redact_headers(frame[:payload]))
  351. when :window_update
  352. connection_or_stream = if (id = frame[:stream]).zero?
  353. @connection
  354. else
  355. @streams.each_value.find { |s| s.id == id }
  356. end
  357. if connection_or_stream
  358. frame.merge(
  359. local_window: connection_or_stream.local_window,
  360. remote_window: connection_or_stream.remote_window,
  361. buffered_amount: connection_or_stream.buffered_amount,
  362. stream_state: connection_or_stream.state,
  363. )
  364. else
  365. frame
  366. end
  367. else
  368. 90 frame
  369. end.merge(connection_state: @connection.state)
  370. end
  371. 30 def on_altsvc(origin, frame)
  372. log(level: 2) { "#{frame[:stream]}: altsvc frame was received" }
  373. log(level: 2) { "#{frame[:stream]}: #{log_redact_headers(frame.inspect)}" }
  374. alt_origin = URI.parse("#{frame[:proto]}://#{frame[:host]}:#{frame[:port]}")
  375. params = { "ma" => frame[:max_age] }
  376. emit(:altsvc, origin, alt_origin, origin, params)
  377. end
  378. 30 def on_promise(stream)
  379. 27 emit(:promise, @streams.key(stream.parent), stream)
  380. end
  381. 30 def on_origin(origin)
  382. emit(:origin, origin)
  383. end
  384. 30 def on_pong(ping)
  385. 9 raise PingError unless @pings.delete(ping.to_s)
  386. 9 emit(:pong)
  387. end
  388. 30 def teardown(request = nil)
  389. 4239 if request
  390. 4174 @drains.delete(request)
  391. 4174 @streams.delete(request)
  392. else
  393. 65 @drains.clear
  394. 65 @streams.clear
  395. end
  396. end
  397. end
  398. 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. 936 @timeout = timeout
  16. 936 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. 765 @request = request
  40. 765 @response = response
  41. 765 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. 161 @connection = connection
  68. 161 @host = host
  69. 161 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. 20 if size < arr.size
  10. smaller = self
  11. else
  12. 20 smaller, arr = arr, self
  13. end
  14. 20 (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. 840 @non_ascii_hostname
  24. end
  25. 30 def non_ascii_hostname=(hostname)
  26. 36 @non_ascii_hostname = hostname
  27. end
  28. def authority
  29. 6376 return host if port == default_port
  30. 717 "#{host}:#{port}"
  31. 29 end unless URI::HTTP.method_defined?(:authority)
  32. def origin
  33. 5190 "#{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. 32635 return headers if headers.is_a?(self)
  7. 14118 super
  8. end
  9. end
  10. 30 def initialize(headers = nil)
  11. 14118 if headers.nil? || headers.empty?
  12. 2139 @headers = headers.to_h
  13. 1928 return
  14. end
  15. 11979 @headers = {}
  16. 11979 headers.each do |field, value|
  17. 74388 field = downcased(field)
  18. 74388 value = array_value(value)
  19. 74388 current = @headers[field]
  20. 74388 if current.nil?
  21. 67078 @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. 27580 super
  35. 27580 @headers = orig.instance_variable_get(:@headers).transform_values(&:dup)
  36. end
  37. # freezes the headers hash
  38. 30 def freeze
  39. 27567 @headers.each_value(&:freeze).freeze
  40. 27567 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. 6058 headers = dup
  48. 6058 other.each do |field, value|
  49. 15326 headers[downcased(field)] = value
  50. end
  51. 6058 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. 76782 a = @headers[downcased(field)] || return
  58. 31910 a.join(", ")
  59. end
  60. # sets +value+ (if not nil) as single value for the +field+ header.
  61. #
  62. 30 def []=(field, value)
  63. 29892 return unless value
  64. 27227 @headers[downcased(field)] = array_value(value)
  65. end
  66. # deletes all values associated with +field+ header.
  67. #
  68. 30 def delete(field)
  69. 379 canonical = downcased(field)
  70. 379 @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. 1788 (@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. 45352 return enum_for(__method__, extra_headers) { @headers.size } unless block_given?
  90. 25473 @headers.each do |field, value|
  91. 93463 yield(field, value.join(", ")) unless value.empty?
  92. end
  93. 6731 extra_headers.each do |field, value|
  94. 30865 yield(field, value) unless value.empty?
  95. 25472 end if extra_headers
  96. end
  97. 30 def ==(other)
  98. 6644 other == to_hash
  99. end
  100. 30 def empty?
  101. 414 @headers.empty?
  102. end
  103. # the headers store in Hash format
  104. 30 def to_hash
  105. 8885 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. 8911 Array(each)
  111. end
  112. # headers as string
  113. 30 def to_s
  114. 2405 @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. 93742 @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. 395 @headers[field] || EMPTY
  135. end
  136. 30 private
  137. 30 def array_value(value)
  138. 104280 Array(value)
  139. end
  140. 30 def downcased(field)
  141. 199950 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. 3717 super
  16. 3717 @ssl_session = nil
  17. 3717 ctx_options = TLS_OPTIONS.merge(options.ssl)
  18. 3717 @sni_hostname = ctx_options.delete(:hostname) || @hostname
  19. 3717 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. 3692 @ctx = OpenSSL::SSL::SSLContext.new
  25. 3692 @ctx.set_params(ctx_options) unless ctx_options.empty?
  26. 3692 unless @ctx.session_cache_mode.nil? # a dummy method on JRuby
  27. 3338 @ctx.session_cache_mode =
  28. OpenSSL::SSL::SSLContext::SESSION_CACHE_CLIENT | OpenSSL::SSL::SSLContext::SESSION_CACHE_NO_INTERNAL_STORE
  29. end
  30. 3692 yield(self) if block_given?
  31. end
  32. 3717 @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. 9692 @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. 3725 @io.alpn_protocol || super
  44. rescue StandardError
  45. 15 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. 399 proto = @io.alpn_protocol
  52. 398 return super if proto.nil? || proto.empty?
  53. 395 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. 16306 @state == :negotiated
  68. end
  69. 30 def ssl_session_expired?
  70. 4077 @ssl_session.nil? || Process.clock_gettime(Process::CLOCK_REALTIME) >= (@ssl_session.time.to_f + @ssl_session.timeout)
  71. end
  72. 30 def connect
  73. 16374 return if @state == :negotiated
  74. 16374 unless @state == :connected
  75. 9118 super
  76. 9077 return unless @state == :connected
  77. end
  78. 11217 unless @io.is_a?(OpenSSL::SSL::SSLSocket)
  79. 4077 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. 4077 @io = OpenSSL::SSL::SSLSocket.new(@io, @ctx)
  86. 4077 @io.hostname = @sni_hostname unless hostname_is_ip
  87. 4077 @io.session = @ssl_session unless ssl_session_expired?
  88. 4077 @io.sync_close = true
  89. end
  90. 11217 try_ssl_connect
  91. end
  92. 30 def try_ssl_connect
  93. 11217 ret = @io.connect_nonblock(exception: false)
  94. 11240 log(level: 3, color: :cyan) { "TLS CONNECT: #{ret}..." }
  95. 10452 case ret
  96. when :wait_readable
  97. 7167 @interests = :r
  98. 7167 return
  99. when :wait_writable
  100. @interests = :w
  101. return
  102. end
  103. 4024 @io.post_connection_check(@sni_hostname) if @ctx.verify_mode != OpenSSL::SSL::VERIFY_NONE && @verify_hostname
  104. 4023 transition(:negotiated)
  105. 4023 @interests = :w
  106. end
  107. 30 private
  108. 30 def transition(nextstate)
  109. 14364 case nextstate
  110. when :negotiated
  111. 4023 return unless @state == :connected
  112. when :closed
  113. 3948 return unless @state == :negotiated ||
  114. @state == :connected
  115. end
  116. 15962 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. 8732 @state = :idle
  11. 8732 @keep_open = false
  12. 8732 @addresses = []
  13. 8732 @ip_index = -1
  14. 8732 @ip = nil
  15. 8732 @hostname = origin.host
  16. 8732 @options = options
  17. 8732 @fallback_protocol = @options.fallback_protocol
  18. 8732 @port = origin.port
  19. 8732 @interests = :w
  20. 8732 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. 8673 add_addresses(addresses)
  35. end
  36. 8732 @ip_index = @addresses.size - 1
  37. end
  38. 30 def socket
  39. 219 @io
  40. end
  41. 30 def add_addresses(addrs)
  42. 9139 return if addrs.empty?
  43. 9130 ip_index = @ip_index || (@addresses.size - 1)
  44. 9130 if addrs.first.ipv6?
  45. # should be the next in line
  46. 409 @addresses = [*@addresses[0, ip_index], *addrs, *@addresses[ip_index..-1]]
  47. else
  48. 8721 @addresses.unshift(*addrs)
  49. end
  50. 8240 @ip_index += addrs.size
  51. end
  52. # eliminates expired entries and returns whether there are still any left.
  53. 30 def addresses?
  54. 1066 prev_addr_size = @addresses.size
  55. 1066 @addresses.delete_if(&:expired?).sort! do |addr1, addr2|
  56. 1634 if addr1.ipv6?
  57. 4 addr2.ipv6? ? 0 : 1
  58. else
  59. 1630 addr2.ipv6? ? -1 : 0
  60. end
  61. end
  62. 1066 @ip_index = @addresses.size - 1 if prev_addr_size != @addresses.size
  63. 1066 @addresses.any?
  64. end
  65. 30 def to_io
  66. 33644 @io.to_io
  67. end
  68. 30 def protocol
  69. 5572 @fallback_protocol
  70. end
  71. 30 def connect
  72. 21839 return unless closed?
  73. 21696 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. 21696 if !@io || @io.closed?
  83. 9754 transition(:idle)
  84. 9754 @io = build_socket
  85. end
  86. 21696 try_connect
  87. rescue Errno::EHOSTUNREACH,
  88. Errno::ENETUNREACH => e
  89. 34 @ip_index -= 1
  90. 34 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. 1064 @ip_index -= 1
  100. 1085 raise e if @ip_index.negative?
  101. 1021 log { "failed connecting to #{@ip} (#{e.message}), trying next..." }
  102. 1007 @io = build_socket
  103. 1007 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. 21696 ret = @io.connect_nonblock(Socket.sockaddr_in(@port, @ip.to_s), exception: false)
  113. 20577 log(level: 3, color: :cyan) { "TCP CONNECT: #{ret}..." }
  114. 18440 case ret
  115. when :wait_readable
  116. @interests = :r
  117. return
  118. when :wait_writable
  119. 10769 @interests = :w
  120. 10769 return
  121. end
  122. 9636 transition(:connected)
  123. 9636 @interests = :w
  124. rescue Errno::EALREADY
  125. 172 @interests = :w
  126. end
  127. 30 private :try_connect
  128. 30 def read(size, buffer)
  129. 67641 ret = @io.read_nonblock(size, buffer, exception: false)
  130. 67639 if ret == :wait_readable
  131. 17000 buffer.clear
  132. 15756 return 0
  133. end
  134. 50639 return if ret.nil?
  135. 50739 log { "READ: #{buffer.bytesize} bytes..." }
  136. 50619 buffer.bytesize
  137. end
  138. 30 def write(buffer)
  139. 23287 siz = @io.write_nonblock(buffer, exception: false)
  140. 23273 return 0 if siz == :wait_writable
  141. 23255 return if siz.nil?
  142. 23363 log { "WRITE: #{siz} bytes..." }
  143. 23255 buffer.shift!(siz)
  144. 23255 siz
  145. end
  146. 30 def close
  147. 11071 return if @keep_open || closed?
  148. 965 begin
  149. 9539 @io.close
  150. ensure
  151. 9539 transition(:closed)
  152. end
  153. end
  154. 30 def connected?
  155. 11659 @state == :connected
  156. end
  157. 30 def closed?
  158. 32988 @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. 10783 @ip = @addresses[@ip_index]
  173. 10783 Socket.new(@ip.family, :STREAM, 0)
  174. end
  175. 30 def transition(nextstate)
  176. 15281 case nextstate
  177. # when :idle
  178. when :connected
  179. 5691 return unless @state == :idle
  180. when :closed
  181. 5591 return unless @state == :connected
  182. end
  183. 17014 do_transition(nextstate)
  184. end
  185. 30 def do_transition(nextstate)
  186. 33224 log(level: 1) { log_transition_state(nextstate) }
  187. 32976 @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. 1620 @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. 51 siz = @io.send(buffer.to_s, 0, @host, @port)
  26. 51 log { "WRITE: #{siz} bytes..." }
  27. 51 buffer.shift!(siz)
  28. 51 siz
  29. end
  30. else
  31. 29 def write(buffer)
  32. 792 siz = @io.sendmsg_nonblock(buffer.to_s, 0, Socket.sockaddr_in(@port, @host.to_s), exception: false)
  33. 792 return 0 if siz == :wait_writable
  34. 792 return if siz.nil?
  35. 792 log { "WRITE: #{siz} bytes..." }
  36. 792 buffer.shift!(siz)
  37. 792 siz
  38. end
  39. end
  40. 30 def read(size, buffer)
  41. 1595 ret = @io.recvfrom_nonblock(size, 0, buffer, exception: false)
  42. 1595 return 0 if ret == :wait_readable
  43. 768 return if ret.nil?
  44. 768 log { "READ: #{buffer.bytesize} bytes..." }
  45. 768 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. 874840 return unless debug_level >= level
  24. 343601 debug_stream = debug || ($stderr if USE_DEBUG_LOG)
  25. 343601 return unless debug_stream
  26. 4979 klass = self.class
  27. 10896 until (class_name = klass.name)
  28. 1933 klass = klass.superclass
  29. end
  30. 4979 message = +"(time:#{Time.now.utc}, pid:#{Process.pid}, " \
  31. 498 "tid:#{Thread.current.object_id}, " \
  32. 498 "fid:#{Fiber.current.object_id}, " \
  33. 498 "self:#{class_name}##{object_id}) "
  34. 4979 message << msg.call << "\n"
  35. 4979 message = "\e[#{COLORS[color]}m#{message}\e[0m" if color && debug_stream.respond_to?(:isatty) && debug_stream.isatty
  36. 4979 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. 1848 log(level: level, color: color, debug_level: debug_level, debug: debug) { ex.full_message }
  40. end
  41. 30 def log_redact_headers(text)
  42. 1026 log_redact(text, @options.debug_redact == :headers)
  43. end
  44. 30 def log_redact_body(text)
  45. 108 log_redact(text, @options.debug_redact == :body)
  46. end
  47. 30 def log_redact(text, should_redact)
  48. 1134 should_redact ||= @options.debug_redact == true
  49. 1134 return text.to_s unless should_redact
  50. 252 "[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. 16011 return options if self == Options && options.class < self
  27. 11459 return options if options.is_a?(self)
  28. 6689 super
  29. end
  30. 30 def freeze
  31. 17623 @options_names.freeze
  32. 17623 super
  33. end
  34. 30 def method_added(meth)
  35. 36478 super
  36. 36478 return unless meth =~ /^option_(.+)$/
  37. 15662 optname = Regexp.last_match(1) #: String
  38. 15662 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. 15662 optname = optname.to_sym
  48. 15662 attr_reader(optname) unless method_defined?(optname)
  49. 15662 @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. 6689 options_names = self.class.options_names
  107. 1331 defaults =
  108. 5358 case options
  109. when Options
  110. 4925 unknown_options = options.class.options_names - options_names
  111. 4925 raise Error, "unknown option: #{unknown_options.first}" unless unknown_options.empty?
  112. 4925 DEFAULT_OPTIONS.merge(options)
  113. else
  114. 1764 options.each_key do |k|
  115. 12054 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. 6680 options_names.each do |k|
  120. 294498 v = defaults[k]
  121. 294498 if v.nil?
  122. 72202 instance_variable_set(:"@#{k}", v)
  123. 72202 next
  124. end
  125. 222296 value = __send__(:"option_#{k}", v)
  126. 222252 instance_variable_set(:"@#{k}", value)
  127. end
  128. 6636 do_initialize
  129. 6636 freeze
  130. end
  131. # returns the class with which to instantiate the DNS resolver.
  132. 30 def resolver_class
  133. 18729 case @resolver_class
  134. when Symbol
  135. 16125 public_send(:"resolver_#{@resolver_class}_class")
  136. else
  137. 4419 @resolver_class
  138. end
  139. end
  140. 30 def resolver_cache
  141. 19318 cache_type = @resolver_cache
  142. 17502 case cache_type
  143. when :memory
  144. 15109 Resolver::Cache::Memory.cache(cache_type)
  145. when :file
  146. Resolver::Cache::File.cache(cache_type)
  147. else
  148. 4209 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. 4209 cache_type #: Object & Resolver::_Cache
  155. end
  156. end
  157. 30 def freeze
  158. 17562 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. 775748 next if ivar == :debug
  166. 758186 instance_variable_get(:"@#{ivar}").freeze
  167. end
  168. 17562 super
  169. end
  170. 30 REQUEST_BODY_IVARS = %i[@headers].freeze
  171. 30 def ==(other)
  172. 2667 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. 570 ivars = instance_variables - ignore_ivars
  179. 570 other_ivars = other.instance_variables - ignore_ivars
  180. 570 return false if ivars.size != other_ivars.size
  181. 570 return false if ivars.sort != other_ivars.sort
  182. 570 ivars.all? do |ivar|
  183. 23420 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. 46581 if (is_options = other.is_a?(Options))
  190. 14179 return self if eql?(other)
  191. 3885 opts_names = other.class.options_names
  192. 129602 return self if opts_names.all? { |opt| public_send(opt) == other.public_send(opt) }
  193. 3614 other_opts = opts_names
  194. else
  195. 32402 other_opts = other # : Hash[Symbol, untyped]
  196. 32402 other_opts = Hash[other] unless other.is_a?(Hash)
  197. 32394 return self if other_opts.empty?
  198. 30855 return self if other_opts.all? { |opt, v| !respond_to?(opt) || public_send(opt) == v }
  199. end
  200. 17573 opts = dup
  201. 17573 other_opts.each do |opt, v|
  202. 188246 next unless respond_to?(opt)
  203. 188246 v = other.public_send(opt) if is_options
  204. 188246 ivar = :"@#{opt}"
  205. 188246 unless v
  206. 49707 opts.instance_variable_set(ivar, v)
  207. 49707 next
  208. end
  209. 138539 v = opts.__send__(:"option_#{opt}", v)
  210. 138521 orig_v = public_send(opt)
  211. 138521 v = orig_v.merge(v) if orig_v.respond_to?(:merge) && v.respond_to?(:merge)
  212. 138521 opts.instance_variable_set(ivar, v)
  213. end
  214. 17555 opts
  215. end
  216. 30 def to_hash
  217. 5450 instance_variables.each_with_object({}) do |ivar, hs|
  218. 230139 val = instance_variable_get(ivar)
  219. 230139 next if val.nil?
  220. 164228 hs[ivar[1..-1].to_sym] = val
  221. end
  222. end
  223. 30 def extend_with_plugin_classes(pl)
  224. # extend request class
  225. 10878 if defined?(pl::RequestMethods) || defined?(pl::RequestClassMethods)
  226. 4097 @request_class = @request_class.dup
  227. 4097 SET_TEMPORARY_NAME[@request_class, pl]
  228. 4097 @request_class.__send__(:include, pl::RequestMethods) if defined?(pl::RequestMethods)
  229. 4097 @request_class.extend(pl::RequestClassMethods) if defined?(pl::RequestClassMethods)
  230. end
  231. # extend response class
  232. 10878 if defined?(pl::ResponseMethods) || defined?(pl::ResponseClassMethods)
  233. 2997 @response_class = @response_class.dup
  234. 2997 SET_TEMPORARY_NAME[@response_class, pl]
  235. 2997 @response_class.__send__(:include, pl::ResponseMethods) if defined?(pl::ResponseMethods)
  236. 2997 @response_class.extend(pl::ResponseClassMethods) if defined?(pl::ResponseClassMethods)
  237. end
  238. # extend headers class
  239. 10878 if defined?(pl::HeadersMethods) || defined?(pl::HeadersClassMethods)
  240. 234 @headers_class = @headers_class.dup
  241. 234 SET_TEMPORARY_NAME[@headers_class, pl]
  242. 234 @headers_class.__send__(:include, pl::HeadersMethods) if defined?(pl::HeadersMethods)
  243. 234 @headers_class.extend(pl::HeadersClassMethods) if defined?(pl::HeadersClassMethods)
  244. end
  245. # extend request body class
  246. 10878 if defined?(pl::RequestBodyMethods) || defined?(pl::RequestBodyClassMethods)
  247. 451 @request_body_class = @request_body_class.dup
  248. 451 SET_TEMPORARY_NAME[@request_body_class, pl]
  249. 451 @request_body_class.__send__(:include, pl::RequestBodyMethods) if defined?(pl::RequestBodyMethods)
  250. 451 @request_body_class.extend(pl::RequestBodyClassMethods) if defined?(pl::RequestBodyClassMethods)
  251. end
  252. # extend response body class
  253. 10878 if defined?(pl::ResponseBodyMethods) || defined?(pl::ResponseBodyClassMethods)
  254. 1273 @response_body_class = @response_body_class.dup
  255. 1273 SET_TEMPORARY_NAME[@response_body_class, pl]
  256. 1273 @response_body_class.__send__(:include, pl::ResponseBodyMethods) if defined?(pl::ResponseBodyMethods)
  257. 1273 @response_body_class.extend(pl::ResponseBodyClassMethods) if defined?(pl::ResponseBodyClassMethods)
  258. end
  259. # extend connection pool class
  260. 10878 if defined?(pl::PoolMethods)
  261. 927 @pool_class = @pool_class.dup
  262. 927 SET_TEMPORARY_NAME[@pool_class, pl]
  263. 927 @pool_class.__send__(:include, pl::PoolMethods)
  264. end
  265. # extend connection class
  266. 10878 if defined?(pl::ConnectionMethods)
  267. 4653 @connection_class = @connection_class.dup
  268. 4653 SET_TEMPORARY_NAME[@connection_class, pl]
  269. 4653 @connection_class.__send__(:include, pl::ConnectionMethods)
  270. end
  271. # extend http1 class
  272. 10878 if defined?(pl::HTTP1Methods)
  273. 634 @http1_class = @http1_class.dup
  274. 634 SET_TEMPORARY_NAME[@http1_class, pl]
  275. 634 @http1_class.__send__(:include, pl::HTTP1Methods)
  276. end
  277. # extend http2 class
  278. 10878 if defined?(pl::HTTP2Methods)
  279. 715 @http2_class = @http2_class.dup
  280. 715 SET_TEMPORARY_NAME[@http2_class, pl]
  281. 715 @http2_class.__send__(:include, pl::HTTP2Methods)
  282. end
  283. # extend native resolver class
  284. 10878 if defined?(pl::ResolverNativeMethods)
  285. 1662 @resolver_native_class = @resolver_native_class.dup
  286. 1662 SET_TEMPORARY_NAME[@resolver_native_class, pl]
  287. 1662 @resolver_native_class.__send__(:include, pl::ResolverNativeMethods)
  288. end
  289. # extend system resolver class
  290. 10878 if defined?(pl::ResolverSystemMethods)
  291. 739 @resolver_system_class = @resolver_system_class.dup
  292. 739 SET_TEMPORARY_NAME[@resolver_system_class, pl]
  293. 739 @resolver_system_class.__send__(:include, pl::ResolverSystemMethods)
  294. end
  295. # extend https resolver class
  296. 10878 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. 10878 return unless defined?(pl::OptionsMethods)
  302. # extend option class
  303. # works around lack of initialize_dup callback
  304. 4925 @options_class = @options_class.dup
  305. # (self.class.options_names)
  306. 4925 @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. 11035 value = value.dup if value.frozen?
  353. 11035 headers_class.new(value)
  354. end
  355. 30 def option_timeout(value)
  356. 12501 timeout_hash = Hash[value]
  357. 12501 default_timeouts = DEFAULT_OPTIONS[:timeout]
  358. # Validate keys and values
  359. 12501 timeout_hash.each do |key, val|
  360. 85611 raise TypeError, "invalid timeout: :#{key}" unless default_timeouts.key?(key)
  361. 85602 next if val.nil?
  362. 65846 raise TypeError, ":#{key} must be numeric" unless val.is_a?(Numeric)
  363. end
  364. 12483 timeout_hash
  365. end
  366. 30 def option_supported_compression_formats(value)
  367. 10467 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. 9965 case resolver_type
  382. when Symbol
  383. 7130 meth = :"resolver_#{resolver_type}_class"
  384. 7130 raise TypeError, ":resolver_class must be a supported type" unless respond_to?(meth)
  385. 7121 resolver_type
  386. when Class
  387. 3833 raise TypeError, ":resolver_class must be a subclass of `#{Resolver::Resolver}`" unless resolver_type < Resolver::Resolver
  388. 3825 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. 10422 if cache_type.is_a?(Symbol)
  395. 6682 raise TypeError, ":resolver_cache: #{cache_type} is invalid" unless RESOLVER_TYPES.include?(cache_type)
  396. 6682 require "httpx/resolver/cache/file" if cache_type == :file
  397. else
  398. 3740 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. 10422 cache_type
  406. end
  407. # called after all options are initialized
  408. 30 def do_initialize
  409. 6636 hs = @headers
  410. # initialized default request headers
  411. 6636 hs["user-agent"] = USER_AGENT unless hs.key?("user-agent")
  412. 6636 hs["accept"] = "*/*" unless hs.key?("accept")
  413. 6636 if hs.key?("range")
  414. 9 hs.delete("accept-encoding")
  415. else
  416. 6627 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. 19493 if klass.respond_to?(:set_temporary_name) # ruby 3.4 only
  431. 10237 name = klass.name || "#{klass.superclass.name}(plugin)"
  432. 10237 name = "#{name}/#{pl}" if pl
  433. 10237 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. 5663 @observer = observer
  10. 5663 @state = :idle
  11. 5663 @buffer = "".b
  12. 5663 @headers = {}
  13. end
  14. 30 def <<(chunk)
  15. 8588 @buffer << chunk
  16. 8588 parse
  17. end
  18. 30 def reset!
  19. 11159 @state = :idle
  20. 11159 @headers = {}
  21. 11159 @content_length = nil
  22. 11159 @_has_trailers = nil
  23. 11159 @buffer.clear
  24. end
  25. 30 def upgrade?
  26. 5459 @upgrade
  27. end
  28. 30 def upgrade_data
  29. 37 @buffer
  30. end
  31. 30 private
  32. 30 def parse
  33. 8588 loop do
  34. 18392 state = @state
  35. 16649 case @state
  36. when :idle
  37. 5864 parse_headline
  38. when :headers, :trailers
  39. 5965 parse_headers
  40. when :data
  41. 6561 parse_data
  42. end
  43. 13333 return if @buffer.empty? || state == @state
  44. end
  45. end
  46. 30 def parse_headline
  47. 5864 idx = @buffer.index("\n")
  48. 5864 return unless idx
  49. 5864 (m = %r{\AHTTP(?:/(\d+\.\d+))?\s+(\d\d\d)(?:\s+(.*))?}in.match(@buffer)) ||
  50. raise(Error, "wrong head line format")
  51. 5855 version, code, _ = m.captures
  52. 5855 raise(Error, "unsupported HTTP version (HTTP/#{version})") unless version && VERSIONS.include?(version)
  53. 5846 @http_version = version.split(".").map(&:to_i)
  54. 5846 @status_code = code.to_i
  55. 5846 raise(Error, "wrong status code (#{@status_code})") unless (100..599).cover?(@status_code)
  56. 5837 @buffer = @buffer.byteslice((idx + 1)..-1)
  57. 5837 nextstate(:headers)
  58. end
  59. 30 def parse_headers
  60. 5967 headers = @headers
  61. 5967 buffer = @buffer
  62. 47131 while (idx = buffer.index("\n"))
  63. # @type var line: String
  64. 45916 line = buffer.byteslice(0..idx)
  65. 45916 raise Error, "wrong header format" if line.start_with?("\s", "\t")
  66. 45907 line.lstrip!
  67. 45907 buffer = @buffer = buffer.byteslice((idx + 1)..-1)
  68. 45907 if line.empty?
  69. 5290 case @state
  70. when :headers
  71. 5819 prepare_data(headers)
  72. 5819 @observer.on_headers(headers)
  73. 5055 return unless @state == :headers
  74. # state might have been reset
  75. # in the :headers callback
  76. 4973 nextstate(:data)
  77. 4973 headers.clear
  78. when :trailers
  79. 18 @observer.on_trailers(headers)
  80. 18 headers.clear
  81. 18 nextstate(:complete)
  82. end
  83. 4982 return
  84. end
  85. 40070 separator_index = line.index(":")
  86. 40070 raise Error, "wrong header format" unless separator_index
  87. # @type var key: String
  88. 40061 key = line.byteslice(0..(separator_index - 1))
  89. 40061 key.rstrip! # was lstripped previously!
  90. # @type var value: String
  91. 40061 value = line.byteslice((separator_index + 1)..-1)
  92. 40061 value.strip!
  93. 40061 raise Error, "wrong header format" if value.nil?
  94. 40061 (headers[key.downcase] ||= []) << value
  95. end
  96. end
  97. 30 def parse_data
  98. 6561 if @buffer.respond_to?(:each)
  99. 190 @buffer.each do |chunk|
  100. 257 @observer.on_data(chunk)
  101. end
  102. 6370 elsif @content_length
  103. # @type var data: String
  104. 6326 data = @buffer.byteslice(0, @content_length)
  105. 6326 @buffer = @buffer.byteslice(@content_length..-1) || "".b
  106. 5719 @content_length -= data.bytesize
  107. 6326 @observer.on_data(data)
  108. 6301 data.clear
  109. else
  110. 45 @observer.on_data(@buffer)
  111. 45 @buffer.clear
  112. end
  113. 6527 return unless no_more_data?
  114. 4804 @buffer = @buffer.to_s
  115. 4804 if @_has_trailers
  116. 18 nextstate(:trailers)
  117. else
  118. 4786 nextstate(:complete)
  119. end
  120. end
  121. 30 def prepare_data(headers)
  122. 5819 @upgrade = headers.key?("upgrade")
  123. 5819 @_has_trailers = headers.key?("trailer")
  124. 5819 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. 5690 @content_length = headers["content-length"][0].to_i if headers.key?("content-length")
  135. end
  136. end
  137. 30 def no_more_data?
  138. 6527 if @content_length
  139. 6301 @content_length <= 0
  140. 225 elsif @buffer.respond_to?(:finished?)
  141. 181 @buffer.finished?
  142. else
  143. 45 false
  144. end
  145. end
  146. 30 def nextstate(state)
  147. 15632 @state = state
  148. 14175 case state
  149. when :headers
  150. 5837 @observer.on_start
  151. when :complete
  152. 4804 @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

72 relevant lines. 72 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. 164 {
  14. 1315 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. 540 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. 1644 super
  39. 1644 @auth_header_value = nil
  40. 1644 @skip_auth_header_value = false
  41. end
  42. 9 def authorization(token = nil, auth_header_type: nil, &blk)
  43. 270 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. 1504 return super if @skip_auth_header_value || request.authorized?
  60. 1174 @auth_header_value ||= generate_auth_token
  61. 1174 request.authorize(@auth_header_value) if @auth_header_value
  62. 1174 super
  63. end
  64. 9 def generate_auth_token
  65. 544 return unless (auth_value = @options.auth_header_value)
  66. 324 auth_value = auth_value.call(self) if dynamic_auth_token?(auth_value)
  67. 324 auth_value
  68. end
  69. 9 def dynamic_auth_token?(auth_header_value)
  70. 360 auth_header_value&.respond_to?(:call)
  71. end
  72. end
  73. 9 module RequestMethods
  74. 9 def initialize(*)
  75. 1268 super
  76. 1268 @auth_token_value = nil
  77. end
  78. 9 def authorized?
  79. 1360 !@auth_token_value.nil?
  80. end
  81. 9 def unauthorize!
  82. 56 return unless (auth_value = @auth_token_value)
  83. 56 @headers.get("authorization").delete(auth_value)
  84. 56 @auth_token_value = nil
  85. end
  86. 9 def authorize(auth_value)
  87. 1122 if (auth_type = @options.auth_header_type)
  88. 72 auth_value = "#{auth_type} #{auth_value}"
  89. end
  90. 1122 @headers.add("authorization", auth_value)
  91. 1122 @auth_token_value = auth_value
  92. end
  93. end
  94. 9 module AuthRetries
  95. 9 module InstanceMethods
  96. 9 private
  97. 9 def retryable_request?(request, response, options)
  98. 108 super || auth_error?(response, options)
  99. end
  100. 9 def retryable_response?(response, options)
  101. 90 auth_error?(response, options) || super
  102. end
  103. 9 def prepare_to_retry(request, response)
  104. 72 super
  105. 76 return unless auth_error?(response, request.options) ||
  106. 16 (@options.generate_auth_value_on_retry && @options.generate_auth_value_on_retry.call(response))
  107. 54 request.unauthorize!
  108. 54 @auth_header_value = generate_auth_token
  109. end
  110. 9 def auth_error?(response, options)
  111. 180 response.is_a?(Response) && response.status == 401 && dynamic_auth_token?(options.auth_header_value)
  112. end
  113. end
  114. end
  115. end
  116. 9 register_plugin :auth, Auth
  117. end
  118. 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 class Error < Error
  10. end
  11. 9 def initialize(user, password, hashed: false, **)
  12. 198 @user = user
  13. 198 @password = password
  14. 198 @nonce = 0
  15. 198 @hashed = hashed
  16. end
  17. 9 def can_authenticate?(authenticate)
  18. 180 authenticate && /Digest .*/.match?(authenticate)
  19. end
  20. 9 def authenticate(request, authenticate)
  21. 180 "Digest #{generate_header(request.verb, request.path, authenticate)}"
  22. end
  23. 9 private
  24. 9 def generate_header(meth, uri, authenticate)
  25. # discard first token, it's Digest
  26. 180 auth_info = authenticate[/^(\w+) (.*)/, 2]
  27. 180 raise_format_error unless auth_info
  28. 180 s = StringScanner.new(auth_info)
  29. 180 params = {}
  30. 284 until s.eos?
  31. 936 k = s.scan_until(/=/)
  32. 936 raise_format_error unless k&.end_with?("=")
  33. 936 if s.peek(1) == "\""
  34. 720 s.skip("\"")
  35. 720 v = s.scan_until(/"/)
  36. 720 raise_format_error unless v&.end_with?("\"")
  37. 720 v = v[0..-2]
  38. 720 s.skip_until(/,/)
  39. else
  40. 216 v = s.scan_until(/,|$/)
  41. 216 if v&.end_with?(",")
  42. 198 v = v[0..-2]
  43. else
  44. 18 raise_format_error unless s.eos?
  45. end
  46. 216 v = v[0..-2] if v&.end_with?(",")
  47. end
  48. 832 params[k[0..-2]] = v
  49. 936 s.skip(/\s/)
  50. end
  51. 180 nonce = params["nonce"]
  52. 180 nc = next_nonce
  53. # verify qop
  54. 180 qop = params["qop"]
  55. 180 if qop
  56. # some servers send multiple values wrapped in parentheses (i.e. "(qauth,)")
  57. 180 qop = qop[/\(?([^)]+)\)?/, 1]
  58. 360 qop = qop.split(",").map { |s| s.delete_prefix("'").delete_suffix("'") }.delete_if(&:empty?).map.first
  59. end
  60. 180 if params["algorithm"] =~ /(.*?)(-sess)?$/
  61. 162 alg = Regexp.last_match(1)
  62. 162 algorithm = ::Digest.const_get(alg)
  63. 162 raise Error, "unknown algorithm \"#{alg}\"" unless algorithm
  64. 162 sess = Regexp.last_match(2)
  65. else
  66. 18 algorithm = ::Digest::MD5
  67. end
  68. 180 if qop || sess
  69. 180 cnonce = make_cnonce
  70. 180 nc = format("%<nonce>08x", nonce: nc)
  71. end
  72. 180 a1 = if sess
  73. 4 [
  74. 36 (@hashed ? @password : algorithm.hexdigest("#{@user}:#{params["realm"]}:#{@password}")),
  75. nonce,
  76. cnonce,
  77. 3 ].join ":"
  78. else
  79. 144 @hashed ? @password : "#{@user}:#{params["realm"]}:#{@password}"
  80. end
  81. 180 ha1 = algorithm.hexdigest(a1)
  82. 180 ha2 = algorithm.hexdigest("#{meth}:#{uri}")
  83. 180 request_digest = [ha1, nonce]
  84. 180 request_digest.push(nc, cnonce, qop) if qop
  85. 180 request_digest << ha2
  86. 180 request_digest = request_digest.join(":")
  87. 40 header = [
  88. 160 %(username="#{@user}"),
  89. 20 %(nonce="#{nonce}"),
  90. 20 %(uri="#{uri}"),
  91. 20 %(response="#{algorithm.hexdigest(request_digest)}"),
  92. ]
  93. 180 header << %(realm="#{params["realm"]}") if params.key?("realm")
  94. 180 header << %(algorithm=#{params["algorithm"]}) if params.key?("algorithm")
  95. 180 header << %(cnonce="#{cnonce}") if cnonce
  96. 180 header << %(nc=#{nc})
  97. 180 header << %(qop=#{qop}) if qop
  98. 180 header << %(opaque="#{params["opaque"]}") if params.key?("opaque")
  99. 180 header.join ", "
  100. end
  101. 9 def make_cnonce
  102. 200 ::Digest::MD5.hexdigest [
  103. Time.now.to_i,
  104. Process.pid,
  105. SecureRandom.random_number(2**32),
  106. ].join ":"
  107. end
  108. 9 def next_nonce
  109. 160 @nonce += 1
  110. end
  111. 9 def raise_format_error
  112. raise Error, "unsupported digest header format"
  113. end
  114. end
  115. end
  116. end
  117. 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

41 relevant lines. 41 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 8 module HTTPX
  3. 8 module Plugins
  4. 8 module Brotli
  5. 8 class Error < HTTPX::Error; end
  6. 8 class Deflater < Transcoder::Deflater
  7. 8 def initialize(body)
  8. 14 @compressor = ::Brotli::Compressor.new
  9. 14 super
  10. end
  11. 8 def deflate(chunk)
  12. 42 return @compressor.process(chunk) << @compressor.flush if chunk
  13. 28 @compressor.finish
  14. end
  15. end
  16. 8 class Inflater
  17. 8 def initialize(bytesize)
  18. 15 @inflater = ::Brotli::Decompressor.new
  19. 15 @bytesize = bytesize
  20. end
  21. 8 def call(chunk)
  22. 16 buffer = @inflater.process(chunk)
  23. 16 @bytesize -= chunk.bytesize
  24. 16 raise Error, "Unexpected end of compressed stream" if @bytesize <= 0 && !@inflater.finished?
  25. 16 buffer
  26. end
  27. end
  28. 8 module RequestBodyClassMethods
  29. 8 def initialize_deflater_body(body, encoding)
  30. 28 return Brotli.encode(body) if encoding == "br"
  31. 14 super
  32. end
  33. end
  34. 8 module ResponseBodyClassMethods
  35. 8 def initialize_inflater_by_encoding(encoding, response, **kwargs)
  36. 29 return Brotli.decode(response, **kwargs) if encoding == "br"
  37. 14 super
  38. end
  39. end
  40. 8 module_function
  41. 8 def load_dependencies(*)
  42. 29 gem "brotli", ">= 0.8.0"
  43. 29 require "brotli"
  44. end
  45. 8 def self.extra_options(options)
  46. 29 supported_compression_formats = (%w[br] + options.supported_compression_formats).freeze
  47. 29 options.merge(
  48. supported_compression_formats: supported_compression_formats,
  49. headers: options.headers_class.new(options.headers.merge("accept-encoding" => supported_compression_formats))
  50. )
  51. end
  52. 8 def encode(body)
  53. 14 Deflater.new(body)
  54. end
  55. 8 def decode(response, bytesize: nil)
  56. 15 bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
  57. 15 Inflater.new(bytesize)
  58. end
  59. end
  60. 8 register_plugin :brotli, Brotli
  61. end
  62. 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. 253 super
  51. 253 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. 253 connection.on(:callback_connection_closed) do
  56. 246 next unless connection.current_session == self
  57. 246 emit_or_callback_error(:connection_closed, connection.origin) if connection.used?
  58. end
  59. 253 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. 186 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. 1365 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. 264 return if @exhausted
  108. 264 return unless @current_session && @current_selector
  109. 246 emit(:callback_connection_closed)
  110. 219 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. 681 response = super
  92. 681 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

54 relevant lines. 54 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. # https://gitlab.com/os85/httpx/wikis/Cookies
  9. #
  10. 9 module Cookies
  11. 9 def self.load_dependencies(*)
  12. 216 require "httpx/plugins/cookies/jar"
  13. 216 require "httpx/plugins/cookies/cookie"
  14. 216 require "httpx/plugins/cookies/set_cookie_parser"
  15. end
  16. 9 module InstanceMethods
  17. 9 extend Forwardable
  18. 9 def_delegator :@options, :cookies
  19. 9 def initialize(options = {}, &blk)
  20. 378 super({ cookies: Jar.new }.merge(options), &blk)
  21. end
  22. 9 def wrap
  23. 18 return super unless block_given?
  24. 18 super do |session|
  25. 18 old_cookies_jar = @options.cookies.dup
  26. 1 begin
  27. 18 yield session
  28. ensure
  29. 18 @options = @options.merge(cookies: old_cookies_jar)
  30. end
  31. end
  32. end
  33. 9 def build_request(*)
  34. 360 request = super
  35. 360 request.headers.set_cookie(request.options.cookies[request.uri])
  36. 360 request
  37. end
  38. # factory method to return a Jar to the user, which can then manipulate
  39. # externally to the session.
  40. 9 def make_jar(*args)
  41. 18 Jar.new(*args)
  42. end
  43. 9 private
  44. 9 def set_request_callbacks(request)
  45. 360 super
  46. 360 request.on(:response) do |response|
  47. 360 next unless response && response.respond_to?(:headers) && (set_cookie = response.headers["set-cookie"])
  48. 72 log { "cookies: set-cookie is over #{Cookie::MAX_LENGTH}" } if set_cookie.bytesize > Cookie::MAX_LENGTH
  49. 72 @options.cookies.parse(set_cookie)
  50. end
  51. end
  52. end
  53. 9 module HeadersMethods
  54. 9 def set_cookie(cookies)
  55. 360 return if cookies.empty?
  56. 306 header_value = cookies.sort.join("; ")
  57. 306 add("cookie", header_value)
  58. end
  59. end
  60. # adds support for the following options:
  61. #
  62. # :cookies :: cookie jar for the session (can be a Hash, an Array, an instance of HTTPX::Plugins::Cookies::CookieJar)
  63. 9 module OptionsMethods
  64. 9 private
  65. 9 def option_headers(*)
  66. 414 value = super
  67. 414 merge_cookie_in_jar(value.delete("cookie"), @cookies) if defined?(@cookies) && value.key?("cookie")
  68. 414 value
  69. end
  70. 9 def option_cookies(value)
  71. 594 jar = value.is_a?(Jar) ? value : Jar.new(value)
  72. 594 merge_cookie_in_jar(@headers.delete("cookie"), jar) if defined?(@headers) && @headers.key?("cookie")
  73. 594 jar
  74. end
  75. 9 def merge_cookie_in_jar(cookies, jar)
  76. 18 cookies.each do |ck|
  77. 18 ck.split(/ *; */).each do |cookie|
  78. 36 name, value = cookie.split("=", 2)
  79. 36 jar.set(name, value)
  80. end
  81. end
  82. end
  83. end
  84. end
  85. 9 register_plugin :cookies, Cookies
  86. end
  87. end

lib/httpx/plugins/cookies/cookie.rb

97.67% lines covered

86 relevant lines. 84 lines covered and 2 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. # assigns a new +path+ to this cookie.
  14. 9 def path=(path)
  15. 207 path = String(path)
  16. 207 @for_domain = false
  17. 207 @path = path.start_with?("/") ? path : "/"
  18. end
  19. # assigns a new +domain+ to this cookie.
  20. 9 def domain=(domain)
  21. 45 domain = String(domain)
  22. 45 if domain.start_with?(".")
  23. 18 @for_domain = true
  24. 18 domain = domain[1..-1]
  25. end
  26. 45 return if domain.empty?
  27. 45 @domain_name = DomainName.new(domain)
  28. # RFC 6265 5.3 5.
  29. 45 @for_domain = false if @domain_name.domain.nil? # a public suffix or IP address
  30. 45 @domain = @domain_name.hostname
  31. end
  32. # checks whether +other+ is the same cookie, i.e. name, value, domain and path are
  33. # the same.
  34. 9 def ==(other)
  35. 135 @name == other.name && @value == other.value &&
  36. @path == other.path && @domain == other.domain
  37. end
  38. # Compares the cookie with another. When there are many cookies with
  39. # the same name for a URL, the value of the smallest must be used.
  40. 9 def <=>(other)
  41. # RFC 6265 5.4
  42. # Precedence: 1. longer path 2. older creation
  43. 786 (@name <=> other.name).nonzero? ||
  44. 67 (other.path.length <=> @path.length).nonzero? ||
  45. 39 (@created_at <=> other.created_at).nonzero? || 0
  46. end
  47. 9 def match?(name_or_options)
  48. 152 case name_or_options
  49. when String
  50. 72 @name == name_or_options
  51. when Hash, Array
  52. 279 name_or_options.all? { |k, v| respond_to?(k) && send(k) == v }
  53. else
  54. false
  55. end
  56. end
  57. 9 class << self
  58. 9 def new(cookie, *args)
  59. 632 case cookie
  60. when self
  61. cookie
  62. when Array, Hash
  63. 36 options = Hash[cookie] #: cookie_attributes
  64. 36 super(options[:name], options[:value], options)
  65. else
  66. 675 super
  67. end
  68. end
  69. # Tests if +target_path+ is under +base_path+ as described in RFC
  70. # 6265 5.1.4. +base_path+ must be an absolute path.
  71. # +target_path+ may be empty, in which case it is treated as the
  72. # root path.
  73. #
  74. # e.g.
  75. #
  76. # path_match?('/admin/', '/admin/index') == true
  77. # path_match?('/admin/', '/Admin/index') == false
  78. # path_match?('/admin/', '/admin/') == true
  79. # path_match?('/admin/', '/admin') == false
  80. #
  81. # path_match?('/admin', '/admin') == true
  82. # path_match?('/admin', '/Admin') == false
  83. # path_match?('/admin', '/admins') == false
  84. # path_match?('/admin', '/admin/') == true
  85. # path_match?('/admin', '/admin/index') == true
  86. 9 def path_match?(base_path, target_path)
  87. 1521 base_path.start_with?("/") || (return false)
  88. # RFC 6265 5.1.4
  89. 1521 bsize = base_path.size
  90. 1521 tsize = target_path.size
  91. 1521 return bsize == 1 if tsize.zero? # treat empty target_path as "/"
  92. 1521 return false unless target_path.start_with?(base_path)
  93. 1512 return true if bsize == tsize || base_path.end_with?("/")
  94. 18 target_path[bsize] == "/"
  95. end
  96. end
  97. 9 def initialize(arg, value, attrs = nil)
  98. 711 @created_at = Time.now
  99. 711 @name = arg
  100. 711 @value = value
  101. 711 attr_hash = Hash.try_convert(attrs)
  102. 34 attr_hash.each do |key, val|
  103. 369 key = key.downcase.tr("-", "_").to_sym unless key.is_a?(Symbol)
  104. 328 case key
  105. when :domain, :path
  106. 229 __send__(:"#{key}=", val)
  107. else
  108. 117 instance_variable_set(:"@#{key}", val)
  109. end
  110. 710 end if attr_hash
  111. 711 @path ||= "/"
  112. 711 raise ArgumentError, "name must be specified" if @name.nil?
  113. 711 @name = @name.to_s
  114. end
  115. 9 def expires
  116. 855 @expires || (@created_at && @max_age ? @created_at + @max_age : nil)
  117. end
  118. 9 def expired?(time = Time.now)
  119. 819 return false unless expires
  120. 36 expires <= time
  121. end
  122. # Returns a string for use in the Cookie header, i.e. `name=value`
  123. # or `name="value"`.
  124. 9 def cookie_value
  125. 552 "#{@name}=#{Scanner.quote(@value.to_s)}"
  126. end
  127. 9 alias_method :to_s, :cookie_value
  128. # Tests if it is OK to send this cookie to a given `uri`. A
  129. # RuntimeError is raised if the cookie's domain is unknown.
  130. 9 def valid_for_uri?(uri)
  131. 801 uri = URI(uri)
  132. # RFC 6265 5.4
  133. 801 return false if @secure && uri.scheme != "https"
  134. 792 acceptable_from_uri?(uri) && Cookie.path_match?(@path, uri.path)
  135. end
  136. 9 private
  137. # Tests if it is OK to accept this cookie if it is sent from a given
  138. # URI/URL, `uri`.
  139. 9 def acceptable_from_uri?(uri)
  140. 828 uri = URI(uri)
  141. 828 host = DomainName.new(uri.host)
  142. # RFC 6265 5.3
  143. 828 if host.hostname == @domain
  144. 18 true
  145. 809 elsif @for_domain # !host-only-flag
  146. 36 host.cookie_domain?(@domain_name)
  147. else
  148. 774 @domain.nil?
  149. end
  150. end
  151. 9 module Scanner
  152. 9 RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/.freeze
  153. 9 module_function
  154. 9 def quote(s)
  155. 621 return s unless s.match(RE_BAD_CHAR)
  156. 9 "\"#{s.gsub(/([\\"])/, "\\\\\\1")}\""
  157. end
  158. end
  159. end
  160. end
  161. end

lib/httpx/plugins/cookies/jar.rb

100.0% lines covered

73 relevant lines. 73 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 stores and manages cookies for a session, such as i.e. evicting when expired, access methods, or
  7. # initialization from parsing `Set-Cookie` HTTP header values.
  8. #
  9. # It closely follows the [CookieStore API](https://developer.mozilla.org/en-US/docs/Web/API/CookieStore),
  10. # by implementing the same methods, with a few specific conveniences for this non-browser manipulation use-case.
  11. #
  12. 9 class Jar
  13. 9 using URIExtensions
  14. 9 include Enumerable
  15. 9 def initialize_dup(orig)
  16. 243 super
  17. 243 @mtx = orig.instance_variable_get(:@mtx).dup
  18. 243 @cookies = orig.instance_variable_get(:@cookies).dup
  19. end
  20. # initializes the cookie store, either empty, or with whatever is passed as +cookies+, which
  21. # can be an array of HTTPX::Plugins::Cookies::Cookie objects or hashes-or-tuples of cookie attributes.
  22. 9 def initialize(cookies = nil)
  23. 774 @mtx = Thread::Mutex.new
  24. 774 @cookies = []
  25. 162 cookies.each do |elem|
  26. 270 cookie = case elem
  27. when Cookie
  28. 27 elem
  29. when Array
  30. 225 Cookie.new(*elem)
  31. else
  32. 18 Cookie.new(elem)
  33. end
  34. 270 @cookies << cookie
  35. 773 end if cookies
  36. end
  37. # parses the `Set-Cookie` header value as +set_cookie+ and does the corresponding updates.
  38. 9 def parse(set_cookie)
  39. 162 SetCookieParser.call(set_cookie) do |name, value, attrs|
  40. 234 set(Cookie.new(name, value, attrs))
  41. end
  42. end
  43. # returns the first HTTPX::Plugins::Cookie::Cookie instance in the store which matches either the name
  44. # (when String) or all attributes (when a Hash or array of tuples) passed to +name_or_options+
  45. 9 def get(name_or_options)
  46. 108 each.find { |ck| ck.match?(name_or_options) }
  47. end
  48. # returns all HTTPX::Plugins::Cookie::Cookie instances in the store which match either the name
  49. # (when String) or all attributes (when a Hash or array of tuples) passed to +name_or_options+
  50. 9 def get_all(name_or_options)
  51. 135 each.select { |ck| ck.match?(name_or_options) } # rubocop:disable Style/SelectByRegexp
  52. end
  53. # when +name+ is a HTTPX::Plugins::Cookie::Cookie, it stores it internally; when +name+ is a String,
  54. # it creates a cookie with it and the value-or-attributes passed to +value_or_options+.
  55. # optionally, +name+ can also be the attributes hash-or-array as long it contains a <tt>:name</tt> field).
  56. 9 def set(name, value_or_options = nil)
  57. 576 cookie = case name
  58. when Cookie
  59. 504 raise ArgumentError, "there should not be a second argument" if value_or_options
  60. 495 name
  61. when Array, Hash
  62. 18 raise ArgumentError, "there should not be a second argument" if value_or_options
  63. 9 Cookie.new(name)
  64. else
  65. 54 raise ArgumentError, "the second argument is required" unless value_or_options
  66. 45 Cookie.new(name, value_or_options)
  67. end
  68. 549 synchronize do
  69. # If the user agent receives a new cookie with the same cookie-name, domain-value, and path-value
  70. # as a cookie that it has already stored, the existing cookie is evicted and replaced with the new cookie.
  71. 1008 @cookies.delete_if { |ck| ck.name == cookie.name && ck.domain == cookie.domain && ck.path == cookie.path }
  72. 549 @cookies << cookie
  73. end
  74. end
  75. # @deprecated
  76. 9 def add(cookie, path = nil)
  77. 9 warn "DEPRECATION WARNING: calling `##{__method__}` is deprecated. Use `#set` instead."
  78. 9 c = cookie.dup
  79. 9 c.path = path if path && c.path == "/"
  80. 9 set(c)
  81. end
  82. # deletes all cookies in the store which match either the name (when String) or all attributes (when a Hash
  83. # or array of tuples) passed to +name_or_options+.
  84. #
  85. # alternatively, of +name_or_options+ is an instance of HTTPX::Plugins::Cookies::Cookiem, it deletes it from the store.
  86. 9 def delete(name_or_options)
  87. 36 synchronize do
  88. 32 case name_or_options
  89. when Cookie
  90. 9 @cookies.delete(name_or_options)
  91. else
  92. 54 @cookies.delete_if { |ck| ck.match?(name_or_options) }
  93. end
  94. end
  95. end
  96. # returns the list of valid cookies which matdh the domain and path from the URI object passed to +uri+.
  97. 9 def [](uri)
  98. 531 each(uri).sort
  99. end
  100. # enumerates over all stored cookies. if +uri+ is passed, it'll filter out expired cookies and
  101. # only yield cookies which match its domain and path.
  102. 9 def each(uri = nil, &blk)
  103. 1764 return enum_for(__method__, uri) unless blk
  104. 1431 return synchronize { @cookies.each(&blk) } unless uri
  105. 531 now = Time.now
  106. 531 tpath = uri.path
  107. 531 synchronize do
  108. 531 @cookies.delete_if do |cookie|
  109. 819 if cookie.expired?(now)
  110. 18 true
  111. else
  112. 801 yield cookie if cookie.valid_for_uri?(uri) && Cookie.path_match?(cookie.path, tpath)
  113. 801 false
  114. end
  115. end
  116. end
  117. end
  118. 9 def merge(other)
  119. 225 jar_dup = dup
  120. 225 other.each do |elem|
  121. 243 cookie = case elem
  122. when Cookie
  123. 225 elem
  124. when Array
  125. 9 Cookie.new(*elem)
  126. else
  127. 9 Cookie.new(elem)
  128. end
  129. 243 jar_dup.set(cookie)
  130. end
  131. 225 jar_dup
  132. end
  133. 9 private
  134. 9 def synchronize(&block)
  135. 1566 return yield if @mtx.owned?
  136. 1566 @mtx.synchronize(&block)
  137. end
  138. end
  139. end
  140. 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. 9 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

71 relevant lines. 71 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 NOEXPECT_STORE_MUTEX = Thread::Mutex.new
  12. 10 class Store
  13. 10 def initialize
  14. 10 @store = []
  15. 10 @mutex = Thread::Mutex.new
  16. end
  17. 10 def include?(host)
  18. 310 @mutex.synchronize { @store.include?(host) }
  19. end
  20. 10 def add(host)
  21. 36 @mutex.synchronize { @store << host }
  22. end
  23. 10 def delete(host)
  24. 18 @mutex.synchronize { @store.delete(host) }
  25. end
  26. end
  27. 10 class << self
  28. 10 def no_expect_store
  29. 182 return Ractor.store_if_absent(:httpx_no_expect_store) { Store.new } if Utils.in_ractor?
  30. 182 @no_expect_store ||= NOEXPECT_STORE_MUTEX.synchronize do
  31. 10 @no_expect_store || Store.new
  32. end
  33. end
  34. 10 def extra_options(options)
  35. 227 options.merge(expect_timeout: EXPECT_TIMEOUT)
  36. end
  37. end
  38. # adds support for the following options:
  39. #
  40. # :expect_timeout :: time (in seconds) to wait for a 100-expect response,
  41. # before retrying without the Expect header (defaults to <tt>2</tt>).
  42. # :expect_threshold_size :: min threshold (in bytes) of the request payload to enable the 100-continue negotiation on.
  43. 10 module OptionsMethods
  44. 10 private
  45. 10 def option_expect_timeout(value)
  46. 416 seconds = Float(value)
  47. 416 raise TypeError, ":expect_timeout must be positive" unless seconds.positive?
  48. 416 seconds
  49. end
  50. 10 def option_expect_threshold_size(value)
  51. 18 bytes = Integer(value)
  52. 18 raise TypeError, ":expect_threshold_size must be positive" unless bytes.positive?
  53. 18 bytes
  54. end
  55. end
  56. 10 module RequestMethods
  57. 10 def initialize(*)
  58. 263 super
  59. 263 @informational_status = nil
  60. 263 return if @body.empty?
  61. 173 threshold = @options.expect_threshold_size
  62. 173 return if threshold && !@body.unbounded_body? && @body.bytesize < threshold
  63. 155 return if Expect.no_expect_store.include?(origin)
  64. 130 @headers["expect"] = "100-continue"
  65. end
  66. 10 def response=(response)
  67. 159 if response.is_a?(Response) &&
  68. response.status == 100 &&
  69. !@headers.key?("expect") &&
  70. 4 (@state == :body || @state == :done)
  71. # if we're past this point, this means that we just received a 100-Continue response,
  72. # but the request doesn't have the expect flag, and is already flushing (or flushed) the body.
  73. #
  74. # this means that expect was deactivated for this request too soon, i.e. response took longer.
  75. #
  76. # so we have to reactivate it again.
  77. 8 @headers["expect"] = "100-continue"
  78. 9 @informational_status = 100
  79. 9 Expect.no_expect_store.delete(origin)
  80. end
  81. 159 super
  82. end
  83. end
  84. 10 module ConnectionMethods
  85. 10 def send_request_to_parser(request)
  86. 94 super
  87. 94 return unless request.headers["expect"] == "100-continue"
  88. 74 expect_timeout = request.options.expect_timeout
  89. 74 return if expect_timeout.nil? || expect_timeout.infinite?
  90. 74 set_request_timeout(:expect_timeout, request, expect_timeout, :expect, %i[body response]) do
  91. # expect timeout expired
  92. 18 if request.state == :expect && !request.expects?
  93. 18 Expect.no_expect_store.add(request.origin)
  94. 18 request.headers.delete("expect")
  95. 18 consume
  96. end
  97. end
  98. end
  99. end
  100. 10 module InstanceMethods
  101. 10 def fetch_response(request, selector, options)
  102. 415 response = super
  103. 415 return unless response
  104. 94 if response.is_a?(Response) && response.status == 417 && request.headers.key?("expect")
  105. 2 response.close
  106. 2 request.headers.delete("expect")
  107. 2 request.transition(:idle)
  108. 2 send_request(request, selector, options)
  109. # recalling itself, in case an error was triggered by the above, and we can
  110. # verify retriability again.
  111. 2 return fetch_response(request, selector, options)
  112. end
  113. 92 response
  114. end
  115. end
  116. end
  117. 10 register_plugin :expect, Expect
  118. end
  119. end

lib/httpx/plugins/fiber_concurrency.rb

92.93% lines covered

99 relevant lines. 92 lines covered and 7 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. 2068 h2c: FiberConcurrencyH2C,
  14. stream: FiberConcurrencyStream,
  15. }
  16. end
  17. 19 module InstanceMethods
  18. 19 private
  19. 19 def send_request(request, *)
  20. 772 request.set_context!
  21. 772 super
  22. end
  23. 19 def get_current_selector
  24. 687 super(&nil) || begin
  25. 597 return unless block_given?
  26. 597 default = yield
  27. 597 set_current_selector(default)
  28. 597 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. 700 super
  37. 700 @context = nil
  38. end
  39. # sets the execution context for this request. the default is the current fiber.
  40. 19 def set_context!
  41. 1569 @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. 5974 @context == Fiber.current
  46. end
  47. 19 def complete!(response = @response)
  48. 669 @context = nil
  49. 669 super
  50. end
  51. end
  52. 19 module ConnectionMethods
  53. 19 def current_context?
  54. 1503 @pending.any?(&:current_context?) || (
  55. 924 @sibling && @sibling.pending.any?(&:current_context?)
  56. )
  57. end
  58. 19 def interests
  59. 12395 return if connecting? && @pending.none?(&:current_context?)
  60. 11926 super
  61. end
  62. 19 def send(request)
  63. # DoH requests bypass the session, so context needs to be set here.
  64. 797 request.set_context!
  65. 797 super
  66. end
  67. end
  68. 19 module HTTP1Methods
  69. 19 def interests
  70. 1304 request = @request || @requests.first
  71. 1304 return unless request
  72. 1284 return unless request.current_context? || @requests.any?(&:current_context?) || @pending.any?(&:current_context?)
  73. 1284 super
  74. end
  75. end
  76. 19 module HTTP2Methods
  77. 19 def initialize(*)
  78. 456 super
  79. 1384 @contexts = Hash.new { |hs, k| hs[k] = Set.new }
  80. end
  81. 19 def interests
  82. 9301 if @connection.state == :connected && @handshake_completed && !@contexts.key?(Fiber.current)
  83. 562 return :w unless @pings.empty?
  84. 480 return
  85. end
  86. 8739 super
  87. end
  88. 19 def send(request, *)
  89. 1022 add_to_context(request)
  90. 1022 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. 1022 @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 ResolverNativeMethods
  124. 19 def calculate_interests
  125. 814 return if @queries.empty?
  126. 774 return unless @queries.values.any?(&:current_context?) || @connections.any?(&:current_context?)
  127. 719 super
  128. end
  129. end
  130. 19 module ResolverSystemMethods
  131. 19 def interests
  132. return unless @queries.any? { |_, conn| conn.current_context? }
  133. super
  134. end
  135. end
  136. 19 module FiberConcurrencyH2C
  137. 19 module HTTP2Methods
  138. 19 def upgrade(request, *)
  139. @contexts[request.context] << request
  140. super
  141. end
  142. end
  143. end
  144. 19 module FiberConcurrencyStream
  145. 19 module StreamResponseMethods
  146. 19 def close
  147. 10 unless @request.current_context?
  148. 10 @request.close
  149. 10 return
  150. end
  151. super
  152. end
  153. end
  154. end
  155. end
  156. 19 register_plugin :fiber_concurrency, FiberConcurrency
  157. end
  158. end

lib/httpx/plugins/follow_redirects.rb

100.0% lines covered

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

91.04% lines covered

134 relevant lines. 122 lines covered and 12 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. 9 def dynamic_auth_token?(_)
  214. 36 @oauth_session
  215. end
  216. end
  217. 9 module OAuthRetries
  218. 9 module InstanceMethods
  219. 9 private
  220. 9 def prepare_to_retry(_request, response)
  221. 18 @oauth_session.reset! if @oauth_session
  222. 18 super
  223. end
  224. end
  225. end
  226. end
  227. 9 register_plugin :oauth, OAuth
  228. end
  229. end

lib/httpx/plugins/persistent.rb

100.0% lines covered

30 relevant lines. 30 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. 4517 store = thread_selector_store(th)
  42. 4517 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 retryable_request?(request, response, *)
  49. 686 super || begin
  50. 226 return false unless response && response.is_a?(ErrorResponse)
  51. 32 error = response.error
  52. 352 Retries::RECONNECTABLE_ERRORS.any? { |klass| error.is_a?(klass) }
  53. end
  54. end
  55. 19 def retryable_error?(ex, options)
  56. 97 super &&
  57. # under the persistent plugin rules, requests are only retried for connection related errors,
  58. # which do not include request timeout related errors. This only gets overriden if the end user
  59. # manually changed +:max_retries+ to something else, which means it is aware of the
  60. # consequences.
  61. 81 (!ex.is_a?(RequestTimeoutError) || options.max_retries != 1)
  62. end
  63. end
  64. end
  65. 19 register_plugin :persistent, Persistent
  66. end
  67. end

lib/httpx/plugins/proxy.rb

94.86% lines covered

175 relevant lines. 166 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. 128 "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. 2161 response = request.response # in case it goes wrong later
  144. 168 begin
  145. 2161 response = super
  146. 2161 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. # recalling itself, in case an error was triggered by the above, and we can
  154. # verify retriability again.
  155. 18 return fetch_response(request, selector, options)
  156. end
  157. 2143 response
  158. rescue ProxyError
  159. # may happen if coupled with retries, and there are no more proxies to try, in which case
  160. # it'll end up here
  161. response
  162. end
  163. end
  164. 11 def proxy_error?(_request, response, options)
  165. 190 return false unless options.proxy
  166. 189 error = response.error
  167. 168 case error
  168. when NativeResolveError
  169. 18 proxy_uri = URI(options.proxy.uri)
  170. 18 unresolved_host = error.host
  171. # failed resolving proxy domain
  172. 18 unresolved_host == proxy_uri.host
  173. when ResolveError
  174. proxy_uri = URI(options.proxy.uri)
  175. error.message.end_with?(proxy_uri.to_s)
  176. when ProxyConnectionError
  177. # timeout errors connecting to proxy
  178. true
  179. else
  180. 171 false
  181. end
  182. end
  183. end
  184. 11 module ConnectionMethods
  185. 11 using URIExtensions
  186. 11 def initialize(*)
  187. 440 super
  188. 440 return unless @options.proxy
  189. # redefining the connection origin as the proxy's URI,
  190. # as this will be used as the tcp peer ip.
  191. 420 @proxy_uri = URI(@options.proxy.uri)
  192. end
  193. 11 def peer
  194. 1064 @proxy_uri || super
  195. end
  196. 11 def connecting?
  197. 6821 return super unless @options.proxy
  198. 6608 super || @state == :connecting || @state == :connected
  199. end
  200. 11 def call
  201. 1553 super
  202. 1553 return unless @options.proxy
  203. 1385 case @state
  204. when :connecting
  205. 375 consume
  206. end
  207. rescue *PROXY_ERRORS => e
  208. if connecting?
  209. error = ProxyConnectionError.new(e.message)
  210. error.set_backtrace(e.backtrace)
  211. raise error
  212. end
  213. raise e
  214. end
  215. 11 def reset
  216. 475 return super unless @options.proxy
  217. 456 @state = :open
  218. 456 super
  219. # emit(:close)
  220. end
  221. 11 private
  222. 11 def initialize_type(uri, options)
  223. 440 return super unless options.proxy
  224. 420 "tcp"
  225. end
  226. 11 def connect
  227. 1268 return super unless @options.proxy
  228. 1102 case @state
  229. when :idle
  230. 833 transition(:connecting)
  231. when :connected
  232. 397 transition(:open)
  233. end
  234. end
  235. 11 def handle_transition(nextstate)
  236. 2593 return super unless @options.proxy
  237. 2232 case nextstate
  238. when :closing
  239. # this is a hack so that we can use the super method
  240. # and it'll think that the current state is open
  241. 456 @state = :open if @state == :connecting
  242. end
  243. 2496 super
  244. end
  245. 11 def purge_after_closed
  246. 502 super
  247. 514 while @io.respond_to?(:proxy_io)
  248. 115 @io = @io.proxy_io
  249. 115 super
  250. end
  251. end
  252. end
  253. 11 module ProxyRetries
  254. 11 module InstanceMethods
  255. 11 private
  256. 11 def retryable_error?(ex, *)
  257. 62 super || ex.is_a?(ProxyConnectionError)
  258. end
  259. end
  260. end
  261. end
  262. 11 register_plugin :proxy, Proxy
  263. end
  264. 11 class ProxySSL < SSL
  265. 11 attr_reader :proxy_io
  266. 11 def initialize(tcp, request_uri, options)
  267. 116 @proxy_io = tcp
  268. 116 @io = tcp.to_io
  269. 116 super(request_uri, tcp.addresses, options)
  270. 116 @hostname = request_uri.host
  271. 116 @state = :connected
  272. end
  273. end
  274. end

lib/httpx/plugins/proxy/http.rb

94.87% lines covered

117 relevant lines. 111 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. 2161 response = super
  23. 2161 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. # recalling itself, in case an error was triggered by the above, and we can
  33. # verify retriability again.
  34. 8 return fetch_response(request, selector, options)
  35. end
  36. 2152 response
  37. end
  38. end
  39. 11 module ConnectionMethods
  40. 11 def force_close(*)
  41. if @state == :connecting
  42. # proxy connect related requests should not be reenqueed
  43. @parser.reset
  44. @inflight -= @parser.pending.size
  45. @parser.pending.clear
  46. end
  47. super
  48. end
  49. 11 private
  50. 11 def handle_transition(nextstate)
  51. 2878 return super unless @options.proxy && @options.proxy.uri.scheme == "http"
  52. 1363 case nextstate
  53. when :connecting
  54. 374 return unless @state == :idle
  55. 374 @io.connect
  56. 374 return unless @io.connected?
  57. 187 @parser || begin
  58. 178 @parser = parser = parser_type(@io.protocol).new(@write_buffer, @options.merge(max_concurrent_requests: 1))
  59. 178 parser.extend(ProxyParser)
  60. 178 parser.on(:response, &method(:__http_on_connect))
  61. 178 parser.on(:close) do
  62. 80 next unless @parser
  63. 9 reset
  64. end
  65. 178 parser.on(:reset) do
  66. 18 if parser.pending.empty? && 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 connect_request = parser = nil
  80. 9 if initial_state == :connecting
  81. 9 parser = @parser
  82. 9 @parser.reset
  83. 9 if @pending.first.is_a?(ConnectRequest)
  84. 9 connect_request = @pending.shift # this happened when reenqueing
  85. end
  86. end
  87. 9 idling
  88. 9 @parser = parser
  89. 9 if connect_request
  90. 8 @inflight += 1
  91. 9 parser.send(connect_request)
  92. end
  93. 9 transition(:connecting)
  94. end
  95. end
  96. 178 __http_proxy_connect(parser)
  97. end
  98. 187 return if @state == :connected
  99. when :connected
  100. 169 return unless @state == :idle || @state == :connecting
  101. 152 case @state
  102. when :connecting
  103. 71 parser = @parser
  104. 71 @parser = nil
  105. 71 parser.close
  106. when :idle
  107. 98 @parser.callbacks.clear
  108. 98 set_parser_callbacks(@parser)
  109. end
  110. end
  111. 1231 super
  112. end
  113. 11 def __http_proxy_connect(parser)
  114. 178 req = @pending.first
  115. 178 if req && req.uri.scheme == "https"
  116. # if the first request after CONNECT is to an https address, it is assumed that
  117. # all requests in the queue are not only ALL HTTPS, but they also share the certificate,
  118. # and therefore, will share the connection.
  119. #
  120. 80 connect_request = ConnectRequest.new(req.uri, @options)
  121. 72 @inflight += 1
  122. 80 parser.send(connect_request)
  123. else
  124. 98 handle_transition(:connected)
  125. end
  126. end
  127. 11 def __http_on_connect(request, response)
  128. 80 @inflight -= 1
  129. 89 if response.is_a?(Response) && response.status == 200
  130. 71 req = @pending.first
  131. 71 request_uri = req.uri
  132. 71 @io = ProxySSL.new(@io, request_uri, @options)
  133. 71 transition(:connected)
  134. 71 throw(:called)
  135. 17 elsif response.is_a?(Response) &&
  136. response.status == 407 &&
  137. !request.headers.key?("proxy-authorization") &&
  138. @options.proxy.can_authenticate?(response.headers["proxy-authenticate"])
  139. 9 request.transition(:idle)
  140. 8 request.headers["proxy-authorization"] = @options.proxy.authenticate(request, response.headers["proxy-authenticate"])
  141. 9 @parser.send(request)
  142. 8 @inflight += 1
  143. else
  144. 9 pending = @pending + @parser.pending
  145. 24 while (req = pending.shift)
  146. 9 response.finish!
  147. 9 req.response = response
  148. 9 req.emit(:response, response)
  149. end
  150. 9 reset
  151. end
  152. end
  153. end
  154. 11 module ProxyParser
  155. 11 def join_headline(request)
  156. 178 return super if request.verb == "CONNECT"
  157. 80 "#{request.verb} #{request.uri} HTTP/#{@version.join(".")}"
  158. end
  159. 11 def set_protocol_headers(request)
  160. 187 extra_headers = super
  161. 187 proxy_params = @options.proxy
  162. 187 if proxy_params.scheme == "basic"
  163. # opt for basic auth
  164. 97 extra_headers["proxy-authorization"] = proxy_params.authenticate(extra_headers)
  165. end
  166. 187 extra_headers["proxy-connection"] = extra_headers.delete("connection") if extra_headers.key?("connection")
  167. 187 extra_headers
  168. end
  169. end
  170. 11 class ConnectRequest < Request
  171. 11 def initialize(uri, options)
  172. 80 super("CONNECT", uri, options)
  173. 80 @headers.delete("accept")
  174. end
  175. 11 def path
  176. 88 "#{@uri.hostname}:#{@uri.port}"
  177. end
  178. end
  179. end
  180. end
  181. 11 register_plugin :"proxy/http", Proxy::HTTP
  182. end
  183. 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. 4758 if @state == :connecting
  22. return @write_buffer.empty? ? :r : :w
  23. end
  24. 4758 super
  25. end
  26. 11 private
  27. 11 def handle_transition(nextstate)
  28. 2950 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. 421 log(level: 1) { "SOCKS4: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
  44. 421 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. 1553 super
  28. 1553 return unless @options.proxy && @options.proxy.uri.scheme == "socks5"
  29. 382 case @state
  30. when :connecting,
  31. :negotiating,
  32. :authenticating
  33. 183 consume
  34. end
  35. end
  36. 11 def connecting?
  37. 6821 super || @state == :authenticating || @state == :negotiating
  38. end
  39. 11 def interests
  40. 7821 if @state == :connecting || @state == :authenticating || @state == :negotiating
  41. 2847 return @write_buffer.empty? ? :r : :w
  42. end
  43. 4758 super
  44. end
  45. 11 private
  46. 11 def handle_transition(nextstate)
  47. 3274 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 retryable_request?(request, *)
  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

21 relevant lines. 21 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 RATE_LIMIT_CODES = [429, 503].freeze
  15. 9 class << self
  16. 9 def load_dependencies(klass)
  17. 72 klass.plugin(:retries)
  18. end
  19. end
  20. 9 module InstanceMethods
  21. 9 private
  22. 9 def retryable_request?(request, response, options)
  23. 144 super || rate_limit_error?(response)
  24. end
  25. 9 def retryable_response?(response, options)
  26. 144 rate_limit_error?(response) || super
  27. end
  28. 9 def rate_limit_error?(response)
  29. 144 response.is_a?(Response) && RATE_LIMIT_CODES.include?(response.status)
  30. end
  31. # Servers send the "Retry-After" header field to indicate how long the
  32. # user agent ought to wait before making a follow-up request. When
  33. # sent with a 503 (Service Unavailable) response, Retry-After indicates
  34. # how long the service is expected to be unavailable to the client.
  35. # When sent with any 3xx (Redirection) response, Retry-After indicates
  36. # the minimum time that the user agent is asked to wait before issuing
  37. # the redirected request.
  38. #
  39. 9 def when_to_retry(_, response, options)
  40. 72 return super unless response.is_a?(Response)
  41. 72 retry_after = response.headers["retry-after"]
  42. 72 return super unless retry_after
  43. 36 Utils.parse_retry_after(retry_after)
  44. end
  45. end
  46. end
  47. 9 register_plugin :rate_limiter, RateLimiter
  48. end
  49. 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. 662 response = super
  97. 662 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. 692 @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. 566 return chunk if @response.cached?
  263. 354 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.44% lines covered

117 relevant lines. 114 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. 1035 options.merge(max_retries: MAX_RETRIES)
  42. end
  43. else
  44. 1 def extra_options(options)
  45. 8 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. 270 if value.respond_to?(:call)
  72. 126 value1 = value
  73. 126 value1 = value1.method(:call) unless value1.respond_to?(:arity)
  74. # allow ->(*) arity as well, which is < 0
  75. 126 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. 270 value
  89. end
  90. 19 def option_retry_jitter(value)
  91. # return early if callable
  92. 70 raise TypeError, ":retry_jitter must be callable" unless value.respond_to?(:call)
  93. 70 value
  94. end
  95. 19 def option_max_retries(value)
  96. 3381 num = Integer(value)
  97. 3381 raise TypeError, ":max_retries must be positive" unless num >= 0
  98. 3381 num
  99. end
  100. 19 def option_retry_change_requests(v)
  101. 101 v
  102. end
  103. 19 def option_retry_on(value)
  104. 342 raise TypeError, ":retry_on must be called with the response" unless value.respond_to?(:call)
  105. 342 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. 162 with(max_retries: n)
  112. end
  113. 19 private
  114. 19 def fetch_response(request, selector, options)
  115. 8896 response = super
  116. 8896 if response &&
  117. request.retries.positive? &&
  118. retryable_request?(request, response, options) &&
  119. retryable_response?(response, options)
  120. 878 try_partial_retry(request, response)
  121. 878 log { "failed to get response, #{request.retries} tries to go..." }
  122. 878 prepare_to_retry(request, response)
  123. 878 if (retry_after = when_to_retry(request, response, options))
  124. # apply jitter
  125. 180 if (jitter = request.options.retry_jitter)
  126. 18 retry_after = jitter.call(retry_after)
  127. end
  128. 180 retry_start = Utils.now
  129. 180 log { "retrying after #{retry_after} secs..." }
  130. 180 selector.after(retry_after) do
  131. 180 if (response = request.response)
  132. response.finish!
  133. # request has terminated abruptly meanwhile
  134. request.emit(:response, response)
  135. else
  136. 180 log { "retrying (elapsed time: #{Utils.elapsed_time(retry_start)})!!" }
  137. 180 send_request(request, selector, options)
  138. end
  139. end
  140. 160 return
  141. else
  142. 698 send_request(request, selector, options)
  143. # recalling itself, in case an error was triggered by the above, and we can
  144. # verify retriability again.
  145. 626 return fetch_response(request, selector, options)
  146. end
  147. end
  148. 8018 response
  149. end
  150. # returns whether +request+ can be retried.
  151. 19 def retryable_request?(request, _, options)
  152. 1679 IDEMPOTENT_METHODS.include?(request.verb) || options.retry_change_requests
  153. end
  154. 19 def retryable_response?(response, options)
  155. 1323 (response.is_a?(ErrorResponse) && retryable_error?(response.error, options)) || options.retry_on&.call(response)
  156. end
  157. # returns whether the +ex+ exception happend for a retriable request.
  158. 19 def retryable_error?(ex, _)
  159. 7486 RETRYABLE_ERRORS.any? { |klass| ex.is_a?(klass) }
  160. end
  161. 19 def proxy_error?(request, response, _)
  162. 72 super && !request.retries.positive?
  163. end
  164. 19 def prepare_to_retry(request, _response)
  165. 878 request.retries -= 1 unless request.ping? # do not exhaust retries on connection liveness probes
  166. 878 request.transition(:idle)
  167. end
  168. 19 def when_to_retry(request, response, options)
  169. 842 retry_after = options.retry_after
  170. 842 retry_after = retry_after.call(request, response) if retry_after.respond_to?(:call)
  171. 842 retry_after
  172. end
  173. #
  174. # Attempt to set the request to perform a partial range request.
  175. # This happens if the peer server accepts byte-range requests, and
  176. # the last response contains some body payload.
  177. #
  178. 19 def try_partial_retry(request, response)
  179. 878 response = response.response if response.is_a?(ErrorResponse)
  180. 878 return unless response
  181. 348 unless response.headers.key?("accept-ranges") &&
  182. response.headers["accept-ranges"] == "bytes" && # there's nothing else supported though...
  183. 18 (original_body = response.body)
  184. 330 response.body.close
  185. 295 return
  186. end
  187. 18 request.partial_response = response
  188. 18 size = original_body.bytesize
  189. 16 request.headers["range"] = "bytes=#{size}-"
  190. end
  191. end
  192. 19 module RequestMethods
  193. # number of retries left.
  194. 19 attr_accessor :retries
  195. # a response partially received before.
  196. 19 attr_writer :partial_response
  197. # initializes the request instance, sets the number of retries for the request.
  198. 19 def initialize(*args)
  199. 1238 super
  200. 1238 @retries = @options.max_retries
  201. 1238 @partial_response = nil
  202. end
  203. 19 def response=(response)
  204. 2161 if (partial_response = @partial_response)
  205. 18 if response.is_a?(Response) && response.status == 206
  206. 18 response.from_partial_response(partial_response)
  207. else
  208. partial_response.close
  209. end
  210. 18 @partial_response = nil
  211. end
  212. 2161 super
  213. end
  214. end
  215. 19 module ResponseMethods
  216. 19 def from_partial_response(response)
  217. 18 @status = response.status
  218. 18 @headers = response.headers
  219. 18 @body = response.body
  220. end
  221. end
  222. end
  223. 19 register_plugin :retries, Retries
  224. end
  225. end

lib/httpx/plugins/ssrf_filter.rb

100.0% lines covered

62 relevant lines. 62 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.response = response
  92. 9 request.emit(:response, response)
  93. 9 response
  94. end
  95. 194 allowed_requests = requests.select { |req| responses[requests.index(req)].nil? }
  96. 97 allowed_responses = super(*allowed_requests)
  97. 97 allowed_responses.each_with_index do |res, idx|
  98. 88 req = allowed_requests[idx]
  99. 78 responses[requests.index(req)] = res
  100. end
  101. 97 responses
  102. end
  103. end
  104. 9 module ConnectionMethods
  105. 9 def initialize(*)
  106. begin
  107. 88 super
  108. 8 rescue ServerSideRequestForgeryError => e
  109. # may raise when IPs are passed as options via :addresses
  110. 18 throw(:resolve_error, e)
  111. end
  112. end
  113. 9 def addresses=(addrs)
  114. 88 addrs.reject!(&SsrfFilter.method(:unsafe_ip_address?))
  115. 88 raise ServerSideRequestForgeryError, "#{@origin.host} has no public IP addresses" if addrs.empty?
  116. 18 super
  117. end
  118. end
  119. end
  120. 9 register_plugin :ssrf_filter, SsrfFilter
  121. end
  122. 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. 262 @request = request
  7. 262 @options = @request.options
  8. 262 @session = session
  9. 262 @response_enum = nil
  10. 262 @buffered_chunks = []
  11. end
  12. 19 def each(&block)
  13. 439 return enum_for(__method__) unless block
  14. 280 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. 58 while (chunk = response_enum.next)
  23. 28 block.call(chunk)
  24. end
  25. rescue StopIteration
  26. 18 return
  27. end
  28. end
  29. 262 @request.stream = self
  30. 23 begin
  31. 262 @on_chunk = block
  32. 262 response = @session.request(@request)
  33. 235 response.raise_for_status
  34. ensure
  35. 235 @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. 56 line << chunk
  43. 159 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. 573 raise NoMethodError unless @on_chunk
  53. 573 @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. 470 @request.response || begin
  70. 51 response_enum = each
  71. 91 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. 38 if (response = @request.response)
  81. response.respond_to_missing?(meth, include_private)
  82. else
  83. 38 @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. 238 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. 459 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. 365 val
  113. end
  114. 19 def option_stream_response_class(value)
  115. 1105 value
  116. end
  117. 19 def extend_with_plugin_classes(pl)
  118. 275 return super unless defined?(pl::StreamResponseMethods)
  119. 167 @stream_response_class = @stream_response_class.dup
  120. 167 Options::SET_TEMPORARY_NAME[@stream_response_class, pl]
  121. 167 @stream_response_class.__send__(:include, pl::StreamResponseMethods) if defined?(pl::StreamResponseMethods)
  122. 167 super
  123. end
  124. end
  125. 19 module InstanceMethods
  126. 19 def request(*args, **options)
  127. 688 if args.first.is_a?(Request)
  128. 472 requests = args
  129. 472 request = requests.first
  130. 472 unless request.options.stream && !request.stream
  131. 381 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. 381 return super
  136. end
  137. else
  138. 216 return super unless options[:stream]
  139. 189 requests = build_requests(*args, options)
  140. 189 request = requests.first
  141. end
  142. 280 raise Error, "only 1 response at a time is supported for streaming requests" unless requests.size == 1
  143. 262 @options.stream_response_class.new(request, self)
  144. end
  145. 19 def build_request(verb, uri, params = EMPTY_HASH, options = @options)
  146. 478 return super unless params[:stream]
  147. 307 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. 422 request = @request.root_request if @request.respond_to?(:root_request)
  156. 422 request ||= @request
  157. 422 request.stream
  158. end
  159. end
  160. 19 module ResponseBodyMethods
  161. 19 def initialize(*)
  162. 422 super
  163. 422 @stream = @response.stream
  164. end
  165. 19 def write(chunk)
  166. 781 return super unless @stream
  167. 666 return 0 if chunk.empty?
  168. 573 chunk = decode_chunk(chunk)
  169. 573 @stream.on_chunk(chunk.dup)
  170. 546 chunk.bytesize
  171. end
  172. 19 private
  173. 19 def transition(*)
  174. 170 return if @stream
  175. 143 super
  176. end
  177. end
  178. end
  179. 19 register_plugin :stream, Stream
  180. end
  181. end

lib/httpx/plugins/stream_bidi.rb

93.99% lines covered

183 relevant lines. 172 lines covered and 11 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. 101 super
  21. 101 @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. 99 return super unless @options.stream
  54. 90 request.flush_buffer_on_body do
  55. 341 next unless request.headers_sent
  56. 251 handle(request, stream)
  57. 251 emit(:flush_buffer)
  58. end
  59. 90 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. 373 return super unless @options.stream
  64. 373 super
  65. 373 return if next_chunk
  66. 341 request.transition(:waiting_for_chunk)
  67. 341 throw(:buffer_full)
  68. end
  69. # sets end-stream flag when the request is closed.
  70. 9 def end_stream?(request, next_chunk)
  71. 373 return super unless @options.stream
  72. 373 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. 54 super
  85. 54 @buffer_mutex = Thread::Mutex.new
  86. 54 @oob_mutex = Thread::Mutex.new
  87. 54 @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. 3886 @buffer_mutex.synchronize do
  105. 3886 @oob_mutex.synchronize do
  106. 3886 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. 108 @closed = false
  128. 108 @error = nil
  129. 108 @pipe_read, @pipe_write = IO.pipe
  130. end
  131. 9 def state
  132. 824 @closed ? :closed : :open
  133. end
  134. # noop
  135. 9 def log(**, &_); end
  136. 9 def to_io
  137. 1545 @pipe_read.to_io
  138. end
  139. 9 def wakeup
  140. 251 return if @closed
  141. 206 @pipe_write.write("\0")
  142. end
  143. 9 def call
  144. 200 return if @closed
  145. 200 @pipe_read.readpartial(1)
  146. end
  147. 9 def interests
  148. 824 return if @closed
  149. 815 :r
  150. end
  151. 9 def timeout; end
  152. 9 def inflight?
  153. !@closed
  154. end
  155. 9 def force_close(*)
  156. terminate
  157. end
  158. 9 def terminate
  159. 81 return if @closed
  160. 63 @pipe_write.close
  161. 63 @pipe_read.close
  162. 63 @closed = true
  163. end
  164. 9 def on_error(error)
  165. @error = error
  166. terminate
  167. end
  168. 9 alias_method :on_io_error, :on_error
  169. # noop (the owner connection will take of it)
  170. 9 def handle_socket_timeout(interval); end
  171. end
  172. 9 class << self
  173. 9 def load_dependencies(klass)
  174. 81 klass.plugin(:stream)
  175. end
  176. 9 def extra_options(options)
  177. 81 options.merge(fallback_protocol: "h2")
  178. end
  179. end
  180. 9 module InstanceMethods
  181. 9 def initialize(*)
  182. 108 @signal = Signal.new
  183. 108 super
  184. end
  185. 9 def close(selector = Selector.new)
  186. 81 @signal.terminate
  187. 81 selector.deregister(@signal)
  188. 81 super
  189. end
  190. 9 def select_connection(connection, selector)
  191. 155 return super unless connection.options.stream
  192. 146 super
  193. 146 selector.register(@signal)
  194. 146 connection.signal = @signal
  195. end
  196. 9 def deselect_connection(connection, *)
  197. 92 return super unless connection.options.stream
  198. 83 super
  199. 83 connection.signal = nil
  200. end
  201. end
  202. # Adds synchronization to request operations which may buffer payloads from different
  203. # threads.
  204. 9 module RequestMethods
  205. 9 attr_accessor :headers_sent
  206. 9 def initialize(*)
  207. 81 super
  208. 72 @headers_sent = false
  209. 72 @closed = false
  210. 72 @flush_buffer_on_body_cb = nil
  211. 72 @mutex = Thread::Mutex.new
  212. end
  213. 9 def flush_buffer_on_body(&cb)
  214. 90 @flush_buffer_on_body_cb = on(:body, &cb)
  215. end
  216. 9 def closed?
  217. 373 return super unless @options.stream
  218. 373 @closed
  219. end
  220. 9 def can_buffer?
  221. 806 return super unless @options.stream
  222. 788 super && @state != :waiting_for_chunk
  223. end
  224. # overrides state management transitions to introduce an intermediate
  225. # +:waiting_for_chunk+ state, which the request transitions to once payload
  226. # is buffered.
  227. 9 def transition(nextstate)
  228. 1366 return super unless @options.stream
  229. 1330 headers_sent = @headers_sent
  230. 1175 case nextstate
  231. when :idle
  232. 29 headers_sent = false
  233. 29 if @flush_buffer_on_body_cb
  234. 27 callbacks(:body).delete(@flush_buffer_on_body_cb)
  235. 27 @flush_buffer_on_body_cb = nil
  236. end
  237. when :waiting_for_chunk
  238. 341 return unless @state == :body
  239. when :body
  240. 543 case @state
  241. when :headers
  242. 90 headers_sent = true
  243. when :waiting_for_chunk
  244. # HACK: to allow super to pass through
  245. 251 @state = :headers
  246. end
  247. end
  248. 1328 super.tap do
  249. # delay setting this up until after the first transition to :body
  250. 1328 @headers_sent = headers_sent
  251. end
  252. end
  253. 9 def <<(chunk)
  254. 270 @mutex.synchronize do
  255. 270 if @drainer
  256. 251 @body.clear if @body.respond_to?(:clear)
  257. 251 @drainer = nil
  258. end
  259. 270 @body << chunk
  260. 270 transition(:body)
  261. end
  262. end
  263. 9 def close
  264. 63 return super unless @options.stream
  265. 63 @mutex.synchronize do
  266. 63 return if @closed
  267. 63 @closed = true
  268. end
  269. # last chunk to send which ends the stream
  270. 63 self << ""
  271. end
  272. end
  273. 9 module RequestBodyMethods
  274. 9 def initialize(*, **)
  275. 81 super
  276. 81 return unless @options.stream
  277. 72 @headers.delete("content-length")
  278. 72 return unless @body
  279. 72 return if @body.is_a?(Transcoder::Body::Encoder)
  280. 9 raise Error, "bidirectional streams only allow the usage of the `:body` param to set request bodies." \
  281. "You must encode it yourself if you wish to do so."
  282. end
  283. 9 def empty?
  284. 489 return super unless @options.stream
  285. 462 false
  286. end
  287. end
  288. # overrides the declaration of +@write_buffer+, which is now a thread-safe buffer
  289. # responding to the same API.
  290. 9 module ConnectionMethods
  291. 9 attr_writer :signal
  292. 9 def initialize(*)
  293. 63 super
  294. 63 return unless @options.stream
  295. 54 @write_buffer = BidiBuffer.new(@options.buffer_size)
  296. end
  297. # rebuffers the +@write_buffer+ before calculating interests.
  298. 9 def interests
  299. 4060 return super unless @options.stream
  300. 3886 @write_buffer.rebuffer
  301. 3886 super
  302. end
  303. 9 def call
  304. 744 return super unless @options.stream && (error = @signal.error)
  305. on_error(error)
  306. end
  307. 9 private
  308. 9 def set_parser_callbacks(parser)
  309. 101 return super unless @options.stream
  310. 92 super
  311. 92 parser.on(:flush_buffer) do
  312. 251 @signal.wakeup if @signal
  313. end
  314. end
  315. end
  316. end
  317. 9 register_plugin :stream_bidi, StreamBidi
  318. end
  319. end

lib/httpx/plugins/tracing.rb

89.47% lines covered

57 relevant lines. 51 lines covered and 6 lines missed.
    
  1. # frozen_string_literal: true
  2. 16 module HTTPX::Plugins
  3. #
  4. # This plugin adds a simple interface to integrate request tracing SDKs.
  5. #
  6. # An example of such an integration is the datadog adapter.
  7. #
  8. # https://gitlab.com/os85/httpx/wikis/Tracing
  9. #
  10. 16 module Tracing
  11. 16 class Wrapper
  12. 16 attr_reader :tracers
  13. 16 protected :tracers
  14. 16 def initialize(*tracers)
  15. 54 @tracers = tracers.flat_map do |tracer|
  16. 96 case tracer
  17. when Wrapper
  18. 18 tracer.tracers
  19. else
  20. 90 tracer
  21. end
  22. end.uniq
  23. end
  24. 16 def merge(tracer)
  25. case tracer
  26. when Wrapper
  27. Wrapper.new(*@tracers, *tracer.tracers)
  28. else
  29. Wrapper.new(*@tracers, tracer)
  30. end
  31. end
  32. 16 def freeze
  33. @tracers.each(&:freeze).freeze
  34. super
  35. end
  36. 16 %i[start finish reset enabled?].each do |callback|
  37. 64 class_eval(<<-OUT, __FILE__, __LINE__ + 1)
  38. 4 # proxies ##{callback} calls to wrapper tracers.
  39. 4 def #{callback}(*args) # def start(*args)
  40. 4 @tracers.each { |t| t.#{callback}(*args) } # @tracers.each { |t| t.start(*args) }
  41. end # end
  42. OUT
  43. end
  44. end
  45. # adds support for the following options:
  46. #
  47. # :tracer :: object which responds to #start, #finish and #reset.
  48. 16 module OptionsMethods
  49. 16 private
  50. 16 def option_tracer(tracer)
  51. 167 unless tracer.respond_to?(:start) &&
  52. tracer.respond_to?(:finish) &&
  53. tracer.respond_to?(:reset) &&
  54. tracer.respond_to?(:enabled?)
  55. raise TypeError, "#{tracer} must to respond to `#start(r)`, `#finish` and `#reset` and `#enabled?"
  56. end
  57. 167 tracer = Wrapper.new(@tracer, tracer) if @tracer
  58. 167 tracer
  59. end
  60. end
  61. 16 module RequestMethods
  62. 16 attr_accessor :init_time
  63. # intercepts request initialization to inject the tracing logic.
  64. 16 def initialize(*)
  65. 323 super
  66. 323 @init_time = nil
  67. 323 tracer = @options.tracer
  68. 323 return unless tracer && tracer.enabled?(self)
  69. 152 on(:idle) do
  70. 75 tracer.reset(self)
  71. # request is reset when it's retried.
  72. 75 @init_time = nil
  73. end
  74. 152 on(:headers) do
  75. # the usual request init time (when not including the connection handshake)
  76. # should be the time the request is buffered the first time.
  77. 220 @init_time ||= ::Time.now.utc
  78. 220 tracer.start(self)
  79. end
  80. 372 on(:response) { |response| tracer.finish(self, response) }
  81. end
  82. 16 def response=(*)
  83. # init_time should be set when it's send to a connection.
  84. # However, there are situations where connection initialization fails.
  85. # Example is the :ssrf_filter plugin, which raises an error on
  86. # initialize if the host is an IP which matches against the known set.
  87. # in such cases, we'll just set here right here.
  88. 394 @init_time ||= ::Time.now.utc
  89. 394 super
  90. end
  91. end
  92. # Connection mixin
  93. 16 module ConnectionMethods
  94. 16 def initialize(*)
  95. 304 super
  96. 304 @init_time = ::Time.now.utc
  97. end
  98. 16 def send(request)
  99. # request init time is only the same as the connection init time
  100. # if the connection is going through the connection handshake.
  101. 280 request.init_time ||= @init_time unless open?
  102. 280 super
  103. end
  104. 16 def idling
  105. 75 super
  106. # time of initial request(s) is accounted from the moment
  107. # the connection is back to :idle, and ready to connect again.
  108. 75 @init_time = ::Time.now.utc
  109. end
  110. end
  111. end
  112. 16 register_plugin :tracing, Tracing
  113. 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. 374 response = super
  29. 374 if response
  30. 106 return response unless response.is_a?(Response)
  31. 106 return response unless response.headers.key?("upgrade")
  32. 44 upgrade_protocol = response.headers["upgrade"].split(/ *, */).first
  33. 44 return response unless upgrade_protocol && options.upgrade_handlers.key?(upgrade_protocol)
  34. 44 protocol_handler = options.upgrade_handlers[upgrade_protocol]
  35. 44 return response unless protocol_handler
  36. 44 log { "upgrading to #{upgrade_protocol}..." }
  37. 44 connection = find_connection(request.uri, selector, options)
  38. # do not upgrade already upgraded connections
  39. 44 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. 285 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. 964 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. 14395 @max_connections = options.fetch(:max_connections, Float::INFINITY)
  19. 14395 @max_connections_per_origin = options.fetch(:max_connections_per_origin, Float::INFINITY)
  20. 14395 @pool_timeout = options.fetch(:pool_timeout, POOL_TIMEOUT)
  21. 22196 @resolvers = Hash.new { |hs, resolver_type| hs[resolver_type] = [] }
  22. 14395 @resolver_mtx = Thread::Mutex.new
  23. 14395 @connections = []
  24. 14395 @connection_mtx = Thread::Mutex.new
  25. 14395 @connections_counter = 0
  26. 14395 @max_connections_cond = ConditionVariable.new
  27. 14395 @origin_counters = Hash.new(0)
  28. 21264 @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. 14833 @connection_mtx.synchronize do
  33. 14833 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. 10315 return checkout_new_connection(uri, options) if options.io
  42. 10240 @connection_mtx.synchronize do
  43. 10240 acquire_connection(uri, options) || begin
  44. 9192 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. 18 @max_connections_cond.wait(@connection_mtx, @pool_timeout)
  49. 18 if (conn = acquire_connection(uri, options))
  50. 7 return conn
  51. end
  52. # if one can afford to create a new connection, do it
  53. 11 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. 11 if (conn = @connections.find { |c| c.state == :closed })
  56. 1 drop_connection(conn)
  57. 1 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. 9 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. 9176 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. 8285 @connections_counter += 1
  81. 9158 @origin_counters[uri.origin] += 1
  82. 9158 checkout_new_connection(uri, options)
  83. end
  84. end
  85. end
  86. 30 def checkin_connection(connection)
  87. 10249 return if connection.options.io
  88. 10199 @connection_mtx.synchronize do
  89. 10199 if connection.coalesced? || connection.state == :idle
  90. # when connections coalesce
  91. 57 drop_connection(connection)
  92. 57 return
  93. end
  94. 10142 @connections << connection
  95. 10142 @max_connections_cond.signal
  96. 10142 @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. 10142 Thread.pass
  102. end
  103. end
  104. 30 def checkout_mergeable_connection(connection)
  105. 9147 return if connection.options.io
  106. 9147 @connection_mtx.synchronize do
  107. 9147 idx = @connections.find_index do |ch|
  108. 330 ch != connection && ch.mergeable?(connection)
  109. end
  110. 9147 @connections.delete_at(idx) if idx
  111. end
  112. end
  113. 30 def reset_resolvers
  114. 17926 @resolver_mtx.synchronize { @resolvers.clear }
  115. end
  116. 30 def checkout_resolver(options)
  117. 8919 resolver_type = options.resolver_class
  118. 8919 @resolver_mtx.synchronize do
  119. 8919 resolvers = @resolvers[resolver_type]
  120. 8919 idx = resolvers.find_index do |res|
  121. 30 res.options == options
  122. end
  123. 8919 resolvers.delete_at(idx) if idx
  124. end || checkout_new_resolver(resolver_type, options)
  125. end
  126. 30 def checkin_resolver(resolver)
  127. 655 resolver_class = resolver.class
  128. 655 resolver = resolver.multi
  129. # a multi requires all sub-resolvers being closed in order to be
  130. # correctly checked back in.
  131. 655 return unless resolver.closed?
  132. 627 @resolver_mtx.synchronize do
  133. 627 resolvers = @resolvers[resolver_class]
  134. 627 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. 10276 idx = @connections.find_index do |connection|
  149. 1363 connection.match?(uri, options)
  150. end
  151. 10276 return unless idx
  152. 1064 @connections.delete_at(idx)
  153. end
  154. 30 def checkout_new_connection(uri, options)
  155. 9242 connection = options.connection_class.new(uri, options)
  156. 9310 connection.log(level: 2) { "created connection##{connection.object_id} in pool##{object_id}" }
  157. 9224 connection
  158. end
  159. 30 def checkout_new_resolver(resolver_type, options)
  160. 8891 resolver = if resolver_type.multi?
  161. 8713 Resolver::Multi.new(resolver_type, options)
  162. else
  163. 178 resolver_type.new(options)
  164. end
  165. 8977 resolver.log(level: 2) { "created resolver##{resolver.object_id} in pool##{object_id}" }
  166. 8891 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. 14891 if connection
  172. 58 @connections.delete(connection)
  173. else
  174. 14833 connection = @connections.shift
  175. 14833 return unless connection
  176. end
  177. 5356 @connections_counter -= 1
  178. 5928 @origin_conds.delete(connection.origin) if (@origin_counters[connection.origin.to_s] -= 1).zero?
  179. 5928 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. 12626 @verb = verb.to_s.upcase
  53. 12626 @uri = Utils.to_uri(uri)
  54. 12625 @headers = options.headers.dup
  55. 12625 merge_headers(params.delete(:headers)) if params.key?(:headers)
  56. 12625 @query_params = params.delete(:params) if params.key?(:params)
  57. 12625 @body = options.request_body_class.new(@headers, options, **params)
  58. 12607 @options = @body.options
  59. 12607 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. 12579 raise UnsupportedSchemeError, "#{@uri}: #{@uri.scheme}: unsupported URI scheme" unless ALLOWED_URI_SCHEMES.include?(@uri.scheme)
  66. 12565 @state = :idle
  67. 12565 @response = @drainer = @peer_address = @informational_status = nil
  68. 12565 @ping = false
  69. 12565 @persistent = @options.persistent
  70. 12565 @active_timeouts = []
  71. end
  72. # dupped initialization
  73. 30 def initialize_dup(orig)
  74. 1330 super
  75. 1330 @uri = orig.instance_variable_get(:@uri).dup
  76. 1330 @headers = orig.instance_variable_get(:@headers).dup
  77. 1330 @body = orig.instance_variable_get(:@body).dup
  78. end
  79. 30 def complete!(response = @response)
  80. 9725 emit(:complete, response)
  81. end
  82. # whether request has been buffered with a ping
  83. 30 def ping?
  84. 878 @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. 21512 @options.timeout[:read_timeout]
  93. end
  94. # the write timeout defined for this request.
  95. 30 def write_timeout
  96. 21512 @options.timeout[:write_timeout]
  97. end
  98. # the request timeout defined for this request.
  99. 30 def request_timeout
  100. 21193 @options.timeout[:request_timeout]
  101. end
  102. 30 def persistent?
  103. 5990 @persistent
  104. end
  105. # if the request contains trailer headers
  106. 30 def trailers?
  107. 3636 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. 50810 return :r if @state == :done || @state == :expect
  116. 5823 :w
  117. end
  118. 30 def can_buffer?
  119. 32275 @state != :done
  120. end
  121. # merges +h+ into the instance of HTTPX::Headers of the request.
  122. 30 def merge_headers(h)
  123. 1397 @headers = @headers.merge(h)
  124. 1397 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. 4744 @uri.scheme
  130. end
  131. # sets the +response+ on this request.
  132. 30 def response=(response)
  133. 11991 return unless response
  134. 10877 case response
  135. when Response
  136. 10272 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. 1719 response.error.connection = nil if response.error.respond_to?(:connection=)
  148. end
  149. 11854 @response = response
  150. 11854 emit(:response_started, response)
  151. end
  152. # returnns the URI path of the request +uri+.
  153. 30 def path
  154. 11458 path = uri.path.dup
  155. 11458 path = +"" if path.nil?
  156. 11458 path << "/" if path.empty?
  157. 11458 path << "?#{query}" unless query.empty?
  158. 11458 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. 11004 @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. 5102 @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. 12642 return @query if defined?(@query)
  182. 10368 query = []
  183. 10368 if (q = @query_params) && !q.empty?
  184. 191 query << Transcoder::Form.encode(q)
  185. end
  186. 10368 query << @uri.query if @uri.query
  187. 10368 @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. 11382 return nil if @body.nil?
  192. 11382 @drainer ||= @body.each
  193. 11382 chunk = @drainer.next.dup
  194. 7435 emit(:body_chunk, chunk)
  195. 7435 chunk
  196. rescue StopIteration
  197. 3919 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. 47529 case nextstate
  214. when :idle
  215. 1255 @body.rewind
  216. 1255 @ping = false
  217. 1255 @response = nil
  218. 1255 @drainer = nil
  219. 1255 @active_timeouts.clear
  220. when :headers
  221. 14107 return unless @state == :idle
  222. when :body
  223. 14359 return unless @state == :headers ||
  224. @state == :expect
  225. 11601 if @headers.key?("expect")
  226. 515 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. 387 return if @state == :expect # do not re-set it
  233. 146 nextstate = :expect
  234. end
  235. end
  236. when :trailers
  237. 11253 return unless @state == :body
  238. when :done
  239. 11262 return if @state == :expect
  240. end
  241. 45921 log(level: 3) { "#{@state}] -> #{nextstate}" }
  242. 45665 @state = nextstate
  243. 45665 emit(@state, self)
  244. 21115 nil
  245. end
  246. # whether the request supports the 100-continue handshake and already processed the 100 response.
  247. 30 def expects?
  248. 9928 @headers["expect"] == "100-continue" && @informational_status == 100 && !@response
  249. end
  250. 30 def set_timeout_callback(event, &callback)
  251. 109152 clb = once(event, &callback)
  252. # reset timeout callbacks when requests get rerouted to a different connection
  253. 109152 once(:idle) do
  254. 6929 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. 12634 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. 12616 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. 12616 @headers = h
  26. 12616 @body = self.class.initialize_body(params)
  27. 12616 @options = options.merge(params)
  28. 12616 if @body
  29. 3847 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. 3847 @headers["content-type"] ||= @body.content_type
  35. 3847 @headers["content-length"] = @body.bytesize unless unbounded_body?
  36. end
  37. 12607 super(@body)
  38. end
  39. # consumes and yields the request payload in chunks.
  40. 30 def each(&block)
  41. 8169 return enum_for(__method__) unless block
  42. 4089 return if @body.nil?
  43. 4008 body = stream(@body)
  44. 4008 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. 2366 elsif body.respond_to?(:each)
  51. 839 body.each(&block)
  52. else
  53. 1528 block[body.to_s]
  54. end
  55. end
  56. 30 def close
  57. 532 @body.close if @body.respond_to?(:close)
  58. end
  59. # if the +@body+ is rewindable, it rewinnds it.
  60. 30 def rewind
  61. 1327 return if empty?
  62. 208 @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. 24506 return true if @body.nil?
  67. 10183 return false if chunked?
  68. 10075 @body.bytesize.zero?
  69. end
  70. # returns the +@body+ payload size in bytes.
  71. 30 def bytesize
  72. 4317 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. 4008 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. 4480 return @unbounded_body if defined?(@unbounded_body)
  83. 3928 @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. 24255 @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. 12436 if (body = params.delete(:body))
  102. # @type var body: bodyIO
  103. 1761 Transcoder::Body.encode(body)
  104. 10675 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. 8871 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. 9230 if Utils.in_ractor?
  19. Ractor.store_if_absent(:httpx_supported_ip_families) { find_supported_ip_families }
  20. else
  21. 9230 @supported_ip_families ||= find_supported_ip_families
  22. end
  23. end
  24. 30 def generate_id
  25. 1074 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. 2148 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. 1023 Resolv::DNS::Message.new(message_id).tap do |query|
  34. 1074 query.rd = 1
  35. 1074 query.add_question(hostname, type)
  36. 101 end.encode
  37. end
  38. 30 def decode_dns_answer(payload)
  39. 50 begin
  40. 824 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. 815 return :no_domain_found if message.rcode == Resolv::DNS::RCode::NXDomain
  46. 371 return :message_truncated if message.tc == 1
  47. 357 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. 343 addresses = []
  56. 343 now = Utils.now
  57. 343 message.each_answer do |question, _, value|
  58. 1253 case value
  59. when Resolv::DNS::Resource::IN::CNAME
  60. 30 addresses << {
  61. "name" => question.to_s,
  62. 30 "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. 1248 addresses << {
  68. "name" => question.to_s,
  69. 1248 "TTL" => (now + value.ttl),
  70. "data" => value.address.to_s,
  71. }
  72. end
  73. end
  74. 343 [:ok, addresses]
  75. end
  76. 30 private
  77. 30 def id_synchronize(&block)
  78. 1074 @identifier_mutex.synchronize(&block)
  79. end
  80. 30 def find_supported_ip_families
  81. 28 list = Socket.ip_address_list
  82. 1 begin
  83. 113 if list.any? { |a| a.ipv6? && !a.ipv6_loopback? && !a.ipv6_linklocal? }
  84. 1 [Socket::AF_INET6, Socket::AF_INET]
  85. else
  86. 27 [Socket::AF_INET]
  87. end
  88. rescue NotImplementedError
  89. [Socket::AF_INET]
  90. 7 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. 15109 return Ractor.store_if_absent(:"httpx_resolver_cache_#{label}") { new } if Utils.in_ractor?
  21. 15109 @cache ||= CACHE_MUTEX.synchronize do
  22. 28 @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. 8555 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. 8555 [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. 758 ips = if Utils.in_ractor?
  41. Ractor.store_if_absent(:httpx_hosts_resolver) { Resolv::Hosts.new }
  42. else
  43. 758 HOSTS
  44. end.getaddresses(hostname)
  45. 758 return if ips.empty?
  46. 1074 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. 7838 return unless lookups.key?(hostname)
  52. 7073 entries = lookups[hostname]
  53. 7073 return unless entries
  54. 7073 entries.delete_if do |address|
  55. 16782 address["TTL"] < ttl
  56. end
  57. 7073 if entries.empty?
  58. 20 lookups.delete(hostname)
  59. 20 hostnames.delete(hostname)
  60. end
  61. 7073 ips = entries.flat_map do |address|
  62. 16762 if (als = address["alias"])
  63. 9 _get(als, lookups, hostnames, ttl)
  64. else
  65. 16753 Resolver::Entry.new(address["data"], address["TTL"])
  66. end
  67. end.compact
  68. 7073 ips unless ips.empty?
  69. end
  70. 30 def _set(hostname, family, entries, lookups, hostnames)
  71. # lru cleanup
  72. 6737 while lookups.size >= MAX_CACHE_SIZE
  73. 1692 hs = hostnames.shift
  74. 1692 lookups.delete(hs)
  75. end
  76. 6549 hostnames << hostname
  77. 6549 lookups[hostname] ||= [] # when there's no default proc
  78. 5826 case family
  79. when Socket::AF_INET6
  80. 50 lookups[hostname].concat(entries)
  81. when Socket::AF_INET
  82. 6499 lookups[hostname].unshift(*entries)
  83. end
  84. 6549 entries.each do |entry|
  85. 6644 name = entry["name"]
  86. 6644 next unless name != hostname
  87. 222 lookups[name] ||= []
  88. 204 case family
  89. when Socket::AF_INET6
  90. 20 lookups[name] << entry
  91. when Socket::AF_INET
  92. 202 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. 141 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. 5972 @lookups = Hash.new { |h, k| h[k] = [] }
  10. 44 @lookup_mutex = Thread::Mutex.new
  11. end
  12. 30 def get(hostname)
  13. 7829 now = Utils.now
  14. 7829 synchronize do |lookups, hostnames|
  15. 7829 _get(hostname, lookups, hostnames, now)
  16. end
  17. end
  18. 30 def set(hostname, family, entries)
  19. 6549 synchronize do |lookups, hostnames|
  20. 6549 _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. 28818 @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. 27661 @expires_in = expires_in
  12. 27661 @address = address.is_a?(IPAddr) ? address : IPAddr.new(address.to_s)
  13. 19907 super(@address)
  14. rescue IPAddr::InvalidAddressError
  15. 7754 raise unless rescue_on_convert
  16. 24 @address = address.to_s
  17. 24 super(@address)
  18. end
  19. 30 def expired?
  20. 2603 @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. 25 deactivate
  260. else
  261. 45 disconnect
  262. end
  263. else
  264. resolve
  265. end
  266. end
  267. end
  268. end

lib/httpx/resolver/multi.rb

100.0% lines covered

45 relevant lines. 45 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. 8713 @current_selector = @current_session = nil
  9. 8713 @options = options
  10. 8713 @resolver_options = @options.resolver_options
  11. 8713 ip_families = options.ip_families || Resolver.supported_ip_families
  12. 8713 @resolvers = ip_families.map do |ip_family|
  13. 8785 resolver = resolver_type.new(ip_family, options)
  14. 8785 resolver.multi = self
  15. 8785 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. 8723 @current_selector = s
  23. 17520 @resolvers.each { |r| r.current_selector = s }
  24. end
  25. 30 def current_session=(s)
  26. 8723 @current_session = s
  27. 17520 @resolvers.each { |r| r.current_session = s }
  28. end
  29. 30 def log(*args, **kwargs, &blk)
  30. 35033 @resolvers.each { |r| r.log(*args, **kwargs, &blk) }
  31. end
  32. 30 def closed?
  33. 542 @resolvers.all?(&:closed?)
  34. end
  35. 30 def early_resolve(connection)
  36. 8728 hostname = connection.peer.host
  37. 8728 addresses = @resolver_options[:cache] && (connection.addresses || nolookup_resolve(hostname, connection.options))
  38. 8728 return false unless addresses
  39. 8111 ip_families = connection.options.ip_families
  40. 8111 resolved = false
  41. 8472 addresses.group_by(&:family).sort { |(f1, _), (f2, _)| f2 <=> f1 }.each do |family, addrs|
  42. 8453 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. 16932 resolver = @resolvers.find { |r| r.family == family } || @resolvers.first
  46. 8453 next unless resolver # this should ever happen
  47. # it does not matter which resolver it is, as early-resolve code is shared.
  48. 8453 resolver.emit_addresses(connection, family, addrs, true)
  49. 8417 resolved = true
  50. end
  51. 8075 resolved
  52. end
  53. 30 def lazy_resolve(connection)
  54. 618 @resolvers.each do |resolver|
  55. 671 resolver.lazy_resolve(connection)
  56. end
  57. end
  58. 30 private
  59. 30 def nolookup_resolve(hostname, options)
  60. 8410 options.resolver_cache.resolve(hostname)
  61. end
  62. end
  63. end

lib/httpx/resolver/native.rb

92.22% lines covered

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

lib/httpx/resolver/resolver.rb

95.1% lines covered

102 relevant lines. 97 lines covered and 5 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. 8713 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. 8963 @family = family
  28. 8963 @record_type = RECORD_TYPES[family]
  29. 8963 @options = options
  30. 8963 @connections = []
  31. end
  32. 30 def each_connection(&block)
  33. 516 enum_for(__method__) unless block
  34. 516 return unless @connections
  35. 516 @connections.each(&block)
  36. end
  37. 30 def close; end
  38. 30 alias_method :terminate, :close
  39. 30 def force_close(*args)
  40. 504 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. 75 false
  52. end
  53. 30 def emit_addresses(connection, family, addresses, early_resolve = false)
  54. 28500 addresses.map! { |address| address.is_a?(Resolver::Entry) ? address : Resolver::Entry.new(address) }
  55. # double emission check, but allow early resolution to work
  56. 8962 conn_addrs = connection.addresses
  57. 8962 return if !early_resolve && conn_addrs && !conn_addrs.empty? && !addresses.intersect?(conn_addrs)
  58. 8962 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. 8962 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. 399 (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. 24 log { "resolver #{FAMILY_TYPES[RECORD_TYPES[family]]}: applying resolution delay..." }
  75. 24 @current_selector.after(0.05) do
  76. # double emission check
  77. 19 unless connection.addresses && addresses.intersect?(connection.addresses)
  78. 19 emit_resolved_connection(connection, addresses, early_resolve)
  79. end
  80. end
  81. else
  82. 8938 emit_resolved_connection(connection, addresses, early_resolve)
  83. end
  84. end
  85. 30 def handle_error(error)
  86. 48 if error.respond_to?(:connection) &&
  87. error.respond_to?(:host)
  88. 27 @connections.delete(error.connection)
  89. 27 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_io_error(e)
  97. on_error(e)
  98. force_close(true)
  99. end
  100. 30 def on_error(error)
  101. 14 handle_error(error)
  102. 14 disconnect
  103. end
  104. 30 def early_resolve(connection, hostname: connection.peer.host) # rubocop:disable Naming/PredicateMethod
  105. 5 addresses = @resolver_options[:cache] && (connection.addresses || @options.resolver_cache.resolve(hostname))
  106. 5 return false unless addresses
  107. 12 addresses = addresses.select { |addr| addr.family == @family }
  108. 3 return false if addresses.empty?
  109. emit_addresses(connection, @family, addresses, true)
  110. true
  111. end
  112. 30 def lazy_resolve(connection)
  113. 671 return unless @current_session && @current_selector
  114. 671 conn_to_resolve = @current_session.try_clone_connection(connection, @current_selector, @family)
  115. 671 self << conn_to_resolve
  116. 650 return if empty?
  117. # both the resolver and the connection it's resolving must be pinned to the session
  118. 524 @current_session.pin(conn_to_resolve, @current_selector)
  119. 524 @current_session.select_resolver(self, @current_selector)
  120. end
  121. 30 private
  122. 30 def emit_resolved_connection(connection, addresses, early_resolve)
  123. begin
  124. 8957 connection.addresses = addresses
  125. 8905 return if connection.state == :closed
  126. 8904 resolve_connection(connection)
  127. 24 rescue StandardError => e
  128. 52 if early_resolve
  129. 36 connection.force_close
  130. 36 throw(:resolve_error, e)
  131. else
  132. 16 emit_connection_error(connection, e)
  133. end
  134. end
  135. end
  136. 30 def emit_resolve_error(connection, hostname = connection.peer.host, ex = nil)
  137. 274 emit_connection_error(connection, resolve_error(hostname, ex))
  138. end
  139. 30 def resolve_error(hostname, ex = nil)
  140. 274 return ex if ex.is_a?(ResolveError) || ex.is_a?(ResolveTimeoutError)
  141. 84 message = ex ? ex.message : "Can't resolve #{hostname}"
  142. 84 error = ResolveError.new(message)
  143. 84 error.set_backtrace(ex ? ex.backtrace : caller)
  144. 84 error
  145. end
  146. 30 def resolve_connection(connection)
  147. 8904 @current_session.__send__(:on_resolver_connection, connection, @current_selector)
  148. end
  149. 30 def emit_connection_error(connection, error)
  150. 290 return connection.handle_connect_error(error) if connection.connecting?
  151. 7 connection.on_error(error)
  152. end
  153. 30 def disconnect
  154. 674 close
  155. 674 return unless closed?
  156. 674 @current_session.deselect_resolver(self, @current_selector)
  157. end
  158. end
  159. end

lib/httpx/resolver/system.rb

95.45% lines covered

154 relevant lines. 147 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. 113 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. 467 @pipe_read.to_io
  65. end
  66. 30 def call
  67. 99 case @state
  68. when :open
  69. 99 consume
  70. end
  71. 29 nil
  72. end
  73. 30 def interests
  74. 311 return if @queries.empty?
  75. 311 :r
  76. end
  77. 30 def timeout
  78. 311 _, connection = @queries.first
  79. 311 return unless connection
  80. 311 timeouts = @timeouts[connection.peer.host]
  81. 311 return if timeouts.empty?
  82. 311 log(level: 2) { "resolver #{FAMILY_TYPES[@record_type]}: next timeout #{timeouts.first} secs... (#{timeouts.size - 1} left)" }
  83. 311 timeouts.first
  84. end
  85. 30 def lazy_resolve(connection)
  86. 169 @connections << connection
  87. 169 resolve
  88. 169 return if empty?
  89. 169 @current_session.select_resolver(self, @current_selector)
  90. end
  91. 30 def early_resolve(_, **) # rubocop:disable Naming/PredicateMethod
  92. 169 false
  93. end
  94. 30 def handle_socket_timeout(interval)
  95. 14 error = HTTPX::ResolveTimeoutError.new(interval, "timed out while waiting on select")
  96. 14 error.set_backtrace(caller)
  97. 14 @queries.each do |_, connection| # rubocop:disable Style/HashEachMethods
  98. 14 emit_resolve_error(connection, connection.peer.host, error) if @connections.delete(connection)
  99. end
  100. 28 while (connection = @connections.shift)
  101. emit_resolve_error(connection, connection.peer.host, error)
  102. end
  103. 14 close_or_resolve
  104. end
  105. 30 private
  106. 30 def transition(nextstate)
  107. 338 case nextstate
  108. when :idle
  109. @timeouts.clear
  110. when :open
  111. 169 return unless @state == :idle
  112. 169 @pipe_read, @pipe_write = IO.pipe
  113. when :closed
  114. 169 return unless @state == :open
  115. 169 @pipe_write.close
  116. 169 @pipe_read.close
  117. end
  118. 338 @state = nextstate
  119. end
  120. 30 def consume
  121. 268 return if @connections.empty?
  122. 268 event = @pipe_read.read_nonblock(1, exception: false)
  123. 268 return if event == :wait_readable
  124. 99 raise ResolveError, "socket pipe closed unexpectedly" if event.nil?
  125. 99 case event.unpack1("C")
  126. when DONE
  127. 168 *pair, addrs = @pipe_mutex.synchronize { @ips.pop }
  128. 84 if pair
  129. 84 @queries.delete(pair)
  130. 84 family, connection = pair
  131. 84 @connections.delete(connection)
  132. 168 catch(:coalesced) { emit_addresses(connection, family, addrs) }
  133. end
  134. when ERROR
  135. 30 *pair, error = @pipe_mutex.synchronize { @ips.pop }
  136. 15 if pair && error
  137. 15 @queries.delete(pair)
  138. 15 _, connection = pair
  139. 15 @connections.delete(connection)
  140. 15 emit_resolve_error(connection, connection.peer.host, error)
  141. end
  142. end
  143. 99 return disconnect if @connections.empty?
  144. resolve
  145. rescue StandardError => e
  146. on_error(e)
  147. end
  148. 30 def resolve(connection = nil, hostname = nil)
  149. 169 @connections.shift until @connections.empty? || @connections.first.state != :closed
  150. 169 connection ||= @connections.first
  151. 169 raise Error, "no URI to resolve" unless connection
  152. 169 return unless @queries.empty?
  153. 169 hostname ||= connection.peer.host
  154. 169 scheme = connection.origin.scheme
  155. log do
  156. "resolver: resolve IDN #{connection.peer.non_ascii_hostname} as #{hostname}"
  157. 169 end if connection.peer.non_ascii_hostname
  158. 169 transition(:open)
  159. 169 ip_families = connection.options.ip_families || Resolver.supported_ip_families
  160. 169 ip_families.each do |family|
  161. 204 @queries << [family, connection]
  162. end
  163. 169 async_resolve(connection, hostname, scheme)
  164. 169 consume
  165. end
  166. 30 def async_resolve(connection, hostname, scheme)
  167. 169 families = connection.options.ip_families || Resolver.supported_ip_families
  168. 169 log { "resolver: query for #{hostname}" }
  169. 169 timeouts = @timeouts[connection.peer.host]
  170. 169 resolve_timeout = timeouts.first
  171. 169 Thread.start do
  172. 169 Thread.current.report_on_exception = false
  173. begin
  174. 169 addrs = if resolve_timeout
  175. 169 Timeout.timeout(resolve_timeout) do
  176. 169 __addrinfo_resolve(hostname, scheme)
  177. end
  178. else
  179. __addrinfo_resolve(hostname, scheme)
  180. end
  181. 154 addrs = addrs.sort_by(&:afamily).group_by(&:afamily)
  182. 154 families.each do |family|
  183. 189 addresses = addrs[family]
  184. 189 next unless addresses
  185. 154 addresses.map!(&:ip_address)
  186. 154 addresses.uniq!
  187. 154 @pipe_mutex.synchronize do
  188. 154 @ips.unshift([family, connection, addresses])
  189. 154 @pipe_write.putc(DONE) unless @pipe_write.closed?
  190. end
  191. end
  192. rescue StandardError => e
  193. 15 if e.is_a?(Timeout::Error)
  194. 1 timeouts.shift
  195. 1 retry unless timeouts.empty?
  196. 1 e = ResolveTimeoutError.new(resolve_timeout, e.message)
  197. 1 e.set_backtrace(e.backtrace)
  198. end
  199. 15 @pipe_mutex.synchronize do
  200. 15 families.each do |family|
  201. 15 @ips.unshift([family, connection, e])
  202. 15 @pipe_write.putc(ERROR) unless @pipe_write.closed?
  203. end
  204. end
  205. end
  206. end
  207. 169 Thread.pass
  208. end
  209. 30 def close_or_resolve
  210. # drop already closed connections
  211. 14 @connections.shift until @connections.empty? || @connections.first.state != :closed
  212. 14 if (@connections - @queries.map(&:last)).empty?
  213. 14 disconnect
  214. else
  215. resolve
  216. end
  217. end
  218. 30 def __addrinfo_resolve(host, scheme)
  219. 169 Addrinfo.getaddrinfo(host, scheme, Socket::AF_UNSPEC, Socket::SOCK_STREAM)
  220. end
  221. end
  222. 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. 11274 @request = request
  52. 11274 @options = request.options
  53. 11274 @version = version
  54. 11274 @status = Integer(status)
  55. 11274 @headers = @options.headers_class.new(headers)
  56. 11274 @body = @options.response_body_class.new(self, @options)
  57. 11274 @finished = complete?
  58. 11274 @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. 15091 @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. 11769 @content_type ||= ContentType.new(@headers["content-type"])
  86. end
  87. # returns whether the response has been fully fetched.
  88. 30 def finished?
  89. 17728 @finished
  90. end
  91. # marks the response as finished, freezes the headers.
  92. 30 def finish!
  93. 10005 @finished = true
  94. 10005 @headers.freeze
  95. end
  96. # returns whether the response contains body payload.
  97. 30 def bodyless?
  98. 11274 @request.verb == "HEAD" ||
  99. @status < 200 || # informational response
  100. @status == 204 ||
  101. @status == 205 ||
  102. @status == 304 || begin
  103. 10765 content_length = @headers["content-length"]
  104. 10765 return false if content_length.nil?
  105. 9073 content_length == "0"
  106. end
  107. end
  108. 30 def complete?
  109. 11274 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. 808 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. 754 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. 11727 @header_value = header_value
  175. 11727 @mime_type = @charset = nil
  176. 11727 @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. 11454 return @charset if @initialized
  192. 11454 load
  193. 11454 @charset
  194. end
  195. 30 private
  196. 30 def load
  197. 11727 m = @header_value.to_s[MIME_TYPE_RE, 1]
  198. 11727 m && @mime_type = m.strip.downcase
  199. 11727 c = @header_value.to_s[CHARSET_RE, 1]
  200. 11727 c && @charset = c.strip.delete('"')
  201. 11727 @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. 1834 @request = request
  225. 1834 @response = request.response if request.response.is_a?(Response)
  226. 1834 @error = error
  227. 1834 @options = request.options
  228. 1834 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. 1919 true
  241. end
  242. 30 def finish!; end
  243. # raises the wrapped exception.
  244. 30 def raise_for_status
  245. 106 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. 11454 @response = response
  16. 11454 @headers = response.headers
  17. 11454 @options = options
  18. 11454 @window_size = options.window_size
  19. 11454 @encodings = []
  20. 11454 @length = 0
  21. 11454 @buffer = nil
  22. 11454 @reader = nil
  23. 11454 @state = :idle
  24. # initialize response encoding
  25. 11454 @encoding = if (enc = response.content_type.charset)
  26. 182 begin
  27. 1849 Encoding.find(enc)
  28. rescue ArgumentError
  29. 36 Encoding::BINARY
  30. end
  31. else
  32. 9605 Encoding::BINARY
  33. end
  34. 11454 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. 14950 return if @state == :closed
  47. 14950 return 0 if chunk.empty?
  48. 14384 chunk = decode_chunk(chunk)
  49. 14384 transition(:open)
  50. 14384 @buffer.write(chunk)
  51. 14384 @response.emit(:chunk_received, chunk)
  52. 14366 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. 5634 return "".b unless @buffer
  90. 5224 @buffer.to_s
  91. end
  92. 30 alias_method :to_str, :to_s
  93. # whether the payload is empty.
  94. 30 def empty?
  95. 43 @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. 987 if @buffer
  116. 704 @buffer.close
  117. 704 @buffer = nil
  118. end
  119. 987 @length = 0
  120. 987 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. 11454 @inflaters = nil
  148. 11454 return unless @headers.key?("content-encoding")
  149. 225 return unless @options.decompress_response_body
  150. 207 @inflaters = @headers.get("content-encoding").filter_map do |encoding|
  151. 207 next if encoding == "identity"
  152. 207 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. 207 break unless inflater
  156. 207 @encodings << encoding
  157. 207 inflater
  158. end
  159. end
  160. # passes the +chunk+ through all inflaters to decode it.
  161. 30 def decode_chunk(chunk)
  162. 54 @inflaters.reverse_each do |inflater|
  163. 551 chunk = inflater.call(chunk)
  164. 14744 end if @inflaters
  165. 13304 @length += chunk.bytesize
  166. 14745 chunk
  167. end
  168. # tries transitioning the body STM to the +nextstate+.
  169. 30 def transition(nextstate)
  170. 13840 case nextstate
  171. when :open
  172. 14384 return unless @state == :idle
  173. 8975 @buffer = Response::Buffer.new(
  174. threshold_size: @options.body_threshold_size,
  175. bytesize: @length,
  176. encoding: @encoding
  177. )
  178. when :closed
  179. 960 return if @state == :closed
  180. end
  181. 9908 @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. 9197 @threshold_size = threshold_size
  14. 9197 @bytesize = bytesize
  15. 9197 @encoding = encoding
  16. 9197 @buffer = StringIO.new("".b)
  17. 9197 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. 13388 @bytesize += chunk.bytesize
  39. 14841 try_upgrade_buffer
  40. 14841 @buffer.write(chunk)
  41. end
  42. # returns the buffered content as a string.
  43. 30 def to_s
  44. 4778 case @buffer
  45. when StringIO
  46. 527 begin
  47. 5242 @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. 830 @buffer.close
  64. 830 @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. 14841 return unless @bytesize > @threshold_size
  86. 554 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

92.36% lines covered

144 relevant lines. 133 lines covered and 11 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, :each
  27. 30 def initialize
  28. 9554 @timers = Timers.new
  29. 9554 @selectables = []
  30. 9554 @is_timer_interval = false
  31. end
  32. 30 def empty?
  33. 34052 @selectables.empty? && @timers.empty?
  34. end
  35. 30 def next_tick
  36. 34053 catch(:jump_tick) do
  37. 34053 timeout = next_timeout
  38. 34053 if timeout && timeout.negative?
  39. @timers.fire
  40. throw(:jump_tick)
  41. end
  42. 2475 begin
  43. 34053 select(timeout) do |c|
  44. 32937 c.log(level: 2) { "[#{c.state}] selected from selector##{object_id} #{" after #{timeout} secs" unless timeout.nil?}..." }
  45. 32752 c.call
  46. end
  47. 33807 @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. 9296 selectables = @selectables.reject(&:inflight?)
  56. 9296 selectables.delete_if do |sel|
  57. 3651 sel.terminate
  58. 3642 sel.state == :closed
  59. end
  60. 9288 until selectables.empty?
  61. 1 next_tick
  62. selectables &= @selectables
  63. end
  64. end
  65. 30 def find_resolver(options)
  66. 8897 res = @selectables.find do |c|
  67. 66 c.is_a?(Resolver::Resolver) && options == c.options
  68. end
  69. 8897 res.multi if res
  70. end
  71. 30 def each_connection(&block)
  72. 43116 return enum_for(__method__) unless block
  73. 21558 @selectables.each do |c|
  74. 2957 case c
  75. when Resolver::Resolver
  76. 516 c.each_connection(&block)
  77. when Connection
  78. 2514 yield c
  79. end
  80. end
  81. end
  82. 30 def find_connection(request_uri, options)
  83. 11736 each_connection.find do |connection|
  84. 1515 connection.match?(request_uri, options)
  85. end
  86. end
  87. 30 def find_mergeable_connection(connection)
  88. 9183 each_connection.find do |ch|
  89. 698 ch != connection && ch.mergeable?(connection)
  90. end
  91. end
  92. # deregisters +io+ from selectables.
  93. 30 def deregister(io)
  94. 11283 @selectables.delete(io)
  95. end
  96. # register +io+.
  97. 30 def register(io)
  98. 11648 return if @selectables.include?(io)
  99. 10882 @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. 34053 if @selectables.empty?
  109. 173 sleep(interval) if interval
  110. 154 return
  111. end
  112. # @type var r: (selectable | Array[selectable])?
  113. # @type var w: (selectable | Array[selectable])?
  114. 33880 r, w = nil
  115. 33880 @selectables.delete_if do |io|
  116. 35761 interests = io.interests
  117. 35761 is_closed = io.state == :closed
  118. 35761 next(is_closed) if is_closed
  119. 35658 io.log(level: 2) do
  120. 185 "[#{io.state}] registering in selector##{object_id} for select (#{interests})#{" for #{interval} seconds" unless interval.nil?}"
  121. end
  122. 35658 if READABLE.include?(interests)
  123. 22858 r = r.nil? ? io : (Array(r) << io)
  124. end
  125. 35658 if WRITABLE.include?(interests)
  126. 12673 w = w.nil? ? io : (Array(w) << io)
  127. end
  128. 35658 is_closed
  129. end
  130. 31273 case r
  131. when Array
  132. 865 w = Array(w) unless w.nil?
  133. 865 select_many(r, w, interval, &block)
  134. when nil
  135. 10816 case w
  136. when Array
  137. 57 select_many(r, w, interval, &block)
  138. when nil
  139. 132 return unless interval && @selectables.any?
  140. # no selectables
  141. # TODO: replace with sleep?
  142. 38 select_many(r, w, interval, &block)
  143. else
  144. 11698 select_one(w, :w, interval, &block)
  145. end
  146. else
  147. 19658 case w
  148. when Array
  149. 5 select_many(Array(r), w, interval, &block)
  150. when nil
  151. 20346 select_one(r, :r, interval, &block)
  152. else
  153. 777 if r == w
  154. 475 select_one(r, :rw, interval, &block)
  155. else
  156. 302 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. 58 begin
  163. 1267 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_io_error(e)
  168. end
  169. rescue StandardError => e
  170. (Array(r) + Array(w)).each do |sel|
  171. sel.on_error(e)
  172. end
  173. return
  174. rescue Exception => e # rubocop:disable Lint/RescueException
  175. 42 (Array(r) + Array(w)).each do |sel|
  176. 84 sel.force_close(true)
  177. end
  178. 42 raise e
  179. end
  180. 1225 if readers.nil? && writers.nil? && interval
  181. 95 [*r, *w].each { |io| io.handle_socket_timeout(interval) }
  182. 53 return
  183. end
  184. 1168 if writers
  185. 87 readers.each do |io|
  186. 859 yield io
  187. # so that we don't yield 2 times
  188. 850 writers.delete(io)
  189. 1167 end if readers
  190. 1159 writers.each(&block)
  191. else
  192. readers.each(&block) if readers
  193. end
  194. end
  195. 30 def select_one(io, interests, interval)
  196. 2394 begin
  197. 4905 result =
  198. 27614 case interests
  199. 20346 when :r then io.to_io.wait_readable(interval)
  200. 11698 when :w then io.to_io.wait_writable(interval)
  201. 475 when :rw then rw_wait(io, interval)
  202. end
  203. rescue IOError => e
  204. io.on_io_error(e)
  205. return
  206. rescue StandardError => e
  207. 14 io.on_error(e)
  208. 14 return
  209. rescue Exception => e # rubocop:disable Lint/RescueException
  210. 42 io.force_close(true)
  211. 42 raise e
  212. end
  213. 32463 unless result || interval.nil?
  214. 962 io.handle_socket_timeout(interval) unless @is_timer_interval
  215. 865 return
  216. end
  217. 31501 yield io
  218. end
  219. 30 def next_timeout
  220. 34053 @is_timer_interval = false
  221. 34053 timer_interval = @timers.wait_interval
  222. 34053 connection_interval = @selectables.filter_map(&:timeout).min
  223. 34053 return connection_interval unless timer_interval
  224. 14096 if connection_interval.nil? || timer_interval <= connection_interval
  225. 14035 @is_timer_interval = true
  226. 13060 return timer_interval
  227. end
  228. 61 connection_interval
  229. end
  230. 30 if RUBY_ENGINE == "jruby"
  231. 1 def rw_wait(io, interval)
  232. 46 io.to_io.wait(interval, :read_write)
  233. end
  234. 29 elsif IO.const_defined?(:READABLE)
  235. 27 def rw_wait(io, interval)
  236. 398 io.to_io.wait(IO::READABLE | IO::WRITABLE, interval)
  237. end
  238. else
  239. 2 def rw_wait(io, interval)
  240. 31 if interval
  241. 29 io.to_io.wait(interval, :read_write)
  242. else
  243. 2 io.to_io.wait(:read_write)
  244. end
  245. end
  246. end
  247. end
  248. end

lib/httpx/session.rb

98.97% lines covered

292 relevant lines. 289 lines covered and 3 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. 14359 @options = self.class.default_options.merge(options)
  16. 14359 @persistent = @options.persistent
  17. 14359 @pool = @options.pool_class.new(@options.pool_options)
  18. 14359 @wrapped = false
  19. 14359 @closing = false
  20. 14359 INSTANCES[self] = self if @persistent && @options.close_on_fork && INSTANCES
  21. 14359 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. 821 prev_wrapped = @wrapped
  30. 821 @wrapped = true
  31. 821 was_initialized = false
  32. 821 current_selector = get_current_selector do
  33. 821 selector = Selector.new
  34. 821 set_current_selector(selector)
  35. 821 was_initialized = true
  36. 821 selector
  37. end
  38. 58 begin
  39. 821 yield self
  40. ensure
  41. 821 unless prev_wrapped
  42. 821 if @persistent
  43. 2 deactivate(current_selector)
  44. else
  45. 819 close(current_selector)
  46. end
  47. end
  48. 821 @wrapped = prev_wrapped
  49. 821 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. 8963 @pool.reset_resolvers
  60. # preparing to throw away connections
  61. 21469 while (connection = @pool.pop_connection)
  62. 5870 next if connection.state == :closed
  63. 248 select_connection(connection, selector)
  64. end
  65. 8963 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. 9351 raise ArgumentError, "must perform at least one request" if args.empty?
  89. 9351 requests = args.first.is_a?(Request) ? args : build_requests(*args, params)
  90. 9308 responses = send_requests(*requests)
  91. 9039 return responses.first if responses.size == 1
  92. 290 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. 11290 rklass = options.request_class
  102. 11290 request = rklass.new(verb, uri, options, params)
  103. 11238 request.persistent = @persistent
  104. 11238 set_request_callbacks(request)
  105. 11238 request
  106. end
  107. 30 def select_connection(connection, selector)
  108. 11502 pin(connection, selector)
  109. 11502 connection.log(level: 2) do
  110. 100 "registering into selector##{selector.object_id}"
  111. end
  112. 11502 selector.register(connection)
  113. end
  114. 30 def pin(conn_or_resolver, selector)
  115. 29846 conn_or_resolver.current_session = self
  116. 29846 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. 10528 connection.log(level: 2) do
  121. 86 "deregistering connection##{connection.object_id}(#{connection.state}) from selector##{selector.object_id}"
  122. end
  123. 10528 selector.deregister(connection)
  124. # do not check-in connections only created for Happy Eyeballs
  125. 10528 return if cloned
  126. 10494 return if @closing && connection.state == :closed && !connection.used?
  127. 10328 connection.log(level: 2) { "check-in connection##{connection.object_id}(#{connection.state}) in pool##{@pool.object_id}" }
  128. 10242 @pool.checkin_connection(connection)
  129. end
  130. 30 def deselect_resolver(resolver, selector)
  131. 674 resolver.log(level: 2) do
  132. "deregistering resolver##{resolver.object_id}(#{resolver.state}) from selector##{selector.object_id}"
  133. end
  134. 674 selector.deregister(resolver)
  135. 674 return if @closing && resolver.closed?
  136. 655 resolver.log(level: 2) { "check-in resolver##{resolver.object_id}(#{resolver.state}) in pool##{@pool.object_id}" }
  137. 655 @pool.checkin_resolver(resolver)
  138. end
  139. 30 def try_clone_connection(connection, selector, family)
  140. 671 connection.family ||= family
  141. 671 return connection if connection.family == family
  142. 53 new_connection = connection.class.new(connection.origin, connection.options)
  143. 53 new_connection.family = family
  144. 53 connection.sibling = new_connection
  145. 53 do_init_connection(new_connection, selector)
  146. 53 new_connection
  147. end
  148. # returns the HTTPX::Connection through which the +request+ should be sent through.
  149. 30 def find_connection(request_uri, selector, options)
  150. 11736 if (connection = selector.find_connection(request_uri, options))
  151. 1421 connection.idling if connection.state == :closed
  152. 1421 log(level: 2) { "found connection##{connection.object_id}(#{connection.state}) in selector##{selector.object_id}" }
  153. 1342 return connection
  154. end
  155. 10315 connection = @pool.checkout_connection(request_uri, options)
  156. 10279 log(level: 2) { "found connection##{connection.object_id}(#{connection.state}) in pool##{@pool.object_id}" }
  157. 9287 case connection.state
  158. when :idle
  159. 9140 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. 1033 connection.idling
  168. 1033 if connection.addresses?
  169. 1025 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. 10222 connection
  178. end
  179. 30 private
  180. 30 def selector_close(selector)
  181. begin
  182. 9296 @closing = true
  183. 9296 selector.terminate
  184. ensure
  185. 9296 @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. 639 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. 345122 response = request.response
  200. 345122 return unless response && response.finished?
  201. 11369 log(level: 2) { "response##{response.object_id} fetched" }
  202. 11369 response
  203. end
  204. # sends the +request+ to the corresponding HTTPX::Connection
  205. 30 def send_request(request, selector, options = request.options)
  206. 2125 error = begin
  207. 11566 catch(:resolve_error) do
  208. 11566 log(level: 2) { "finding connection for request##{request.object_id}..." }
  209. 11566 connection = find_connection(request.uri, selector, options)
  210. 11446 connection.send(request)
  211. end
  212. rescue StandardError => e
  213. 45 e
  214. end
  215. 11559 return unless error && error.is_a?(Exception)
  216. 120 raise error unless error.is_a?(Error)
  217. 113 response = ErrorResponse.new(request, error)
  218. 113 request.response = response
  219. 113 request.emit(:response, response)
  220. end
  221. # returns a set of HTTPX::Request objects built from the given +args+ and +options+.
  222. 30 def build_requests(*args, params)
  223. 8516 requests = if args.size == 1
  224. 88 reqs = args.first
  225. 88 reqs.map do |verb, uri, ps = EMPTY_HASH|
  226. 176 request_params = params
  227. 176 request_params = request_params.merge(ps) unless ps.empty?
  228. 176 build_request(verb, uri, request_params)
  229. end
  230. else
  231. 8428 verb, uris = args
  232. 8428 if uris.respond_to?(:each)
  233. 8158 uris.enum_for(:each).map do |uri, ps = EMPTY_HASH|
  234. 9020 request_params = params
  235. 9020 request_params = request_params.merge(ps) unless ps.empty?
  236. 9020 build_request(verb, uri, request_params)
  237. end
  238. else
  239. 270 [build_request(verb, uris, params)]
  240. end
  241. end
  242. 8473 raise ArgumentError, "wrong number of URIs (given 0, expect 1..+1)" if requests.empty?
  243. 8473 requests
  244. end
  245. 30 def set_request_callbacks(request)
  246. 11094 request.on(:promise, &method(:on_promise))
  247. end
  248. 30 def do_init_connection(connection, selector)
  249. 9193 resolve_connection(connection, selector) unless connection.family
  250. end
  251. # sends an array of HTTPX::Request +requests+, returns the respective array of HTTPX::Response objects.
  252. 30 def send_requests(*requests)
  253. 17790 selector = get_current_selector { Selector.new }
  254. 896 begin
  255. 9418 _send_requests(requests, selector)
  256. 9404 receive_requests(requests, selector)
  257. ensure
  258. 9391 unless @wrapped
  259. 8420 if @persistent
  260. 637 deactivate(selector)
  261. else
  262. 7783 close(selector)
  263. end
  264. end
  265. end
  266. end
  267. # sends an array of HTTPX::Request objects
  268. 30 def _send_requests(requests, selector)
  269. 9418 requests.each do |request|
  270. 10351 send_request(request, selector)
  271. end
  272. end
  273. # returns the array of HTTPX::Response objects corresponding to the array of HTTPX::Request +requests+.
  274. 30 def receive_requests(requests, selector)
  275. 9404 waiting = 0
  276. 9404 responses = requests.map do |request|
  277. 10337 fetch_response(request, selector, request.options).tap do |response|
  278. 10337 waiting += 1 if response.nil?
  279. end
  280. end
  281. 12011 until waiting.zero? || selector.empty?
  282. # loop on selector until at least one response has been received.
  283. 68104 catch(:coalesced) { selector.next_tick }
  284. 33806 responses.each_with_index do |response, idx|
  285. 632814 next unless response.nil?
  286. 333750 request = requests[idx]
  287. 333750 response = fetch_response(request, selector, request.options)
  288. 333750 next unless response
  289. 9725 request.complete!(response)
  290. 8813 responses[idx] = response
  291. 8813 waiting -= 1
  292. end
  293. end
  294. 9158 raise Error, "something went wrong, responses not found and requests not resent" unless waiting.zero?
  295. 9158 responses
  296. end
  297. 30 def resolve_connection(connection, selector)
  298. 9176 if connection.addresses? || connection.open?
  299. #
  300. # there are two cases in which we want to activate initialization of
  301. # connection immediately:
  302. #
  303. # 1. when the connection already has addresses, i.e. it doesn't need to
  304. # resolve a name (not the same as name being an IP, yet)
  305. # 2. when the connection is initialized with an external already open IO.
  306. #
  307. 279 on_resolver_connection(connection, selector)
  308. 277 return
  309. end
  310. 8897 resolver = find_resolver_for(connection, selector)
  311. 8897 pin(connection, selector)
  312. 8897 early_resolve(resolver, connection) || resolver.lazy_resolve(connection)
  313. end
  314. 30 def early_resolve(resolver, connection)
  315. 8897 resolver.early_resolve(connection)
  316. end
  317. 30 def on_resolver_connection(connection, selector)
  318. 9183 from_pool = false
  319. 9183 found_connection = selector.find_mergeable_connection(connection) || begin
  320. 9147 from_pool = true
  321. 9147 connection.log(level: 2) do
  322. 100 "try finding a mergeable connection in pool##{@pool.object_id}"
  323. end
  324. 9147 @pool.checkout_mergeable_connection(connection)
  325. end
  326. 9183 return select_connection(connection, selector) unless found_connection
  327. 57 connection.log(level: 2) do
  328. "try coalescing from #{from_pool ? "pool##{@pool.object_id}" : "selector##{selector.object_id}"} " \
  329. "(connection##{found_connection.object_id}[#{found_connection.origin}])"
  330. end
  331. 57 coalesce_connections(found_connection, connection, selector, from_pool)
  332. end
  333. 30 def find_resolver_for(connection, selector)
  334. 8897 if (resolver = selector.find_resolver(connection.options))
  335. 5 resolver.log(level: 2) { "found resolver##{resolver.object_id}(#{resolver.state}) in selector##{selector.object_id}" }
  336. 5 return resolver
  337. end
  338. 8892 resolver = @pool.checkout_resolver(connection.options)
  339. 8978 resolver.log(level: 2) { "found resolver##{resolver.object_id}(#{resolver.state}) in pool##{@pool.object_id}" }
  340. 8892 pin(resolver, selector)
  341. 8892 resolver
  342. end
  343. # coalesces +conn2+ into +conn1+. if +conn1+ was loaded from the connection pool
  344. # (it is known via +from_pool+), then it adds its to the +selector+.
  345. 30 def coalesce_connections(conn1, conn2, selector, from_pool)
  346. 57 unless conn1.coalescable?(conn2)
  347. 28 conn2.log(level: 2) { "not coalescing with conn##{conn1.object_id}[#{conn1.origin}])" }
  348. 28 select_connection(conn2, selector)
  349. 28 if from_pool
  350. 7 conn1.log(level: 2) { "check-in connection##{conn1.object_id}(#{conn1.state}) in pool##{@pool.object_id}" }
  351. 7 @pool.checkin_connection(conn1)
  352. end
  353. 28 return
  354. end
  355. 29 conn2.log(level: 2) { "coalescing with connection##{conn1.object_id}[#{conn1.origin}])" }
  356. 29 select_connection(conn1, selector) if from_pool
  357. 29 conn2.coalesce!(conn1)
  358. 29 conn2.disconnect
  359. end
  360. 30 def get_current_selector
  361. 10267 selector_store[self] || (yield if block_given?)
  362. end
  363. 30 def set_current_selector(selector)
  364. 2239 if selector
  365. 1314 selector_store[self] = selector
  366. else
  367. 821 selector_store.delete(self)
  368. end
  369. end
  370. 30 def selector_store
  371. 12506 th_current = Thread.current
  372. 12506 thread_selector_store(th_current) || begin
  373. 249 {}.compare_by_identity.tap do |store|
  374. 249 th_current.thread_variable_set(:httpx_persistent_selector_store, store)
  375. end
  376. end
  377. end
  378. 30 def thread_selector_store(th)
  379. 17023 th.thread_variable_get(:httpx_persistent_selector_store)
  380. end
  381. 30 Options.freeze
  382. 30 @default_options = Options.new
  383. 30 @default_options.freeze
  384. 30 @plugins = []
  385. 30 class << self
  386. 30 attr_reader :default_options
  387. 30 def inherited(klass)
  388. 7473 super
  389. 7473 klass.instance_variable_set(:@default_options, @default_options)
  390. 7473 klass.instance_variable_set(:@plugins, @plugins.dup)
  391. 7473 klass.instance_variable_set(:@callbacks, @callbacks.dup)
  392. end
  393. # returns a new HTTPX::Session instance, with the plugin pointed by +pl+ loaded.
  394. #
  395. # session_with_retries = session.plugin(:retries)
  396. # session_with_custom = session.plugin(CustomPlugin)
  397. #
  398. 30 def plugin(pl, options = nil, &block)
  399. 11197 label = pl
  400. 11197 pl = Plugins.load_plugin(pl) if pl.is_a?(Symbol)
  401. 11197 raise ArgumentError, "Invalid plugin type: #{pl.class.inspect}" unless pl.is_a?(Module)
  402. 11189 if !@plugins.include?(pl)
  403. 10878 @plugins << pl
  404. 10878 pl.load_dependencies(self, &block) if pl.respond_to?(:load_dependencies)
  405. 10878 @default_options = @default_options.dup
  406. 10878 include(pl::InstanceMethods) if defined?(pl::InstanceMethods)
  407. 10878 extend(pl::ClassMethods) if defined?(pl::ClassMethods)
  408. 10878 opts = @default_options
  409. 10878 opts.extend_with_plugin_classes(pl)
  410. 10878 if defined?(pl::OptionsMethods)
  411. # when a class gets dup'ed, the #initialize_dup callbacks isn't triggered.
  412. # moreover, and because #method_added does not get triggered on mixin include,
  413. # the callback is also forcefully manually called here.
  414. 4925 opts.options_class.instance_variable_set(:@options_names, opts.options_class.options_names.dup)
  415. 4925 (pl::OptionsMethods.instance_methods + pl::OptionsMethods.private_instance_methods - Object.instance_methods).each do |meth|
  416. 15070 opts.options_class.method_added(meth)
  417. end
  418. 4925 @default_options = opts.options_class.new(opts)
  419. end
  420. 10878 @default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
  421. 10878 @default_options = @default_options.merge(options) if options
  422. 10878 if pl.respond_to?(:subplugins)
  423. 1995 pl.subplugins.transform_keys(&Plugins.method(:load_plugin)).each do |main_pl, sub_pl|
  424. # in case the main plugin has already been loaded, then apply subplugin functionality
  425. # immediately
  426. 2611 next unless @plugins.include?(main_pl)
  427. 80 plugin(sub_pl, options, &block)
  428. end
  429. end
  430. 10878 pl.configure(self, &block) if pl.respond_to?(:configure)
  431. 10878 if label.is_a?(Symbol)
  432. # in case an already-loaded plugin complements functionality of
  433. # the plugin currently being loaded, loaded it now
  434. 8145 @plugins.each do |registered_pl|
  435. 22022 next if registered_pl == pl
  436. 13877 next unless registered_pl.respond_to?(:subplugins)
  437. 3841 sub_pl = registered_pl.subplugins[label]
  438. 3841 next unless sub_pl
  439. 204 plugin(sub_pl, options, &block)
  440. end
  441. end
  442. 10878 @default_options.freeze
  443. 10878 set_temporary_name("#{superclass}/#{pl}") if respond_to?(:set_temporary_name) # ruby 3.4 only
  444. 310 elsif options
  445. # this can happen when two plugins are loaded, an one of them calls the other under the hood,
  446. # albeit changing some default.
  447. 26 @default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
  448. 26 @default_options = @default_options.merge(options) if options
  449. 18 @default_options.freeze
  450. end
  451. 11181 self
  452. end
  453. end
  454. # setup of the support for close_on_fork sessions.
  455. # adapted from https://github.com/mperham/connection_pool/blob/main/lib/connection_pool.rb#L48
  456. 30 if Process.respond_to?(:fork)
  457. 28 INSTANCES = ObjectSpace::WeakMap.new
  458. 28 private_constant :INSTANCES
  459. 28 def self.after_fork
  460. 1 INSTANCES.each_value(&:close)
  461. 1 nil
  462. end
  463. 28 if ::Process.respond_to?(:_fork)
  464. 24 module ForkTracker
  465. 24 def _fork
  466. 1 pid = super
  467. 1 Session.after_fork if pid.zero?
  468. 1 pid
  469. end
  470. end
  471. 24 Process.singleton_class.prepend(ForkTracker)
  472. end
  473. else
  474. 2 INSTANCES = nil
  475. 2 private_constant :INSTANCES
  476. 2 def self.after_fork
  477. # noop
  478. end
  479. end
  480. end
  481. # session may be overridden by certain adapters.
  482. 30 S = Session
  483. 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.94% lines covered

66 relevant lines. 62 lines covered and 4 lines missed.
    
  1. # frozen_string_literal: true
  2. 30 module HTTPX
  3. 30 class Timers
  4. 30 def initialize
  5. 9554 @intervals = []
  6. end
  7. 30 def empty?
  8. 208 @intervals.empty?
  9. end
  10. 30 def after(interval_in_secs, cb = nil, &blk)
  11. 44817 callback = cb || blk
  12. 44817 raise Error, "timer must have a callback" unless callback
  13. # I'm assuming here that most requests will have the same
  14. # request timeout, as in most cases they share common set of
  15. # options. A user setting different request timeouts for 100s of
  16. # requests will already have a hard time dealing with that.
  17. 81020 unless (interval = @intervals.bsearch { |t| t.interval == interval_in_secs })
  18. 12275 interval = Interval.new(interval_in_secs)
  19. 12275 @intervals << interval
  20. 12275 @intervals.sort!
  21. end
  22. 44817 interval << callback
  23. 44817 @next_interval_at = nil
  24. 44817 Timer.new(interval, callback)
  25. end
  26. 30 def wait_interval
  27. 34053 return if @intervals.empty?
  28. 14096 first_interval = @intervals.first
  29. 14096 drop_elapsed!(0) if first_interval.elapsed?(0)
  30. 14096 @next_interval_at = Utils.now
  31. 14096 first_interval.interval
  32. end
  33. 30 def fire(error = nil)
  34. 33807 raise error if error && error.timeout != @intervals.first
  35. 33807 return if @intervals.empty? || !@next_interval_at
  36. 12859 elapsed_time = Utils.elapsed_time(@next_interval_at)
  37. 12859 drop_elapsed!(elapsed_time)
  38. 12859 @next_interval_at = nil if @intervals.empty?
  39. end
  40. 30 private
  41. 30 def drop_elapsed!(elapsed_time)
  42. 28005 @intervals = @intervals.drop_while { |interval| interval.elapse(elapsed_time) <= 0 }
  43. end
  44. 30 class Timer
  45. 30 def initialize(interval, callback)
  46. 44817 @interval = interval
  47. 44817 @callback = callback
  48. end
  49. 30 def cancel
  50. 64762 @interval.delete(@callback)
  51. end
  52. end
  53. 30 class Interval
  54. 30 include Comparable
  55. 30 attr_reader :interval
  56. 30 def initialize(interval)
  57. 12275 @interval = interval
  58. 12275 @callbacks = []
  59. end
  60. 30 def <=>(other)
  61. 2076 @interval <=> other.interval
  62. end
  63. 30 def ==(other)
  64. return @interval == other if other.is_a?(Numeric)
  65. @interval == other.to_f # rubocop:disable Lint/FloatComparison
  66. end
  67. 30 def to_f
  68. Float(@interval)
  69. end
  70. 30 def <<(callback)
  71. 44817 @callbacks << callback
  72. end
  73. 30 def delete(callback)
  74. 64762 @callbacks.delete(callback)
  75. end
  76. 30 def no_callbacks?
  77. @callbacks.empty?
  78. end
  79. 30 def elapsed?(elapsed = 0)
  80. 14096 (@interval - elapsed) <= 0 || @callbacks.empty?
  81. end
  82. 30 def elapse(elapsed)
  83. # same as elapsing
  84. 14585 return 0 if @callbacks.empty?
  85. 4865 @interval -= elapsed
  86. 5272 if @interval <= 0
  87. 1349 cb = @callbacks.dup
  88. 1349 cb.each(&:call)
  89. end
  90. 5272 @interval
  91. end
  92. end
  93. 30 private_constant :Interval
  94. end
  95. 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. 2847 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. 2335 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. 1688 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. 1761 body = body.open(File::RDONLY, encoding: Encoding::BINARY) if Object.const_defined?(:Pathname) && body.is_a?(Pathname)
  10. 1761 @body = body
  11. 1761 super
  12. end
  13. 30 def bytesize
  14. 6779 if @body.respond_to?(:bytesize)
  15. 2877 @body.bytesize
  16. 3901 elsif @body.respond_to?(:to_ary)
  17. 1475 @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. 1628 "application/octet-stream"
  30. end
  31. end
  32. 30 def encode(body)
  33. 1761 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. 190 loop do
  40. 1168 case @state
  41. when :length
  42. 377 index = @buffer.index(CRLF)
  43. 377 return unless index && index.positive?
  44. # Read hex-length
  45. 377 hexlen = @buffer.byteslice(0, index)
  46. 377 @buffer = @buffer.byteslice(index..-1) || "".b
  47. 377 hexlen[/\h/] || raise(Error, "wrong chunk size line: #{hexlen}")
  48. 377 @chunk_length = hexlen.hex
  49. # check if is last chunk
  50. 377 @finished = @chunk_length.zero?
  51. 377 nextstate(:crlf)
  52. when :crlf
  53. 625 crlf_size = @finished && !@trailers ? 4 : 2
  54. # consume CRLF
  55. 625 return if @buffer.bytesize < crlf_size
  56. 625 raise Error, "wrong chunked encoding format" unless @buffer.start_with?(CRLF * (crlf_size / 2))
  57. 625 @buffer = @buffer.byteslice(crlf_size..-1)
  58. 625 if @chunk_length.nil?
  59. 248 nextstate(:length)
  60. else
  61. 377 return if @finished
  62. 257 nextstate(:data)
  63. end
  64. when :data
  65. 308 chunk = @buffer.byteslice(0, @chunk_length)
  66. 308 @buffer = @buffer.byteslice(@chunk_length..-1) || "".b
  67. 308 @chunk_buffer << chunk
  68. 275 @chunk_length -= chunk.bytesize
  69. 308 if @chunk_length.zero?
  70. 257 yield @chunk_buffer unless @chunk_buffer.empty?
  71. 248 @chunk_buffer.clear
  72. 248 @chunk_length = nil
  73. 248 nextstate(:crlf)
  74. end
  75. end
  76. 1181 break if @buffer.empty?
  77. end
  78. end
  79. 30 def finished?
  80. 181 @finished
  81. end
  82. 30 private
  83. 30 def nextstate(state)
  84. 1130 @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. 853 @raw = form.each_with_object("".b) do |(key, val), buf|
  18. 1465 HTTPX::Transcoder.normalize_keys(key, val) do |k, v|
  19. 1688 buf << "&" unless buf.empty?
  20. 1688 buf << URI.encode_www_form_component(k)
  21. 1688 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. 853 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. 549 buffer = @inflater.inflate(chunk)
  46. 495 @bytesize -= chunk.bytesize
  47. 549 if @bytesize <= 0
  48. 134 buffer << @inflater.finish
  49. 134 @inflater.close
  50. end
  51. 549 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. 552 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. 486 return @buffer.read(length, outbuf) if @buffer
  18. 285 return if @closed
  19. 230 chunk = @body.read(length)
  20. 230 compressed_chunk = deflate(chunk)
  21. 230 return unless compressed_chunk
  22. 203 if outbuf
  23. 194 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. 46034 Process.clock_gettime(Process::CLOCK_MONOTONIC)
  12. end
  13. 30 def elapsed_time(monotonic_timestamp)
  14. 13435 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. 22274 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. 15385 Ractor.main != Ractor.current
  59. end
  60. else
  61. 6 def in_ractor?
  62. 10968 false
  63. end
  64. end
  65. end
  66. end