-
# frozen_string_literal: true
-
-
24
require "httpx/version"
-
-
24
require "httpx/extensions"
-
-
24
require "httpx/errors"
-
24
require "httpx/utils"
-
24
require "httpx/punycode"
-
24
require "httpx/domain_name"
-
24
require "httpx/altsvc"
-
24
require "httpx/callbacks"
-
24
require "httpx/loggable"
-
24
require "httpx/transcoder"
-
24
require "httpx/timers"
-
24
require "httpx/pool"
-
24
require "httpx/headers"
-
24
require "httpx/request"
-
24
require "httpx/response"
-
24
require "httpx/options"
-
24
require "httpx/chainable"
-
-
# Top-Level Namespace
-
#
-
24
module HTTPX
-
24
EMPTY = [].freeze
-
-
# All plugins should be stored under this module/namespace. Can register and load
-
# plugins.
-
#
-
24
module Plugins
-
24
@plugins = {}
-
24
@plugins_mutex = Thread::Mutex.new
-
-
# Loads a plugin based on a name. If the plugin hasn't been loaded, tries to load
-
# it from the load path under "httpx/plugins/" directory.
-
#
-
24
def self.load_plugin(name)
-
4231
h = @plugins
-
4231
m = @plugins_mutex
-
8462
unless (plugin = m.synchronize { h[name] })
-
129
require "httpx/plugins/#{name}"
-
258
raise "Plugin #{name} hasn't been registered" unless (plugin = m.synchronize { h[name] })
-
end
-
4231
plugin
-
end
-
-
# Registers a plugin (+mod+) in the central store indexed by +name+.
-
#
-
24
def self.register_plugin(name, mod)
-
251
h = @plugins
-
251
m = @plugins_mutex
-
476
m.synchronize { h[name] = mod }
-
end
-
end
-
-
24
extend Chainable
-
end
-
-
24
require "httpx/session"
-
24
require "httpx/session_extensions"
-
-
# load integrations when possible
-
-
24
require "httpx/adapters/datadog" if defined?(DDTrace) || defined?(Datadog)
-
24
require "httpx/adapters/sentry" if defined?(Sentry)
-
24
require "httpx/adapters/webmock" if defined?(WebMock)
-
# frozen_string_literal: true
-
-
5
require "datadog/tracing/contrib/integration"
-
5
require "datadog/tracing/contrib/configuration/settings"
-
5
require "datadog/tracing/contrib/patcher"
-
-
5
module Datadog::Tracing
-
5
module Contrib
-
5
module HTTPX
-
5
DATADOG_VERSION = defined?(::DDTrace) ? ::DDTrace::VERSION : ::Datadog::VERSION
-
-
5
METADATA_MODULE = Datadog::Tracing::Metadata
-
-
5
TYPE_OUTBOUND = Datadog::Tracing::Metadata::Ext::HTTP::TYPE_OUTBOUND
-
-
5
TAG_PEER_SERVICE = Datadog::Tracing::Metadata::Ext::TAG_PEER_SERVICE
-
-
5
TAG_URL = Datadog::Tracing::Metadata::Ext::HTTP::TAG_URL
-
5
TAG_METHOD = Datadog::Tracing::Metadata::Ext::HTTP::TAG_METHOD
-
5
TAG_TARGET_HOST = Datadog::Tracing::Metadata::Ext::NET::TAG_TARGET_HOST
-
5
TAG_TARGET_PORT = Datadog::Tracing::Metadata::Ext::NET::TAG_TARGET_PORT
-
-
5
TAG_STATUS_CODE = Datadog::Tracing::Metadata::Ext::HTTP::TAG_STATUS_CODE
-
-
# HTTPX Datadog Plugin
-
#
-
# Enables tracing for httpx requests.
-
#
-
# A span will be created for each request transaction; the span is created lazily only when
-
# receiving a response, and it is fed the start time stored inside the tracer object.
-
#
-
5
module Plugin
-
5
class RequestTracer
-
5
include Contrib::HttpAnnotationHelper
-
-
5
SPAN_REQUEST = "httpx.request"
-
-
# initializes the tracer object on the +request+.
-
5
def initialize(request)
-
163
@request = request
-
163
@start_time = nil
-
-
# request objects are reused, when already buffered requests get rerouted to a different
-
# connection due to connection issues, or when they already got a response, but need to
-
# be retried. In such situations, the original span needs to be extended for the former,
-
# while a new is required for the latter.
-
182
request.on(:idle) { reset }
-
# the span is initialized when the request is buffered in the parser, which is the closest
-
# one gets to actually sending the request.
-
273
request.on(:headers) { call }
-
end
-
-
# sets up the span start time, while preparing the on response callback.
-
5
def call(*args)
-
119
return if @start_time
-
-
114
start(*args)
-
-
114
@request.once(:response, &method(:finish))
-
end
-
-
5
private
-
-
# just sets the span init time. It can be passed a +start_time+ in cases where
-
# this is collected outside the request transaction.
-
5
def start(start_time = now)
-
119
@start_time = start_time
-
end
-
-
# resets the start time for already finished request transactions.
-
5
def reset
-
19
return unless @start_time
-
-
5
start
-
end
-
-
# creates the span from the collected +@start_time+ to what the +response+ state
-
# contains. It also resets internal state to allow this object to be reused.
-
5
def finish(response)
-
114
return unless @start_time
-
-
114
span = initialize_span
-
-
114
return unless span
-
-
114
if response.is_a?(::HTTPX::ErrorResponse)
-
9
span.set_error(response.error)
-
else
-
105
span.set_tag(TAG_STATUS_CODE, response.status.to_s)
-
-
105
span.set_error(::HTTPX::HTTPError.new(response)) if response.status >= 400 && response.status <= 599
-
end
-
-
114
span.finish
-
ensure
-
114
@start_time = nil
-
end
-
-
# return a span initialized with the +@request+ state.
-
5
def initialize_span
-
114
verb = @request.verb
-
114
uri = @request.uri
-
-
114
span = create_span(@request)
-
-
114
span.resource = verb
-
-
# Add additional request specific tags to the span.
-
-
114
span.set_tag(TAG_URL, @request.path)
-
114
span.set_tag(TAG_METHOD, verb)
-
-
114
span.set_tag(TAG_TARGET_HOST, uri.host)
-
114
span.set_tag(TAG_TARGET_PORT, uri.port.to_s)
-
-
# Tag as an external peer service
-
114
span.set_tag(TAG_PEER_SERVICE, span.service)
-
-
114
if configuration[:distributed_tracing]
-
109
propagate_trace_http(
-
Datadog::Tracing.active_trace.to_digest,
-
@request.headers
-
)
-
end
-
-
# Set analytics sample rate
-
114
if Contrib::Analytics.enabled?(configuration[:analytics_enabled])
-
10
Contrib::Analytics.set_sample_rate(span, configuration[:analytics_sample_rate])
-
end
-
-
114
span
-
rescue StandardError => e
-
Datadog.logger.error("error preparing span for http request: #{e}")
-
Datadog.logger.error(e.backtrace)
-
end
-
-
5
def now
-
110
::Datadog::Core::Utils::Time.now.utc
-
end
-
-
5
def configuration
-
352
@configuration ||= Datadog.configuration.tracing[:httpx, @request.uri.host]
-
end
-
-
5
if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("2.0.0")
-
2
def propagate_trace_http(digest, headers)
-
41
Datadog::Tracing::Contrib::HTTP.inject(digest, headers)
-
end
-
-
2
def create_span(request)
-
43
Datadog::Tracing.trace(
-
SPAN_REQUEST,
-
service: service_name(request.uri.host, configuration, Datadog.configuration_for(self)),
-
type: TYPE_OUTBOUND,
-
start_time: @start_time
-
)
-
end
-
else
-
3
def propagate_trace_http(digest, headers)
-
68
Datadog::Tracing::Propagation::HTTP.inject!(digest, headers)
-
end
-
-
3
def create_span(request)
-
71
Datadog::Tracing.trace(
-
SPAN_REQUEST,
-
service: service_name(request.uri.host, configuration, Datadog.configuration_for(self)),
-
span_type: TYPE_OUTBOUND,
-
start_time: @start_time
-
)
-
end
-
end
-
end
-
-
5
module RequestMethods
-
# intercepts request initialization to inject the tracing logic.
-
5
def initialize(*)
-
154
super
-
-
154
return unless Datadog::Tracing.enabled?
-
-
154
RequestTracer.new(self)
-
end
-
end
-
-
5
module ConnectionMethods
-
5
attr_reader :init_time
-
-
5
def initialize(*)
-
139
super
-
-
139
@init_time = ::Datadog::Core::Utils::Time.now.utc
-
end
-
-
# handles the case when the +error+ happened during name resolution, which meanns
-
# that the tracing logic hasn't been injected yet; in such cases, the approximate
-
# initial resolving time is collected from the connection, and used as span start time,
-
# and the tracing object in inserted before the on response callback is called.
-
5
def handle_error(error, request = nil)
-
9
return super unless Datadog::Tracing.enabled?
-
-
9
return super unless error.respond_to?(:connection)
-
-
9
@pending.each do |req|
-
9
next if request and request == req
-
-
9
RequestTracer.new(req).call(error.connection.init_time)
-
end
-
-
9
RequestTracer.new(request).call(error.connection.init_time) if request
-
-
9
super
-
end
-
end
-
end
-
-
5
module Configuration
-
# Default settings for httpx
-
#
-
5
class Settings < Datadog::Tracing::Contrib::Configuration::Settings
-
5
DEFAULT_ERROR_HANDLER = lambda do |response|
-
Datadog::Ext::HTTP::ERROR_RANGE.cover?(response.status)
-
end
-
-
5
option :service_name, default: "httpx"
-
5
option :distributed_tracing, default: true
-
5
option :split_by_domain, default: false
-
-
5
if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
-
5
option :enabled do |o|
-
5
o.type :bool
-
5
o.env "DD_TRACE_HTTPX_ENABLED"
-
5
o.default true
-
end
-
-
5
option :analytics_enabled do |o|
-
5
o.type :bool
-
5
o.env "DD_TRACE_HTTPX_ANALYTICS_ENABLED"
-
5
o.default false
-
end
-
-
5
option :analytics_sample_rate do |o|
-
5
o.type :float
-
5
o.env "DD_TRACE_HTTPX_ANALYTICS_SAMPLE_RATE"
-
5
o.default 1.0
-
end
-
else
-
option :enabled do |o|
-
o.default { env_to_bool("DD_TRACE_HTTPX_ENABLED", true) }
-
o.lazy
-
end
-
-
option :analytics_enabled do |o|
-
o.default { env_to_bool(%w[DD_TRACE_HTTPX_ANALYTICS_ENABLED DD_HTTPX_ANALYTICS_ENABLED], false) }
-
o.lazy
-
end
-
-
option :analytics_sample_rate do |o|
-
o.default { env_to_float(%w[DD_TRACE_HTTPX_ANALYTICS_SAMPLE_RATE DD_HTTPX_ANALYTICS_SAMPLE_RATE], 1.0) }
-
o.lazy
-
end
-
end
-
-
5
if defined?(Datadog::Tracing::Contrib::SpanAttributeSchema)
-
5
option :service_name do |o|
-
5
o.default do
-
59
Datadog::Tracing::Contrib::SpanAttributeSchema.fetch_service_name(
-
"DD_TRACE_HTTPX_SERVICE_NAME",
-
"httpx"
-
)
-
end
-
5
o.lazy unless Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
-
end
-
else
-
option :service_name do |o|
-
o.default do
-
ENV.fetch("DD_TRACE_HTTPX_SERVICE_NAME", "httpx")
-
end
-
o.lazy unless Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
-
end
-
end
-
-
5
option :distributed_tracing, default: true
-
-
5
if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.15.0")
-
5
option :error_handler do |o|
-
5
o.type :proc
-
5
o.default_proc(&DEFAULT_ERROR_HANDLER)
-
end
-
elsif Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
-
option :error_handler do |o|
-
o.type :proc
-
o.experimental_default_proc(&DEFAULT_ERROR_HANDLER)
-
end
-
else
-
option :error_handler, default: DEFAULT_ERROR_HANDLER
-
end
-
end
-
end
-
-
# Patcher enables patching of 'httpx' with datadog components.
-
#
-
5
module Patcher
-
5
include Datadog::Tracing::Contrib::Patcher
-
-
5
module_function
-
-
5
def target_version
-
10
Integration.version
-
end
-
-
# loads a session instannce with the datadog plugin, and replaces the
-
# base HTTPX::Session with the patched session class.
-
5
def patch
-
5
datadog_session = ::HTTPX.plugin(Plugin)
-
-
5
::HTTPX.send(:remove_const, :Session)
-
5
::HTTPX.send(:const_set, :Session, datadog_session.class)
-
end
-
end
-
-
# Datadog Integration for HTTPX.
-
#
-
5
class Integration
-
5
include Contrib::Integration
-
-
5
MINIMUM_VERSION = Gem::Version.new("0.10.2")
-
-
5
register_as :httpx
-
-
5
def self.version
-
205
Gem.loaded_specs["httpx"] && Gem.loaded_specs["httpx"].version
-
end
-
-
5
def self.loaded?
-
65
defined?(::HTTPX::Request)
-
end
-
-
5
def self.compatible?
-
65
super && version >= MINIMUM_VERSION
-
end
-
-
5
def new_configuration
-
69
Configuration::Settings.new
-
end
-
-
5
def patcher
-
130
Patcher
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
8
require "delegate"
-
8
require "httpx"
-
8
require "faraday"
-
-
8
module Faraday
-
8
class Adapter
-
8
class HTTPX < Faraday::Adapter
-
8
module RequestMixin
-
8
def build_connection(env)
-
190
return @connection if defined?(@connection)
-
-
190
@connection = ::HTTPX.plugin(:persistent).plugin(ReasonPlugin)
-
190
@connection = @connection.with(@connection_options) unless @connection_options.empty?
-
190
connection_opts = options_from_env(env)
-
-
190
if (bind = env.request.bind)
-
7
@bind = TCPSocket.new(bind[:host], bind[:port])
-
6
connection_opts[:io] = @bind
-
end
-
190
@connection = @connection.with(connection_opts)
-
-
190
if (proxy = env.request.proxy)
-
7
proxy_options = { uri: proxy.uri }
-
7
proxy_options[:username] = proxy.user if proxy.user
-
7
proxy_options[:password] = proxy.password if proxy.password
-
-
7
@connection = @connection.plugin(:proxy).with(proxy: proxy_options)
-
end
-
190
@connection = @connection.plugin(OnDataPlugin) if env.request.stream_response?
-
-
190
@connection = @config_block.call(@connection) || @connection if @config_block
-
190
@connection
-
end
-
-
8
def close
-
196
@connection.close if @connection
-
196
@bind.close if @bind
-
end
-
-
8
private
-
-
8
def connect(env, &blk)
-
190
connection(env, &blk)
-
rescue ::HTTPX::TLSError => e
-
7
raise Faraday::SSLError, e
-
rescue Errno::ECONNABORTED,
-
Errno::ECONNREFUSED,
-
Errno::ECONNRESET,
-
Errno::EHOSTUNREACH,
-
Errno::EINVAL,
-
Errno::ENETUNREACH,
-
Errno::EPIPE,
-
::HTTPX::ConnectionError => e
-
7
raise Faraday::ConnectionFailed, e
-
end
-
-
8
def build_request(env)
-
197
meth = env[:method]
-
-
28
request_options = {
-
168
headers: env.request_headers,
-
body: env.body,
-
**options_from_env(env),
-
}
-
197
[meth.to_s.upcase, env.url, request_options]
-
end
-
-
8
def options_from_env(env)
-
387
timeout_options = {}
-
387
req_opts = env.request
-
387
if (sec = request_timeout(:read, req_opts))
-
12
timeout_options[:read_timeout] = sec
-
end
-
-
387
if (sec = request_timeout(:write, req_opts))
-
12
timeout_options[:write_timeout] = sec
-
end
-
-
387
if (sec = request_timeout(:open, req_opts))
-
12
timeout_options[:connect_timeout] = sec
-
end
-
-
55
{
-
331
ssl: ssl_options_from_env(env),
-
timeout: timeout_options,
-
}
-
end
-
-
8
if defined?(::OpenSSL)
-
8
def ssl_options_from_env(env)
-
387
ssl_options = {}
-
-
387
unless env.ssl.verify.nil?
-
24
ssl_options[:verify_mode] = env.ssl.verify ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
-
end
-
-
387
ssl_options[:ca_file] = env.ssl.ca_file if env.ssl.ca_file
-
387
ssl_options[:ca_path] = env.ssl.ca_path if env.ssl.ca_path
-
387
ssl_options[:cert_store] = env.ssl.cert_store if env.ssl.cert_store
-
387
ssl_options[:cert] = env.ssl.client_cert if env.ssl.client_cert
-
387
ssl_options[:key] = env.ssl.client_key if env.ssl.client_key
-
387
ssl_options[:ssl_version] = env.ssl.version if env.ssl.version
-
387
ssl_options[:verify_depth] = env.ssl.verify_depth if env.ssl.verify_depth
-
387
ssl_options[:min_version] = env.ssl.min_version if env.ssl.min_version
-
387
ssl_options[:max_version] = env.ssl.max_version if env.ssl.max_version
-
387
ssl_options
-
end
-
else
-
def ssl_options_from_env(*)
-
{}
-
end
-
end
-
end
-
-
8
include RequestMixin
-
-
8
module OnDataPlugin
-
8
module RequestMethods
-
8
attr_writer :response_on_data
-
-
8
def response=(response)
-
14
super
-
-
14
return if response.is_a?(::HTTPX::ErrorResponse)
-
-
14
response.body.on_data = @response_on_data
-
end
-
end
-
-
8
module ResponseBodyMethods
-
8
attr_writer :on_data
-
-
8
def write(chunk)
-
30
return super unless @on_data
-
-
30
@on_data.call(chunk, chunk.bytesize)
-
end
-
end
-
end
-
-
8
module ReasonPlugin
-
8
def self.load_dependencies(*)
-
190
require "net/http/status"
-
end
-
-
8
module ResponseMethods
-
8
def reason
-
155
Net::HTTP::STATUS_CODES.fetch(@status)
-
end
-
end
-
end
-
-
8
class ParallelManager
-
8
class ResponseHandler < SimpleDelegator
-
8
attr_reader :env
-
-
8
def initialize(env)
-
28
@env = env
-
28
super
-
end
-
-
8
def on_response(&blk)
-
56
if blk
-
28
@on_response = ->(response) do
-
28
blk.call(response)
-
end
-
28
self
-
else
-
28
@on_response
-
end
-
end
-
-
8
def on_complete(&blk)
-
84
if blk
-
28
@on_complete = blk
-
28
self
-
else
-
56
@on_complete
-
end
-
end
-
end
-
-
8
include RequestMixin
-
-
8
def initialize(options)
-
28
@handlers = []
-
28
@connection_options = options
-
end
-
-
8
def enqueue(request)
-
28
handler = ResponseHandler.new(request)
-
28
@handlers << handler
-
28
handler
-
end
-
-
8
def run
-
28
return unless @handlers.last
-
-
21
env = @handlers.last.env
-
-
21
connect(env) do |session|
-
49
requests = @handlers.map { |handler| session.build_request(*build_request(handler.env)) }
-
-
21
if env.request.stream_response?
-
7
requests.each do |request|
-
7
request.response_on_data = env.request.on_data
-
end
-
end
-
-
21
responses = session.request(*requests)
-
21
Array(responses).each_with_index do |response, index|
-
28
handler = @handlers[index]
-
28
handler.on_response.call(response)
-
28
handler.on_complete.call(handler.env) if handler.on_complete
-
end
-
end
-
rescue ::HTTPX::TimeoutError => e
-
raise Faraday::TimeoutError, e
-
end
-
-
# from Faraday::Adapter#connection
-
8
def connection(env)
-
21
conn = build_connection(env)
-
21
return conn unless block_given?
-
-
21
yield conn
-
end
-
-
8
private
-
-
# from Faraday::Adapter#request_timeout
-
8
def request_timeout(type, options)
-
147
key = Faraday::Adapter::TIMEOUT_KEYS[type]
-
147
options[key] || options[:timeout]
-
end
-
end
-
-
8
self.supports_parallel = true
-
-
8
class << self
-
8
def setup_parallel_manager(options = {})
-
28
ParallelManager.new(options)
-
end
-
end
-
-
8
def call(env)
-
197
super
-
197
if parallel?(env)
-
28
handler = env[:parallel_manager].enqueue(env)
-
28
handler.on_response do |response|
-
28
if response.is_a?(::HTTPX::Response)
-
21
save_response(env, response.status, response.body.to_s, response.headers, response.reason) do |response_headers|
-
21
response_headers.merge!(response.headers)
-
end
-
else
-
6
env[:error] = response.error
-
7
save_response(env, 0, "", {}, nil)
-
end
-
end
-
24
return handler
-
end
-
-
169
response = connect_and_request(env)
-
134
save_response(env, response.status, response.body.to_s, response.headers, response.reason) do |response_headers|
-
134
response_headers.merge!(response.headers)
-
end
-
134
@app.call(env)
-
end
-
-
8
private
-
-
8
def connect_and_request(env)
-
169
connect(env) do |session|
-
169
request = session.build_request(*build_request(env))
-
-
169
request.response_on_data = env.request.on_data if env.request.stream_response?
-
-
169
response = session.request(request)
-
# do not call #raise_for_status for HTTP 4xx or 5xx, as faraday has a middleware for that.
-
169
response.raise_for_status unless response.is_a?(::HTTPX::Response)
-
134
response
-
end
-
rescue ::HTTPX::TimeoutError => e
-
21
raise Faraday::TimeoutError, e
-
end
-
-
8
def parallel?(env)
-
197
env[:parallel_manager]
-
end
-
end
-
-
8
register_middleware httpx: HTTPX
-
end
-
end
-
# frozen_string_literal: true
-
-
5
require "sentry-ruby"
-
-
5
module HTTPX::Plugins
-
5
module Sentry
-
5
module Tracer
-
5
module_function
-
-
5
def call(request)
-
59
sentry_span = start_sentry_span
-
-
59
return unless sentry_span
-
-
59
set_sentry_trace_header(request, sentry_span)
-
-
59
request.on(:response, &method(:finish_sentry_span).curry(3)[sentry_span, request])
-
end
-
-
5
def start_sentry_span
-
59
return unless ::Sentry.initialized? && (span = ::Sentry.get_current_scope.get_span)
-
59
return if span.sampled == false
-
-
59
span.start_child(op: "httpx.client", start_timestamp: ::Sentry.utc_now.to_f)
-
end
-
-
5
def set_sentry_trace_header(request, sentry_span)
-
59
return unless sentry_span
-
-
59
config = ::Sentry.configuration
-
59
url = request.uri.to_s
-
-
118
return unless config.propagate_traces && config.trace_propagation_targets.any? { |target| url.match?(target) }
-
-
59
trace = ::Sentry.get_current_client.generate_sentry_trace(sentry_span)
-
59
request.headers[::Sentry::SENTRY_TRACE_HEADER_NAME] = trace if trace
-
end
-
-
5
def finish_sentry_span(span, request, response)
-
61
return unless ::Sentry.initialized?
-
-
61
record_sentry_breadcrumb(request, response)
-
61
record_sentry_span(request, response, span)
-
end
-
-
5
def record_sentry_breadcrumb(req, res)
-
61
return unless ::Sentry.configuration.breadcrumbs_logger.include?(:http_logger)
-
-
61
request_info = extract_request_info(req)
-
-
61
data = if res.is_a?(HTTPX::ErrorResponse)
-
6
{ error: res.error.message, **request_info }
-
else
-
55
{ status: res.status, **request_info }
-
end
-
-
61
crumb = ::Sentry::Breadcrumb.new(
-
level: :info,
-
category: "httpx",
-
type: :info,
-
data: data
-
)
-
61
::Sentry.add_breadcrumb(crumb)
-
end
-
-
5
def record_sentry_span(req, res, sentry_span)
-
61
return unless sentry_span
-
-
61
request_info = extract_request_info(req)
-
61
sentry_span.set_description("#{request_info[:method]} #{request_info[:url]}")
-
61
if res.is_a?(HTTPX::ErrorResponse)
-
6
sentry_span.set_data(:error, res.error.message)
-
else
-
55
sentry_span.set_data(:status, res.status)
-
end
-
61
sentry_span.set_timestamp(::Sentry.utc_now.to_f)
-
end
-
-
5
def extract_request_info(req)
-
122
uri = req.uri
-
-
result = {
-
122
method: req.verb,
-
}
-
-
122
if ::Sentry.configuration.send_default_pii
-
20
uri += "?#{req.query}" unless req.query.empty?
-
20
result[:body] = req.body.to_s unless req.body.empty? || req.body.unbounded_body?
-
end
-
-
122
result[:url] = uri.to_s
-
-
122
result
-
end
-
end
-
-
5
module RequestMethods
-
5
def __sentry_enable_trace!
-
61
return if @__sentry_enable_trace
-
-
59
Tracer.call(self)
-
59
@__sentry_enable_trace = true
-
end
-
end
-
-
5
module ConnectionMethods
-
5
def send(request)
-
61
request.__sentry_enable_trace!
-
-
61
super
-
end
-
end
-
end
-
end
-
-
5
Sentry.register_patch(:httpx) do
-
25
sentry_session = HTTPX.plugin(HTTPX::Plugins::Sentry)
-
-
25
HTTPX.send(:remove_const, :Session)
-
25
HTTPX.send(:const_set, :Session, sentry_session.class)
-
end
-
# frozen_string_literal: true
-
-
7
module WebMock
-
7
module HttpLibAdapters
-
7
require "net/http/status"
-
7
HTTP_REASONS = Net::HTTP::STATUS_CODES
-
-
#
-
# HTTPX plugin for webmock.
-
#
-
# Requests are "hijacked" at the session, before they're distributed to a connection.
-
#
-
7
module Plugin
-
7
class << self
-
7
def build_webmock_request_signature(request)
-
157
uri = WebMock::Util::URI.heuristic_parse(request.uri)
-
157
uri.query = request.query
-
157
uri.path = uri.normalized_path.gsub("[^:]//", "/")
-
-
157
WebMock::RequestSignature.new(
-
request.verb.downcase.to_sym,
-
uri.to_s,
-
body: request.body.to_s,
-
headers: request.headers.to_h
-
)
-
end
-
-
7
def build_webmock_response(_request, response)
-
5
webmock_response = WebMock::Response.new
-
5
webmock_response.status = [response.status, HTTP_REASONS[response.status]]
-
5
webmock_response.body = response.body.to_s
-
5
webmock_response.headers = response.headers.to_h
-
5
webmock_response
-
end
-
-
7
def build_from_webmock_response(request, webmock_response)
-
132
return build_error_response(request, HTTPX::TimeoutError.new(1, "Timed out")) if webmock_response.should_timeout
-
-
117
return build_error_response(request, webmock_response.exception) if webmock_response.exception
-
-
111
request.options.response_class.new(request,
-
webmock_response.status[0],
-
"2.0",
-
webmock_response.headers).tap do |res|
-
111
res.mocked = true
-
end
-
end
-
-
7
def build_error_response(request, exception)
-
21
HTTPX::ErrorResponse.new(request, exception)
-
end
-
end
-
-
7
module InstanceMethods
-
7
def init_connection(*)
-
132
connection = super
-
132
connection.once(:unmock_connection) do
-
20
unless connection.addresses
-
20
connection.__send__(:callbacks)[:connect_error].clear
-
20
pool.__send__(:unregister_connection, connection)
-
end
-
20
pool.__send__(:resolve_connection, connection)
-
end
-
132
connection
-
end
-
end
-
-
7
module ResponseMethods
-
7
attr_accessor :mocked
-
-
7
def initialize(*)
-
131
super
-
131
@mocked = false
-
end
-
end
-
-
7
module ResponseBodyMethods
-
7
def decode_chunk(chunk)
-
80
return chunk if @response.mocked
-
-
35
super
-
end
-
end
-
-
7
module ConnectionMethods
-
7
def initialize(*)
-
132
super
-
132
@mocked = true
-
end
-
-
7
def open?
-
152
return true if @mocked
-
-
20
super
-
end
-
-
7
def interests
-
4034
return if @mocked
-
-
205
super
-
end
-
-
7
def send(request)
-
157
request_signature = Plugin.build_webmock_request_signature(request)
-
157
WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
-
-
157
if (mock_response = WebMock::StubRegistry.instance.response_for_request(request_signature))
-
132
response = Plugin.build_from_webmock_response(request, mock_response)
-
132
WebMock::CallbackRegistry.invoke_callbacks({ lib: :httpx }, request_signature, mock_response)
-
132
log { "mocking #{request.uri} with #{mock_response.inspect}" }
-
132
request.response = response
-
132
request.emit(:response, response)
-
132
response << mock_response.body.dup unless response.is_a?(HTTPX::ErrorResponse)
-
25
elsif WebMock.net_connect_allowed?(request_signature.uri)
-
20
if WebMock::CallbackRegistry.any_callbacks?
-
5
request.on(:response) do |resp|
-
5
unless resp.is_a?(HTTPX::ErrorResponse)
-
5
webmock_response = Plugin.build_webmock_response(request, resp)
-
5
WebMock::CallbackRegistry.invoke_callbacks(
-
{ lib: :httpx, real_request: true }, request_signature,
-
webmock_response
-
)
-
end
-
end
-
end
-
20
@mocked = false
-
20
emit(:unmock_connection, self)
-
20
super
-
else
-
5
raise WebMock::NetConnectNotAllowedError, request_signature
-
end
-
end
-
end
-
end
-
-
7
class HttpxAdapter < HttpLibAdapter
-
7
adapter_for :httpx
-
-
7
class << self
-
7
def enable!
-
309
@original_session ||= HTTPX::Session
-
-
309
webmock_session = HTTPX.plugin(Plugin)
-
-
309
HTTPX.send(:remove_const, :Session)
-
309
HTTPX.send(:const_set, :Session, webmock_session.class)
-
end
-
-
7
def disable!
-
309
return unless @original_session
-
-
302
HTTPX.send(:remove_const, :Session)
-
302
HTTPX.send(:const_set, :Session, @original_session)
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "strscan"
-
-
24
module HTTPX
-
24
module AltSvc
-
# makes connections able to accept requests destined to primary service.
-
24
module ConnectionMixin
-
24
using URIExtensions
-
-
24
def send(request)
-
7
request.headers["alt-used"] = @origin.authority if @parser && !@write_buffer.full? && match_altsvcs?(request.uri)
-
-
7
super
-
end
-
-
24
def match?(uri, options)
-
7
return false if !used? && (@state == :closing || @state == :closed)
-
-
7
match_altsvcs?(uri) && match_altsvc_options?(uri, options)
-
end
-
-
24
private
-
-
# checks if this is connection is an alternative service of
-
# +uri+
-
24
def match_altsvcs?(uri)
-
21
@origins.any? { |origin| altsvc_match?(uri, origin) } ||
-
AltSvc.cached_altsvc(@origin).any? do |altsvc|
-
origin = altsvc["origin"]
-
altsvc_match?(origin, uri.origin)
-
end
-
end
-
-
24
def match_altsvc_options?(uri, options)
-
7
return @options == options unless @options.ssl.all? do |k, v|
-
7
v == (k == :hostname ? uri.host : options.ssl[k])
-
end
-
-
7
@options.options_equals?(options, Options::REQUEST_BODY_IVARS + %i[@ssl])
-
end
-
-
24
def altsvc_match?(uri, other_uri)
-
14
other_uri = URI(other_uri)
-
-
14
uri.origin == other_uri.origin || begin
-
6
case uri.scheme
-
when "h2"
-
(other_uri.scheme == "https" || other_uri.scheme == "h2") &&
-
uri.host == other_uri.host &&
-
uri.port == other_uri.port
-
else
-
7
false
-
end
-
end
-
end
-
end
-
-
24
@altsvc_mutex = Thread::Mutex.new
-
42
@altsvcs = Hash.new { |h, k| h[k] = [] }
-
-
24
module_function
-
-
24
def cached_altsvc(origin)
-
35
now = Utils.now
-
35
@altsvc_mutex.synchronize do
-
35
lookup(origin, now)
-
end
-
end
-
-
24
def cached_altsvc_set(origin, entry)
-
21
now = Utils.now
-
21
@altsvc_mutex.synchronize do
-
21
return if @altsvcs[origin].any? { |altsvc| altsvc["origin"] == entry["origin"] }
-
-
21
entry["TTL"] = Integer(entry["ma"]) + now if entry.key?("ma")
-
21
@altsvcs[origin] << entry
-
21
entry
-
end
-
end
-
-
24
def lookup(origin, ttl)
-
35
return [] unless @altsvcs.key?(origin)
-
-
24
@altsvcs[origin] = @altsvcs[origin].select do |entry|
-
21
!entry.key?("TTL") || entry["TTL"] > ttl
-
end
-
42
@altsvcs[origin].reject { |entry| entry["noop"] }
-
end
-
-
24
def emit(request, response)
-
6396
return unless response.respond_to?(:headers)
-
# Alt-Svc
-
6374
return unless response.headers.key?("alt-svc")
-
-
72
origin = request.origin
-
72
host = request.uri.host
-
-
72
altsvc = response.headers["alt-svc"]
-
-
# https://datatracker.ietf.org/doc/html/rfc7838#section-3
-
# A field value containing the special value "clear" indicates that the
-
# origin requests all alternatives for that origin to be invalidated
-
# (including those specified in the same response, in case of an
-
# invalid reply containing both "clear" and alternative services).
-
72
if altsvc == "clear"
-
7
@altsvc_mutex.synchronize do
-
7
@altsvcs[origin].clear
-
end
-
-
6
return
-
end
-
-
65
parse(altsvc) do |alt_origin, alt_params|
-
7
alt_origin.host ||= host
-
7
yield(alt_origin, origin, alt_params)
-
end
-
end
-
-
24
def parse(altsvc)
-
163
return enum_for(__method__, altsvc) unless block_given?
-
-
114
scanner = StringScanner.new(altsvc)
-
120
until scanner.eos?
-
114
alt_service = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
-
-
114
alt_params = []
-
114
loop do
-
135
alt_param = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
-
135
alt_params << alt_param.strip if alt_param
-
135
scanner.skip(/;/)
-
135
break if scanner.eos? || scanner.scan(/ *, */)
-
end
-
228
alt_params = Hash[alt_params.map { |field| field.split("=", 2) }]
-
-
114
alt_proto, alt_authority = alt_service.split("=", 2)
-
114
alt_origin = parse_altsvc_origin(alt_proto, alt_authority)
-
114
return unless alt_origin
-
-
42
yield(alt_origin, alt_params.merge("proto" => alt_proto))
-
end
-
end
-
-
24
def parse_altsvc_scheme(alt_proto)
-
118
case alt_proto
-
when "h2c"
-
7
"http"
-
when "h2"
-
49
"https"
-
end
-
end
-
-
24
def parse_altsvc_origin(alt_proto, alt_origin)
-
114
alt_scheme = parse_altsvc_scheme(alt_proto)
-
-
114
return unless alt_scheme
-
-
42
alt_origin = alt_origin[1..-2] if alt_origin.start_with?("\"") && alt_origin.end_with?("\"")
-
-
42
URI.parse("#{alt_scheme}://#{alt_origin}")
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "forwardable"
-
-
24
module HTTPX
-
# Internal class to abstract a string buffer, by wrapping a string and providing the
-
# minimum possible API and functionality required.
-
#
-
# buffer = Buffer.new(640)
-
# buffer.full? #=> false
-
# buffer << "aa"
-
# buffer.capacity #=> 638
-
#
-
24
class Buffer
-
24
extend Forwardable
-
-
24
def_delegator :@buffer, :<<
-
-
24
def_delegator :@buffer, :to_s
-
-
24
def_delegator :@buffer, :to_str
-
-
24
def_delegator :@buffer, :empty?
-
-
24
def_delegator :@buffer, :bytesize
-
-
24
def_delegator :@buffer, :clear
-
-
24
def_delegator :@buffer, :replace
-
-
24
attr_reader :limit
-
-
24
def initialize(limit)
-
12489
@buffer = "".b
-
12489
@limit = limit
-
end
-
-
24
def full?
-
100451
@buffer.bytesize >= @limit
-
end
-
-
24
def capacity
-
10
@limit - @buffer.bytesize
-
end
-
-
24
def shift!(fin)
-
17633
@buffer = @buffer.byteslice(fin..-1) || "".b
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
module Callbacks
-
24
def on(type, &action)
-
232586
callbacks(type) << action
-
232586
self
-
end
-
-
24
def once(type, &block)
-
87295
on(type) do |*args, &callback|
-
86222
block.call(*args, &callback)
-
86166
:delete
-
end
-
87295
self
-
end
-
-
24
def only(type, &block)
-
17856
callbacks(type).clear
-
17856
on(type, &block)
-
end
-
-
24
def emit(type, *args)
-
264311
callbacks(type).delete_if { |pr| :delete == pr.call(*args) } # rubocop:disable Style/YodaCondition
-
end
-
-
24
def callbacks_for?(type)
-
2615
@callbacks.key?(type) && @callbacks[type].any?
-
end
-
-
24
protected
-
-
24
def callbacks(type = nil)
-
374202
return @callbacks unless type
-
-
549726
@callbacks ||= Hash.new { |h, k| h[k] = [] }
-
374106
@callbacks[type]
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
# Session mixin, implements most of the APIs that the users call.
-
# delegates to a default session when extended.
-
24
module Chainable
-
24
%w[head get post put delete trace options connect patch].each do |meth|
-
207
class_eval(<<-MOD, __FILE__, __LINE__ + 1)
-
9
def #{meth}(*uri, **options) # def get(*uri, **options)
-
18
request("#{meth.upcase}", uri, **options) # request("GET", uri, **options)
-
end # end
-
MOD
-
end
-
-
# delegates to the default session (see HTTPX::Session#request).
-
24
def request(*args, **options)
-
2147
branch(default_options).request(*args, **options)
-
end
-
-
24
def accept(type)
-
14
with(headers: { "accept" => String(type) })
-
end
-
-
# delegates to the default session (see HTTPX::Session#wrap).
-
24
def wrap(&blk)
-
85
branch(default_options).wrap(&blk)
-
end
-
-
# returns a new instance loaded with the +pl+ plugin and +options+.
-
24
def plugin(pl, options = nil, &blk)
-
3976
klass = is_a?(S) ? self.class : Session
-
3976
klass = Class.new(klass)
-
3976
klass.instance_variable_set(:@default_options, klass.default_options.merge(default_options))
-
3976
klass.plugin(pl, options, &blk).new
-
end
-
-
# returns a new instance loaded with +options+.
-
24
def with(options, &blk)
-
2122
branch(default_options.merge(options), &blk)
-
end
-
-
24
private
-
-
# returns default instance of HTTPX::Options.
-
24
def default_options
-
8379
@options || Session.default_options
-
end
-
-
# returns a default instance of HTTPX::Session.
-
24
def branch(options, &blk)
-
4354
return self.class.new(options, &blk) if is_a?(S)
-
-
2543
Session.new(options, &blk)
-
end
-
-
24
def method_missing(meth, *args, **options, &blk)
-
558
case meth
-
when /\Awith_(.+)/
-
-
636
option = Regexp.last_match(1)
-
-
636
return super unless option
-
-
636
with(option.to_sym => args.first || options)
-
when /\Aon_(.+)/
-
8
callback = Regexp.last_match(1)
-
-
7
return super unless %w[
-
connection_opened connection_closed
-
request_error
-
request_started request_body_chunk request_completed
-
response_started response_body_chunk response_completed
-
].include?(callback)
-
-
8
warn "DEPRECATION WARNING: calling `.#{meth}` on plain HTTPX sessions is deprecated. " \
-
1
"Use HTTPX.plugin(:callbacks).#{meth} instead."
-
-
8
plugin(:callbacks).__send__(meth, *args, **options, &blk)
-
else
-
super
-
end
-
end
-
-
24
def respond_to_missing?(meth, *)
-
42
case meth
-
when /\Awith_(.+)/
-
35
option = Regexp.last_match(1)
-
-
35
default_options.respond_to?(option) || super
-
when /\Aon_(.+)/
-
14
callback = Regexp.last_match(1)
-
-
12
%w[
-
connection_opened connection_closed
-
request_error
-
request_started request_body_chunk request_completed
-
response_started response_body_chunk response_completed
-
1
].include?(callback) || super
-
else
-
super
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "resolv"
-
24
require "forwardable"
-
24
require "httpx/io"
-
24
require "httpx/buffer"
-
-
24
module HTTPX
-
# The Connection can be watched for IO events.
-
#
-
# It contains the +io+ object to read/write from, and knows what to do when it can.
-
#
-
# It defers connecting until absolutely necessary. Connection should be triggered from
-
# the IO selector (until then, any request will be queued).
-
#
-
# A connection boots up its parser after connection is established. All pending requests
-
# will be redirected there after connection.
-
#
-
# A connection can be prevented from closing by the parser, that is, if there are pending
-
# requests. This will signal that the connection was prematurely closed, due to a possible
-
# number of conditions:
-
#
-
# * Remote peer closed the connection ("Connection: close");
-
# * Remote peer doesn't support pipelining;
-
#
-
# A connection may also route requests for a different host for which the +io+ was connected
-
# to, provided that the IP is the same and the port and scheme as well. This will allow to
-
# share the same socket to send HTTP/2 requests to different hosts.
-
#
-
24
class Connection
-
24
extend Forwardable
-
24
include Loggable
-
24
include Callbacks
-
-
24
using URIExtensions
-
-
24
require "httpx/connection/http2"
-
24
require "httpx/connection/http1"
-
-
24
def_delegator :@io, :closed?
-
-
24
def_delegator :@write_buffer, :empty?
-
-
24
attr_reader :type, :io, :origin, :origins, :state, :pending, :options, :ssl_session
-
-
24
attr_writer :timers
-
-
24
attr_accessor :family
-
-
24
def initialize(uri, options)
-
5936
@origins = [uri.origin]
-
5936
@origin = Utils.to_uri(uri.origin)
-
5936
@options = Options.new(options)
-
5936
@type = initialize_type(uri, @options)
-
5936
@origins = [uri.origin]
-
5936
@origin = Utils.to_uri(uri.origin)
-
5936
@window_size = @options.window_size
-
5936
@read_buffer = Buffer.new(@options.buffer_size)
-
5936
@write_buffer = Buffer.new(@options.buffer_size)
-
5936
@pending = []
-
5936
on(:error, &method(:on_error))
-
5936
if @options.io
-
# if there's an already open IO, get its
-
# peer address, and force-initiate the parser
-
57
transition(:already_open)
-
57
@io = build_socket
-
57
parser
-
else
-
5879
transition(:idle)
-
end
-
-
5936
@inflight = 0
-
5936
@keep_alive_timeout = @options.timeout[:keep_alive_timeout]
-
-
5936
@intervals = []
-
-
5936
self.addresses = @options.addresses if @options.addresses
-
end
-
-
# this is a semi-private method, to be used by the resolver
-
# to initiate the io object.
-
24
def addresses=(addrs)
-
5738
if @io
-
179
@io.add_addresses(addrs)
-
else
-
5559
@io = build_socket(addrs)
-
end
-
end
-
-
24
def addresses
-
25410
@io && @io.addresses
-
end
-
-
24
def match?(uri, options)
-
12706
return false if !used? && (@state == :closing || @state == :closed)
-
-
476
(
-
12503
@origins.include?(uri.origin) &&
-
# if there is more than one origin to match, it means that this connection
-
# was the result of coalescing. To prevent blind trust in the case where the
-
# origin came from an ORIGIN frame, we're going to verify the hostname with the
-
# SSL certificate
-
2710
(@origins.size == 1 || @origin == uri.origin || (@io.is_a?(SSL) && @io.verify_hostname(uri.host)))
-
) && @options == options
-
end
-
-
24
def expired?
-
return false unless @io
-
-
@io.expired?
-
end
-
-
24
def mergeable?(connection)
-
9953
return false if @state == :closing || @state == :closed || !@io
-
-
6836
return false unless connection.addresses
-
-
90
(
-
6836
(open? && @origin == connection.origin) ||
-
6761
!(@io.addresses & (connection.addresses || [])).empty?
-
) && @options == connection.options
-
end
-
-
# coalescable connections need to be mergeable!
-
# but internally, #mergeable? is called before #coalescable?
-
24
def coalescable?(connection)
-
13
if @io.protocol == "h2" &&
-
@origin.scheme == "https" &&
-
connection.origin.scheme == "https" &&
-
@io.can_verify_peer?
-
6
@io.verify_hostname(connection.origin.host)
-
else
-
7
@origin == connection.origin
-
end
-
end
-
-
24
def create_idle(options = {})
-
7
self.class.new(@origin, @options.merge(options))
-
end
-
-
24
def merge(connection)
-
23
@origins |= connection.instance_variable_get(:@origins)
-
25
if connection.ssl_session
-
6
@ssl_session = connection.ssl_session
-
@io.session_new_cb do |sess|
-
@ssl_session = sess
-
6
end if @io
-
end
-
25
connection.purge_pending do |req|
-
6
send(req)
-
end
-
end
-
-
24
def purge_pending(&block)
-
25
pendings = []
-
25
if @parser
-
12
@inflight -= @parser.pending.size
-
14
pendings << @parser.pending
-
end
-
25
pendings << @pending
-
25
pendings.each do |pending|
-
39
pending.reject!(&block)
-
end
-
end
-
-
24
def connecting?
-
126717
@state == :idle
-
end
-
-
24
def inflight?
-
5649
@parser && !@parser.empty? && !@write_buffer.empty?
-
end
-
-
24
def interests
-
# connecting
-
117620
if connecting?
-
8823
connect
-
-
8823
return @io.interests if connecting?
-
end
-
-
# if the write buffer is full, we drain it
-
109393
return :w unless @write_buffer.empty?
-
-
75883
return @parser.interests if @parser
-
-
9
nil
-
end
-
-
24
def to_io
-
19088
@io.to_io
-
end
-
-
24
def call
-
15240
case @state
-
when :idle
-
8096
connect
-
8082
consume
-
when :closed
-
return
-
when :closing
-
consume
-
transition(:closed)
-
when :open
-
8720
consume
-
end
-
3588
nil
-
end
-
-
24
def close
-
5676
transition(:active) if @state == :inactive
-
-
5676
@parser.close if @parser
-
end
-
-
24
def terminate
-
5676
@connected_at = nil if @state == :closed
-
-
5676
close
-
end
-
-
# bypasses the state machine to force closing of connections still connecting.
-
# **only** used for Happy Eyeballs v2.
-
24
def force_reset
-
135
@state = :closing
-
135
transition(:closed)
-
end
-
-
24
def reset
-
9124
return if @state == :closing || @state == :closed
-
-
6191
transition(:closing)
-
-
6191
transition(:closed)
-
end
-
-
24
def send(request)
-
7233
if @parser && !@write_buffer.full?
-
356
if @response_received_at && @keep_alive_timeout &&
-
Utils.elapsed_time(@response_received_at) > @keep_alive_timeout
-
# when pushing a request into an existing connection, we have to check whether there
-
# is the possibility that the connection might have extended the keep alive timeout.
-
# for such cases, we want to ping for availability before deciding to shovel requests.
-
7
log(level: 3) { "keep alive timeout expired, pinging connection..." }
-
7
@pending << request
-
7
transition(:active) if @state == :inactive
-
7
parser.ping
-
6
return
-
end
-
-
349
send_request_to_parser(request)
-
else
-
6877
@pending << request
-
end
-
end
-
-
24
def timeout
-
3652852
return @timeout if @timeout
-
-
3578022
return @options.timeout[:connect_timeout] if @state == :idle
-
-
3578022
@options.timeout[:operation_timeout]
-
end
-
-
24
def idling
-
565
purge_after_closed
-
565
@write_buffer.clear
-
565
transition(:idle)
-
565
@parser = nil if @parser
-
end
-
-
24
def used?
-
19519
@connected_at
-
end
-
-
24
def deactivate
-
1013
transition(:inactive)
-
end
-
-
24
def open?
-
12595
@state == :open || @state == :inactive
-
end
-
-
24
def handle_socket_timeout(interval)
-
390
@intervals.delete_if(&:elapsed?)
-
-
390
unless @intervals.empty?
-
# remove the intervals which will elapse
-
-
310
return
-
end
-
-
28
error = HTTPX::TimeoutError.new(interval, "timed out while waiting on select")
-
28
error.set_backtrace(caller)
-
28
on_error(error)
-
end
-
-
24
private
-
-
24
def connect
-
16037
transition(:open)
-
end
-
-
24
def consume
-
19344
return unless @io
-
-
19344
catch(:called) do
-
19344
epiped = false
-
19344
loop do
-
# connection may have
-
35682
return if @state == :idle
-
-
33273
parser.consume
-
-
# we exit if there's no more requests to process
-
#
-
# this condition takes into account:
-
#
-
# * the number of inflight requests
-
# * the number of pending requests
-
# * whether the write buffer has bytes (i.e. for close handshake)
-
33259
if @pending.empty? && @inflight.zero? && @write_buffer.empty?
-
2332
log(level: 3) { "NO MORE REQUESTS..." }
-
2318
return
-
end
-
-
30941
@timeout = @current_timeout
-
-
30941
read_drained = false
-
30941
write_drained = nil
-
-
#
-
# tight read loop.
-
#
-
# read as much of the socket as possible.
-
#
-
# this tight loop reads all the data it can from the socket and pipes it to
-
# its parser.
-
#
-
2253
loop do
-
40408
siz = @io.read(@window_size, @read_buffer)
-
40510
log(level: 3, color: :cyan) { "IO READ: #{siz} bytes... (wsize: #{@window_size}, rbuffer: #{@read_buffer.bytesize})" }
-
40408
unless siz
-
13
ex = EOFError.new("descriptor closed")
-
13
ex.set_backtrace(caller)
-
13
on_error(ex)
-
13
return
-
end
-
-
# socket has been drained. mark and exit the read loop.
-
40395
if siz.zero?
-
7990
read_drained = @read_buffer.empty?
-
7990
epiped = false
-
7990
break
-
end
-
-
32405
parser << @read_buffer.to_s
-
-
# continue reading if possible.
-
28953
break if interests == :w && !epiped
-
-
# exit the read loop if connection is preparing to be closed
-
22921
break if @state == :closing || @state == :closed
-
-
# exit #consume altogether if all outstanding requests have been dealt with
-
22915
return if @pending.empty? && @inflight.zero?
-
30941
end unless ((ints = interests).nil? || ints == :w || @state == :closing) && !epiped
-
-
#
-
# tight write loop.
-
#
-
# flush as many bytes as the sockets allow.
-
#
-
2135
loop do
-
# buffer has been drainned, mark and exit the write loop.
-
19505
if @write_buffer.empty?
-
# we only mark as drained on the first loop
-
2433
write_drained = write_drained.nil? && @inflight.positive?
-
-
2433
break
-
end
-
-
1905
begin
-
17072
siz = @io.write(@write_buffer)
-
rescue Errno::EPIPE
-
# this can happen if we still have bytes in the buffer to send to the server, but
-
# the server wants to respond immediately with some message, or an error. An example is
-
# when one's uploading a big file to an unintended endpoint, and the server stops the
-
# consumption, and responds immediately with an authorization of even method not allowed error.
-
# at this point, we have to let the connection switch to read-mode.
-
18
log(level: 2) { "pipe broken, could not flush buffer..." }
-
18
epiped = true
-
18
read_drained = false
-
18
break
-
end
-
17122
log(level: 3, color: :cyan) { "IO WRITE: #{siz} bytes..." }
-
17046
unless siz
-
ex = EOFError.new("descriptor closed")
-
ex.set_backtrace(caller)
-
on_error(ex)
-
return
-
end
-
-
# socket closed for writing. mark and exit the write loop.
-
17046
if siz.zero?
-
21
write_drained = !@write_buffer.empty?
-
21
break
-
end
-
-
# exit write loop if marked to consume from peer, or is closing.
-
17025
break if interests == :r || @state == :closing || @state == :closed
-
-
2477
write_drained = false
-
25001
end unless (ints = interests) == :r
-
-
24993
send_pending if @state == :open
-
-
# return if socket is drained
-
24993
next unless (ints != :r || read_drained) && (ints != :w || write_drained)
-
-
# gotta go back to the event loop. It happens when:
-
#
-
# * the socket is drained of bytes or it's not the interest of the conn to read;
-
# * theres nothing more to write, or it's not in the interest of the conn to write;
-
8682
log(level: 3) { "(#{ints}): WAITING FOR EVENTS..." }
-
8655
return
-
end
-
end
-
end
-
-
24
def send_pending
-
65955
while !@write_buffer.full? && (request = @pending.shift)
-
17070
send_request_to_parser(request)
-
end
-
end
-
-
24
def parser
-
90002
@parser ||= build_parser
-
end
-
-
24
def send_request_to_parser(request)
-
16582
@inflight += 1
-
17419
request.peer_address = @io.ip
-
17419
parser.send(request)
-
-
17419
set_request_timeouts(request)
-
-
17419
return unless @state == :inactive
-
-
80
transition(:active)
-
end
-
-
24
def build_parser(protocol = @io.protocol)
-
5890
parser = self.class.parser_type(protocol).new(@write_buffer, @options)
-
5890
set_parser_callbacks(parser)
-
5890
parser
-
end
-
-
24
def set_parser_callbacks(parser)
-
5987
parser.on(:response) do |request, response|
-
6389
AltSvc.emit(request, response) do |alt_origin, origin, alt_params|
-
7
emit(:altsvc, alt_origin, origin, alt_params)
-
end
-
6389
@response_received_at = Utils.now
-
5626
@inflight -= 1
-
6389
request.emit(:response, response)
-
end
-
5987
parser.on(:altsvc) do |alt_origin, origin, alt_params|
-
emit(:altsvc, alt_origin, origin, alt_params)
-
end
-
-
5987
parser.on(:pong, &method(:send_pending))
-
-
5987
parser.on(:promise) do |request, stream|
-
21
request.emit(:promise, parser, stream)
-
end
-
5987
parser.on(:exhausted) do
-
7
@pending.concat(parser.pending)
-
7
emit(:exhausted)
-
end
-
5987
parser.on(:origin) do |origin|
-
@origins |= [origin]
-
end
-
5987
parser.on(:close) do |force|
-
5287
if force
-
5287
reset
-
5280
emit(:terminate)
-
end
-
end
-
5987
parser.on(:close_handshake) do
-
7
consume
-
end
-
5987
parser.on(:reset) do
-
3124
@pending.concat(parser.pending) unless parser.empty?
-
3124
reset
-
3117
idling unless @pending.empty?
-
end
-
5987
parser.on(:current_timeout) do
-
2537
@current_timeout = @timeout = parser.timeout
-
end
-
5987
parser.on(:timeout) do |tout|
-
2380
@timeout = tout
-
end
-
5987
parser.on(:error) do |request, ex|
-
42
case ex
-
when MisdirectedRequestError
-
7
emit(:misdirected, request)
-
else
-
41
response = ErrorResponse.new(request, ex)
-
41
request.response = response
-
41
request.emit(:response, response)
-
end
-
end
-
end
-
-
24
def transition(nextstate)
-
37851
handle_transition(nextstate)
-
rescue Errno::ECONNABORTED,
-
Errno::ECONNREFUSED,
-
Errno::ECONNRESET,
-
Errno::EADDRNOTAVAIL,
-
Errno::EHOSTUNREACH,
-
Errno::EINVAL,
-
Errno::ENETUNREACH,
-
Errno::EPIPE,
-
Errno::ENOENT,
-
SocketError,
-
IOError => e
-
# connect errors, exit gracefully
-
64
error = ConnectionError.new(e.message)
-
64
error.set_backtrace(e.backtrace)
-
64
connecting? && callbacks_for?(:connect_error) ? emit(:connect_error, error) : handle_error(error)
-
64
@state = :closed
-
64
emit(:close)
-
rescue TLSError, ::HTTP2::Error::ProtocolError, ::HTTP2::Error::HandshakeError => e
-
# connect errors, exit gracefully
-
22
handle_error(e)
-
22
connecting? && callbacks_for?(:connect_error) ? emit(:connect_error, e) : handle_error(e)
-
22
@state = :closed
-
22
emit(:close)
-
end
-
-
24
def handle_transition(nextstate)
-
32797
case nextstate
-
when :idle
-
6458
@timeout = @current_timeout = @options.timeout[:connect_timeout]
-
-
6458
@connected_at = nil
-
when :open
-
16296
return if @state == :closed
-
-
16296
@io.connect
-
16211
emit(:tcp_open, self) if @io.state == :connected
-
-
16211
return unless @io.connected?
-
-
5895
@connected_at = Utils.now
-
-
5895
send_pending
-
-
5895
@timeout = @current_timeout = parser.timeout
-
5895
emit(:open)
-
when :inactive
-
1013
return unless @state == :open
-
-
# do not deactivate connection in use
-
583
return if @inflight.positive?
-
when :closing
-
6248
return unless @state == :idle || @state == :open
-
-
6224
unless @write_buffer.empty?
-
# preset state before handshake, as error callbacks
-
# may take it back here.
-
2258
@state = nextstate
-
# handshakes, try sending
-
2258
consume
-
2257
@write_buffer.clear
-
2257
return
-
end
-
when :closed
-
6333
return unless @state == :closing
-
6315
return unless @write_buffer.empty?
-
-
6293
purge_after_closed
-
6293
emit(:close) if @pending.empty?
-
when :already_open
-
57
nextstate = :open
-
# the first check for given io readiness must still use a timeout.
-
# connect is the reasonable choice in such a case.
-
57
@timeout = @options.timeout[:connect_timeout]
-
57
send_pending
-
when :active
-
493
return unless @state == :inactive
-
-
493
nextstate = :open
-
493
emit(:activate)
-
end
-
24201
@state = nextstate
-
end
-
-
24
def purge_after_closed
-
6865
@io.close if @io
-
6865
@read_buffer.clear
-
6865
@timeout = nil
-
end
-
-
24
def initialize_type(uri, options)
-
5616
options.transport || begin
-
4883
case uri.scheme
-
when "http"
-
3075
"tcp"
-
when "https"
-
2517
"ssl"
-
else
-
raise UnsupportedSchemeError, "#{uri}: #{uri.scheme}: unsupported URI scheme"
-
end
-
end
-
end
-
-
24
def build_socket(addrs = nil)
-
4877
case @type
-
when "tcp"
-
3161
TCP.new(@origin, addrs, @options)
-
when "ssl"
-
2431
SSL.new(@origin, addrs, @options) do |sock|
-
2412
sock.ssl_session = @ssl_session
-
2412
sock.session_new_cb do |sess|
-
4047
@ssl_session = sess
-
-
4047
sock.ssl_session = sess
-
end
-
end
-
when "unix"
-
24
path = Array(addrs).first
-
-
24
path = String(path) if path
-
-
24
UNIX.new(@origin, path, @options)
-
else
-
raise Error, "unsupported transport (#{@type})"
-
end
-
end
-
-
24
def on_error(error, request = nil)
-
699
if error.instance_of?(TimeoutError)
-
-
# inactive connections do not contribute to the select loop, therefore
-
# they should not fail due to such errors.
-
28
return if @state == :inactive
-
-
28
if @timeout
-
24
@timeout -= error.timeout
-
28
return unless @timeout <= 0
-
end
-
-
28
error = error.to_connection_error if connecting?
-
end
-
699
handle_error(error, request)
-
699
reset
-
end
-
-
24
def handle_error(error, request = nil)
-
807
parser.handle_error(error, request) if @parser && parser.respond_to?(:handle_error)
-
1760
while (req = @pending.shift)
-
368
next if request && req == request
-
-
368
response = ErrorResponse.new(req, error)
-
368
req.response = response
-
368
req.emit(:response, response)
-
end
-
-
807
return unless request
-
-
358
response = ErrorResponse.new(request, error)
-
358
request.response = response
-
358
request.emit(:response, response)
-
end
-
-
24
def set_request_timeouts(request)
-
17419
set_request_write_timeout(request)
-
17419
set_request_read_timeout(request)
-
17419
set_request_request_timeout(request)
-
end
-
-
24
def set_request_read_timeout(request)
-
17419
read_timeout = request.read_timeout
-
-
17419
return if read_timeout.nil? || read_timeout.infinite?
-
-
17174
set_request_timeout(request, read_timeout, :done, :response) do
-
21
read_timeout_callback(request, read_timeout)
-
end
-
end
-
-
24
def set_request_write_timeout(request)
-
17419
write_timeout = request.write_timeout
-
-
17419
return if write_timeout.nil? || write_timeout.infinite?
-
-
17419
set_request_timeout(request, write_timeout, :headers, %i[done response]) do
-
21
write_timeout_callback(request, write_timeout)
-
end
-
end
-
-
24
def set_request_request_timeout(request)
-
17170
request_timeout = request.request_timeout
-
-
17170
return if request_timeout.nil? || request_timeout.infinite?
-
-
448
set_request_timeout(request, request_timeout, :headers, :complete) do
-
316
read_timeout_callback(request, request_timeout, RequestTimeoutError)
-
end
-
end
-
-
24
def write_timeout_callback(request, write_timeout)
-
21
return if request.state == :done
-
-
21
@write_buffer.clear
-
21
error = WriteTimeoutError.new(request, nil, write_timeout)
-
-
21
on_error(error, request)
-
end
-
-
24
def read_timeout_callback(request, read_timeout, error_type = ReadTimeoutError)
-
337
response = request.response
-
-
337
return if response && response.finished?
-
-
337
@write_buffer.clear
-
337
error = error_type.new(request, request.response, read_timeout)
-
-
337
on_error(error, request)
-
end
-
-
24
def set_request_timeout(request, timeout, start_event, finish_events, &callback)
-
35111
request.once(start_event) do
-
34478
interval = @timers.after(timeout, callback)
-
-
34478
Array(finish_events).each do |event|
-
# clean up request timeouts if the connection errors out
-
51668
request.once(event) do
-
51535
if @intervals.include?(interval)
-
51064
interval.delete(callback)
-
51064
@intervals.delete(interval) if interval.no_callbacks?
-
end
-
end
-
end
-
-
34478
@intervals << interval
-
end
-
end
-
-
24
class << self
-
24
def parser_type(protocol)
-
5232
case protocol
-
2544
when "h2" then HTTP2
-
3472
when "http/1.1" then HTTP1
-
else
-
raise Error, "unsupported protocol (##{protocol})"
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "httpx/parser/http1"
-
-
24
module HTTPX
-
24
class Connection::HTTP1
-
24
include Callbacks
-
24
include Loggable
-
-
24
MAX_REQUESTS = 200
-
24
CRLF = "\r\n"
-
-
24
attr_reader :pending, :requests
-
-
24
attr_accessor :max_concurrent_requests
-
-
24
def initialize(buffer, options)
-
3472
@options = options
-
3472
@max_concurrent_requests = @options.max_concurrent_requests || MAX_REQUESTS
-
3472
@max_requests = @options.max_requests
-
3472
@parser = Parser::HTTP1.new(self)
-
3472
@buffer = buffer
-
3472
@version = [1, 1]
-
3472
@pending = []
-
3472
@requests = []
-
3472
@handshake_completed = false
-
end
-
-
24
def timeout
-
3370
@options.timeout[:operation_timeout]
-
end
-
-
24
def interests
-
# this means we're processing incoming response already
-
24920
return :r if @request
-
-
20653
return if @requests.empty?
-
-
20598
request = @requests.first
-
-
20598
return unless request
-
-
20598
return :w if request.interests == :w || !@buffer.empty?
-
-
17873
:r
-
end
-
-
24
def reset
-
6092
@max_requests = @options.max_requests || MAX_REQUESTS
-
6092
@parser.reset!
-
6092
@handshake_completed = false
-
6092
@pending.concat(@requests) unless @requests.empty?
-
end
-
-
24
def close
-
2926
reset
-
2926
emit(:close, true)
-
end
-
-
24
def exhausted?
-
545
!@max_requests.positive?
-
end
-
-
24
def empty?
-
# this means that for every request there's an available
-
# partial response, so there are no in-flight requests waiting.
-
6021
@requests.empty? || (
-
# checking all responses can be time-consuming. Alas, as in HTTP/1, responses
-
# do not come out of order, we can get away with checking first and last.
-
279
!@requests.first.response.nil? &&
-
116
(@requests.size == 1 || !@requests.last.response.nil?)
-
)
-
end
-
-
24
def <<(data)
-
5746
@parser << data
-
end
-
-
24
def send(request)
-
14542
unless @max_requests.positive?
-
@pending << request
-
return
-
end
-
-
14542
return if @requests.include?(request)
-
-
14542
@requests << request
-
14542
@pipelining = true if @requests.size > 1
-
end
-
-
24
def consume
-
13028
requests_limit = [@max_requests, @requests.size].min
-
13028
concurrent_requests_limit = [@max_concurrent_requests, requests_limit].min
-
13028
@requests.each_with_index do |request, idx|
-
15527
break if idx >= concurrent_requests_limit
-
12974
next if request.state == :done
-
-
5006
handle(request)
-
end
-
end
-
-
# HTTP Parser callbacks
-
#
-
# must be public methods, or else they won't be reachable
-
-
24
def on_start
-
3859
log(level: 2) { "parsing begins" }
-
end
-
-
24
def on_headers(h)
-
3838
@request = @requests.first
-
-
3838
return if @request.response
-
-
3859
log(level: 2) { "headers received" }
-
3838
headers = @request.options.headers_class.new(h)
-
3838
response = @request.options.response_class.new(@request,
-
@parser.status_code,
-
@parser.http_version.join("."),
-
headers)
-
3859
log(color: :yellow) { "-> HEADLINE: #{response.status} HTTP/#{@parser.http_version.join(".")}" }
-
4027
log(color: :yellow) { response.headers.each.map { |f, v| "-> HEADER: #{f}: #{v}" }.join("\n") }
-
-
3838
@request.response = response
-
3831
on_complete if response.finished?
-
end
-
-
24
def on_trailers(h)
-
7
return unless @request
-
-
7
response = @request.response
-
7
log(level: 2) { "trailer headers received" }
-
-
7
log(color: :yellow) { h.each.map { |f, v| "-> HEADER: #{f}: #{v.join(", ")}" }.join("\n") }
-
7
response.merge_headers(h)
-
end
-
-
24
def on_data(chunk)
-
4379
request = @request
-
-
4379
return unless request
-
-
4400
log(color: :green) { "-> DATA: #{chunk.bytesize} bytes..." }
-
4400
log(level: 2, color: :green) { "-> #{chunk.inspect}" }
-
4379
response = request.response
-
-
4379
response << chunk
-
rescue StandardError => e
-
12
error_response = ErrorResponse.new(request, e)
-
12
request.response = error_response
-
12
dispatch
-
end
-
-
24
def on_complete
-
3812
request = @request
-
-
3812
return unless request
-
-
3833
log(level: 2) { "parsing complete" }
-
3812
dispatch
-
end
-
-
24
def dispatch
-
3824
request = @request
-
-
3824
if request.expects?
-
63
@parser.reset!
-
54
return handle(request)
-
end
-
-
3761
@request = nil
-
3761
@requests.shift
-
3761
response = request.response
-
3761
response.finish! unless response.is_a?(ErrorResponse)
-
3761
emit(:response, request, response)
-
-
3711
if @parser.upgrade?
-
28
response << @parser.upgrade_data
-
28
throw(:called)
-
end
-
-
3683
@parser.reset!
-
3265
@max_requests -= 1
-
3683
if response.is_a?(ErrorResponse)
-
12
disable
-
else
-
3671
manage_connection(request, response)
-
end
-
-
545
if exhausted?
-
@pending.concat(@requests)
-
@requests.clear
-
-
emit(:exhausted)
-
else
-
545
send(@pending.shift) unless @pending.empty?
-
end
-
end
-
-
24
def handle_error(ex, request = nil)
-
189
if (ex.is_a?(EOFError) || ex.is_a?(TimeoutError)) && @request && @request.response &&
-
!@request.response.headers.key?("content-length") &&
-
!@request.response.headers.key?("transfer-encoding")
-
# if the response does not contain a content-length header, the server closing the
-
# connnection is the indicator of response consumed.
-
# https://greenbytes.de/tech/webdav/rfc2616.html#rfc.section.4.4
-
14
catch(:called) { on_complete }
-
6
return
-
end
-
-
182
if @pipelining
-
catch(:called) { disable }
-
else
-
182
@requests.each do |req|
-
172
next if request && request == req
-
-
emit(:error, req, ex)
-
end
-
182
@pending.each do |req|
-
next if request && request == req
-
-
emit(:error, req, ex)
-
end
-
end
-
end
-
-
24
def ping
-
reset
-
emit(:reset)
-
emit(:exhausted)
-
end
-
-
24
private
-
-
24
def manage_connection(request, response)
-
3671
connection = response.headers["connection"]
-
3254
case connection
-
when /keep-alive/i
-
545
if @handshake_completed
-
if @max_requests.zero?
-
@pending.concat(@requests)
-
@requests.clear
-
emit(:exhausted)
-
end
-
return
-
end
-
-
545
keep_alive = response.headers["keep-alive"]
-
545
return unless keep_alive
-
-
114
parameters = Hash[keep_alive.split(/ *, */).map do |pair|
-
114
pair.split(/ *= */, 2)
-
end]
-
114
@max_requests = parameters["max"].to_i - 1 if parameters.key?("max")
-
-
114
if parameters.key?("timeout")
-
keep_alive_timeout = parameters["timeout"].to_i
-
emit(:timeout, keep_alive_timeout)
-
end
-
114
@handshake_completed = true
-
when /close/i
-
3126
disable
-
when nil
-
# In HTTP/1.1, it's keep alive by default
-
return if response.version == "1.1" && request.headers["connection"] != "close"
-
-
disable
-
end
-
end
-
-
24
def disable
-
3138
disable_pipelining
-
3138
reset
-
3138
emit(:reset)
-
3131
throw(:called)
-
end
-
-
24
def disable_pipelining
-
3138
return if @requests.empty?
-
# do not disable pipelining if already set to 1 request at a time
-
169
return if @max_concurrent_requests == 1
-
-
18
@requests.each do |r|
-
18
r.transition(:idle)
-
-
# when we disable pipelining, we still want to try keep-alive.
-
# only when keep-alive with one request fails, do we fallback to
-
# connection: close.
-
18
r.headers["connection"] = "close" if @max_concurrent_requests == 1
-
end
-
# server doesn't handle pipelining, and probably
-
# doesn't support keep-alive. Fallback to send only
-
# 1 keep alive request.
-
18
@max_concurrent_requests = 1
-
18
@pipelining = false
-
end
-
-
24
def set_protocol_headers(request)
-
3972
if !request.headers.key?("content-length") &&
-
request.body.bytesize == Float::INFINITY
-
28
request.body.chunk!
-
end
-
-
3972
extra_headers = {}
-
-
3972
unless request.headers.key?("connection")
-
3951
connection_value = if request.persistent?
-
# when in a persistent connection, the request can't be at
-
# the edge of a renegotiation
-
834
if @requests.index(request) + 1 < @max_requests
-
723
"keep-alive"
-
else
-
111
"close"
-
end
-
else
-
# when it's not a persistent connection, it sets "Connection: close" always
-
# on the last request of the possible batch (either allowed max requests,
-
# or if smaller, the size of the batch itself)
-
3117
requests_limit = [@max_requests, @requests.size].min
-
3117
if request == @requests[requests_limit - 1]
-
3077
"close"
-
else
-
40
"keep-alive"
-
end
-
end
-
-
3497
extra_headers["connection"] = connection_value
-
end
-
3972
extra_headers["host"] = request.authority unless request.headers.key?("host")
-
3972
extra_headers
-
end
-
-
24
def handle(request)
-
5069
catch(:buffer_full) do
-
5069
request.transition(:headers)
-
5062
join_headers(request) if request.state == :headers
-
5062
request.transition(:body)
-
5062
join_body(request) if request.state == :body
-
4128
request.transition(:trailers)
-
# HTTP/1.1 trailers should only work for chunked encoding
-
4128
join_trailers(request) if request.body.chunked? && request.state == :trailers
-
4128
request.transition(:done)
-
end
-
end
-
-
24
def join_headline(request)
-
3455
"#{request.verb} #{request.path} HTTP/#{@version.join(".")}"
-
end
-
-
24
def join_headers(request)
-
3972
headline = join_headline(request)
-
3972
@buffer << headline << CRLF
-
3993
log(color: :yellow) { "<- HEADLINE: #{headline.chomp.inspect}" }
-
3972
extra_headers = set_protocol_headers(request)
-
3972
join_headers2(request.headers.each(extra_headers))
-
3993
log { "<- " }
-
3972
@buffer << CRLF
-
end
-
-
24
def join_body(request)
-
4885
return if request.body.empty?
-
-
5429
while (chunk = request.drain_body)
-
2958
log(color: :green) { "<- DATA: #{chunk.bytesize} bytes..." }
-
2958
log(level: 2, color: :green) { "<- #{chunk.inspect}" }
-
2958
@buffer << chunk
-
2958
throw(:buffer_full, request) if @buffer.full?
-
end
-
-
1299
return unless (error = request.drain_error)
-
-
raise error
-
end
-
-
24
def join_trailers(request)
-
84
return unless request.trailers? && request.callbacks_for?(:trailers)
-
-
28
join_headers2(request.trailers)
-
28
log { "<- " }
-
28
@buffer << CRLF
-
end
-
-
24
def join_headers2(headers)
-
4000
headers.each do |field, value|
-
24040
buffer = "#{capitalized(field)}: #{value}#{CRLF}"
-
24145
log(color: :yellow) { "<- HEADER: #{buffer.chomp}" }
-
24040
@buffer << buffer
-
end
-
end
-
-
24
UPCASED = {
-
"www-authenticate" => "WWW-Authenticate",
-
"http2-settings" => "HTTP2-Settings",
-
"content-md5" => "Content-MD5",
-
}.freeze
-
-
24
def capitalized(field)
-
24040
UPCASED[field] || field.split("-").map(&:capitalize).join("-")
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "securerandom"
-
24
require "http/2"
-
-
24
module HTTPX
-
24
class Connection::HTTP2
-
24
include Callbacks
-
24
include Loggable
-
-
24
MAX_CONCURRENT_REQUESTS = ::HTTP2::DEFAULT_MAX_CONCURRENT_STREAMS
-
-
24
class Error < Error
-
24
def initialize(id, code)
-
29
super("stream #{id} closed with error: #{code}")
-
end
-
end
-
-
24
class GoawayError < Error
-
24
def initialize
-
13
super(0, :no_error)
-
end
-
end
-
-
24
attr_reader :streams, :pending
-
-
24
def initialize(buffer, options)
-
2565
@options = options
-
2565
@settings = @options.http2_settings
-
2565
@pending = []
-
2565
@streams = {}
-
2565
@drains = {}
-
2565
@pings = []
-
2565
@buffer = buffer
-
2565
@handshake_completed = false
-
2565
@wait_for_handshake = @settings.key?(:wait_for_handshake) ? @settings.delete(:wait_for_handshake) : true
-
2565
@max_concurrent_requests = @options.max_concurrent_requests || MAX_CONCURRENT_REQUESTS
-
2565
@max_requests = @options.max_requests
-
2565
init_connection
-
end
-
-
24
def timeout
-
5062
return @options.timeout[:operation_timeout] if @handshake_completed
-
-
2525
@options.timeout[:settings_timeout]
-
end
-
-
24
def interests
-
# waiting for WINDOW_UPDATE frames
-
50899
return :r if @buffer.full?
-
-
50899
if @connection.state == :closed
-
2384
return unless @handshake_completed
-
-
2043
return :w
-
end
-
-
48515
unless @connection.state == :connected && @handshake_completed
-
9396
return @buffer.empty? ? :r : :rw
-
end
-
-
37775
return :w if !@pending.empty? && can_buffer_more_requests?
-
-
37775
return :w unless @drains.empty?
-
-
37024
if @buffer.empty?
-
37024
return if @streams.empty? && @pings.empty?
-
-
29800
return :r
-
end
-
-
:rw
-
end
-
-
24
def close
-
2392
unless @connection.state == :closed
-
2380
@connection.goaway
-
2380
emit(:timeout, @options.timeout[:close_handshake_timeout])
-
end
-
2392
emit(:close, true)
-
end
-
-
24
def empty?
-
2358
@connection.state == :closed || @streams.empty?
-
end
-
-
24
def exhausted?
-
2566
!@max_requests.positive?
-
end
-
-
24
def <<(data)
-
26393
@connection << data
-
end
-
-
24
def can_buffer_more_requests?
-
6035
(@handshake_completed || !@wait_for_handshake) &&
-
@streams.size < @max_concurrent_requests &&
-
@streams.size < @max_requests
-
end
-
-
24
def send(request)
-
5631
unless can_buffer_more_requests?
-
2732
@pending << request
-
2732
return
-
end
-
2899
unless (stream = @streams[request])
-
2899
stream = @connection.new_stream
-
2899
handle_stream(stream, request)
-
2527
@streams[request] = stream
-
2527
@max_requests -= 1
-
end
-
2899
handle(request, stream)
-
2885
true
-
rescue ::HTTP2::Error::StreamLimitExceeded
-
@pending.unshift(request)
-
end
-
-
24
def consume
-
19580
@streams.each do |request, stream|
-
7453
next if request.state == :done
-
-
858
handle(request, stream)
-
end
-
end
-
-
24
def handle_error(ex, request = nil)
-
233
if ex.instance_of?(TimeoutError) && !@handshake_completed && @connection.state != :closed
-
7
@connection.goaway(:settings_timeout, "closing due to settings timeout")
-
7
emit(:close_handshake)
-
7
settings_ex = SettingsTimeoutError.new(ex.timeout, ex.message)
-
7
settings_ex.set_backtrace(ex.backtrace)
-
7
ex = settings_ex
-
end
-
233
@streams.each_key do |req|
-
187
next if request && request == req
-
-
12
emit(:error, req, ex)
-
end
-
233
@pending.each do |req|
-
29
next if request && request == req
-
-
29
emit(:error, req, ex)
-
end
-
end
-
-
24
def ping
-
7
ping = SecureRandom.gen_random(8)
-
7
@connection.ping(ping)
-
ensure
-
7
@pings << ping
-
end
-
-
24
private
-
-
24
def send_pending
-
6649
while (request = @pending.shift)
-
# TODO: this request should go back to top of stack
-
2628
break unless send(request)
-
end
-
end
-
-
24
def handle(request, stream)
-
3813
catch(:buffer_full) do
-
3813
request.transition(:headers)
-
3806
join_headers(stream, request) if request.state == :headers
-
3806
request.transition(:body)
-
3806
join_body(stream, request) if request.state == :body
-
3048
request.transition(:trailers)
-
3048
join_trailers(stream, request) if request.state == :trailers && !request.body.empty?
-
3048
request.transition(:done)
-
end
-
end
-
-
24
def init_connection
-
2565
@connection = ::HTTP2::Client.new(@settings)
-
2565
@connection.on(:frame, &method(:on_frame))
-
2565
@connection.on(:frame_sent, &method(:on_frame_sent))
-
2565
@connection.on(:frame_received, &method(:on_frame_received))
-
2565
@connection.on(:origin, &method(:on_origin))
-
2565
@connection.on(:promise, &method(:on_promise))
-
2565
@connection.on(:altsvc) { |frame| on_altsvc(frame[:origin], frame) }
-
2565
@connection.on(:settings_ack, &method(:on_settings))
-
2565
@connection.on(:ack, &method(:on_pong))
-
2565
@connection.on(:goaway, &method(:on_close))
-
#
-
# Some servers initiate HTTP/2 negotiation right away, some don't.
-
# As such, we have to check the socket buffer. If there is something
-
# to read, the server initiated the negotiation. If not, we have to
-
# initiate it.
-
#
-
2565
@connection.send_connection_preface
-
end
-
-
24
alias_method :reset, :init_connection
-
24
public :reset
-
-
24
def handle_stream(stream, request)
-
2913
request.on(:refuse, &method(:on_stream_refuse).curry(3)[stream, request])
-
2913
stream.on(:close, &method(:on_stream_close).curry(3)[stream, request])
-
2913
stream.on(:half_close) do
-
2894
log(level: 2) { "#{stream.id}: waiting for response..." }
-
end
-
2913
stream.on(:altsvc, &method(:on_altsvc).curry(2)[request.origin])
-
2913
stream.on(:headers, &method(:on_stream_headers).curry(3)[stream, request])
-
2913
stream.on(:data, &method(:on_stream_data).curry(3)[stream, request])
-
end
-
-
24
def set_protocol_headers(request)
-
371
{
-
2520
":scheme" => request.scheme,
-
":method" => request.verb,
-
":path" => request.path,
-
":authority" => request.authority,
-
}
-
end
-
-
24
def join_headers(stream, request)
-
2892
extra_headers = set_protocol_headers(request)
-
-
2892
if request.headers.key?("host")
-
7
log { "forbidden \"host\" header found (#{request.headers["host"]}), will use it as authority..." }
-
6
extra_headers[":authority"] = request.headers["host"]
-
end
-
-
2892
log(level: 1, color: :yellow) do
-
110
request.headers.merge(extra_headers).each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{v}" }.join("\n")
-
end
-
2892
stream.headers(request.headers.each(extra_headers), end_stream: request.body.empty?)
-
end
-
-
24
def join_trailers(stream, request)
-
1187
unless request.trailers?
-
1180
stream.data("", end_stream: true) if request.callbacks_for?(:trailers)
-
1036
return
-
end
-
-
7
log(level: 1, color: :yellow) do
-
13
request.trailers.each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{v}" }.join("\n")
-
end
-
7
stream.headers(request.trailers.each, end_stream: true)
-
end
-
-
24
def join_body(stream, request)
-
3650
return if request.body.empty?
-
-
1945
chunk = @drains.delete(request) || request.drain_body
-
2120
while chunk
-
2283
next_chunk = request.drain_body
-
2301
log(level: 1, color: :green) { "#{stream.id}: -> DATA: #{chunk.bytesize} bytes..." }
-
2301
log(level: 2, color: :green) { "#{stream.id}: -> #{chunk.inspect}" }
-
2283
stream.data(chunk, end_stream: !(next_chunk || request.trailers? || request.callbacks_for?(:trailers)))
-
2283
if next_chunk && (@buffer.full? || request.body.unbounded_body?)
-
654
@drains[request] = next_chunk
-
758
throw(:buffer_full)
-
end
-
1525
chunk = next_chunk
-
end
-
-
1187
return unless (error = request.drain_error)
-
-
10
on_stream_refuse(stream, request, error)
-
end
-
-
######
-
# HTTP/2 Callbacks
-
######
-
-
24
def on_stream_headers(stream, request, h)
-
2871
response = request.response
-
-
2871
if response.is_a?(Response) && response.version == "2.0"
-
95
on_stream_trailers(stream, response, h)
-
95
return
-
end
-
-
2776
log(color: :yellow) do
-
110
h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{v}" }.join("\n")
-
end
-
2776
_, status = h.shift
-
2776
headers = request.options.headers_class.new(h)
-
2776
response = request.options.response_class.new(request, status, "2.0", headers)
-
2776
request.response = response
-
2414
@streams[request] = stream
-
-
2769
handle(request, stream) if request.expects?
-
end
-
-
24
def on_stream_trailers(stream, response, h)
-
95
log(color: :yellow) do
-
h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{v}" }.join("\n")
-
end
-
95
response.merge_headers(h)
-
end
-
-
24
def on_stream_data(stream, request, data)
-
5206
log(level: 1, color: :green) { "#{stream.id}: <- DATA: #{data.bytesize} bytes..." }
-
5206
log(level: 2, color: :green) { "#{stream.id}: <- #{data.inspect}" }
-
5186
request.response << data
-
end
-
-
24
def on_stream_refuse(stream, request, error)
-
10
on_stream_close(stream, request, error)
-
10
stream.close
-
end
-
-
24
def on_stream_close(stream, request, error)
-
2702
return if error == :stream_closed && !@streams.key?(request)
-
-
2704
log(level: 2) { "#{stream.id}: closing stream" }
-
2692
@drains.delete(request)
-
2692
@streams.delete(request)
-
-
2692
if error
-
10
ex = Error.new(stream.id, error)
-
10
ex.set_backtrace(caller)
-
10
response = ErrorResponse.new(request, ex)
-
10
request.response = response
-
10
emit(:response, request, response)
-
else
-
2682
response = request.response
-
2682
if response && response.is_a?(Response) && response.status == 421
-
7
ex = MisdirectedRequestError.new(response)
-
7
ex.set_backtrace(caller)
-
7
emit(:error, request, ex)
-
else
-
2675
emit(:response, request, response)
-
end
-
end
-
2685
send(@pending.shift) unless @pending.empty?
-
2685
return unless @streams.empty? && exhausted?
-
-
7
close
-
7
emit(:exhausted) unless @pending.empty?
-
end
-
-
24
def on_frame(bytes)
-
16221
@buffer << bytes
-
end
-
-
24
def on_settings(*)
-
2537
@handshake_completed = true
-
2537
emit(:current_timeout)
-
2537
@max_concurrent_requests = [@max_concurrent_requests, @connection.remote_settings[:settings_max_concurrent_streams]].min
-
2537
send_pending
-
end
-
-
24
def on_close(_last_frame, error, _payload)
-
19
is_connection_closed = @connection.state == :closed
-
19
if error
-
19
@buffer.clear if is_connection_closed
-
19
if error == :no_error
-
13
ex = GoawayError.new
-
13
@pending.unshift(*@streams.keys)
-
13
@drains.clear
-
13
@streams.clear
-
else
-
6
ex = Error.new(0, error)
-
end
-
19
ex.set_backtrace(caller)
-
19
handle_error(ex)
-
end
-
19
return unless is_connection_closed && @streams.empty?
-
-
19
emit(:close, is_connection_closed)
-
end
-
-
24
def on_frame_sent(frame)
-
13719
log(level: 2) { "#{frame[:stream]}: frame was sent!" }
-
13647
log(level: 2, color: :blue) do
-
84
payload = frame
-
84
payload = payload.merge(payload: frame[:payload].bytesize) if frame[:type] == :data
-
72
"#{frame[:stream]}: #{payload}"
-
end
-
end
-
-
24
def on_frame_received(frame)
-
14317
log(level: 2) { "#{frame[:stream]}: frame was received!" }
-
14261
log(level: 2, color: :magenta) do
-
65
payload = frame
-
65
payload = payload.merge(payload: frame[:payload].bytesize) if frame[:type] == :data
-
56
"#{frame[:stream]}: #{payload}"
-
end
-
end
-
-
24
def on_altsvc(origin, frame)
-
log(level: 2) { "#{frame[:stream]}: altsvc frame was received" }
-
log(level: 2) { "#{frame[:stream]}: #{frame.inspect}" }
-
alt_origin = URI.parse("#{frame[:proto]}://#{frame[:host]}:#{frame[:port]}")
-
params = { "ma" => frame[:max_age] }
-
emit(:altsvc, origin, alt_origin, origin, params)
-
end
-
-
24
def on_promise(stream)
-
21
emit(:promise, @streams.key(stream.parent), stream)
-
end
-
-
24
def on_origin(origin)
-
emit(:origin, origin)
-
end
-
-
24
def on_pong(ping)
-
7
if @pings.delete(ping.to_s)
-
7
emit(:pong)
-
else
-
close(:protocol_error, "ping payload did not match")
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
#
-
# domain_name.rb - Domain Name manipulation library for Ruby
-
#
-
# Copyright (C) 2011-2017 Akinori MUSHA, All rights reserved.
-
#
-
# Redistribution and use in source and binary forms, with or without
-
# modification, are permitted provided that the following conditions
-
# are met:
-
# 1. Redistributions of source code must retain the above copyright
-
# notice, this list of conditions and the following disclaimer.
-
# 2. Redistributions in binary form must reproduce the above copyright
-
# notice, this list of conditions and the following disclaimer in the
-
# documentation and/or other materials provided with the distribution.
-
#
-
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
-
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
-
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-
# SUCH DAMAGE.
-
-
24
require "ipaddr"
-
-
24
module HTTPX
-
# Represents a domain name ready for extracting its registered domain
-
# and TLD.
-
24
class DomainName
-
24
include Comparable
-
-
# The full host name normalized, ASCII-ized and downcased using the
-
# Unicode NFC rules and the Punycode algorithm. If initialized with
-
# an IP address, the string representation of the IP address
-
# suitable for opening a connection to.
-
24
attr_reader :hostname
-
-
# The Unicode representation of the #hostname property.
-
#
-
# :attr_reader: hostname_idn
-
-
# The least "universally original" domain part of this domain name.
-
# For example, "example.co.uk" for "www.sub.example.co.uk". This
-
# may be nil if the hostname does not have one, like when it is an
-
# IP address, an effective TLD or higher itself, or of a
-
# non-canonical domain.
-
24
attr_reader :domain
-
-
24
class << self
-
24
def new(domain)
-
749
return domain if domain.is_a?(self)
-
-
693
super(domain)
-
end
-
-
# Normalizes a _domain_ using the Punycode algorithm as necessary.
-
# The result will be a downcased, ASCII-only string.
-
24
def normalize(domain)
-
665
unless domain.ascii_only?
-
domain = domain.chomp(".").unicode_normalize(:nfc)
-
domain = Punycode.encode_hostname(domain)
-
end
-
-
665
domain.downcase
-
end
-
end
-
-
# Parses _hostname_ into a DomainName object. An IP address is also
-
# accepted. An IPv6 address may be enclosed in square brackets.
-
24
def initialize(hostname)
-
693
hostname = String(hostname)
-
-
693
raise ArgumentError, "domain name must not start with a dot: #{hostname}" if hostname.start_with?(".")
-
-
98
begin
-
693
@ipaddr = IPAddr.new(hostname)
-
28
@hostname = @ipaddr.to_s
-
28
return
-
rescue IPAddr::Error
-
665
nil
-
end
-
-
665
@hostname = DomainName.normalize(hostname)
-
665
tld = if (last_dot = @hostname.rindex("."))
-
161
@hostname[(last_dot + 1)..-1]
-
else
-
504
@hostname
-
end
-
-
# unknown/local TLD
-
665
@domain = if last_dot
-
# fallback - accept cookies down to second level
-
# cf. http://www.dkim-reputation.org/regdom-libs/
-
161
if (penultimate_dot = @hostname.rindex(".", last_dot - 1))
-
42
@hostname[(penultimate_dot + 1)..-1]
-
else
-
119
@hostname
-
end
-
else
-
# no domain part - must be a local hostname
-
504
tld
-
end
-
end
-
-
# Checks if the server represented by this domain is qualified to
-
# send and receive cookies with a domain attribute value of
-
# _domain_. A true value given as the second argument represents
-
# cookies without a domain attribute value, in which case only
-
# hostname equality is checked.
-
24
def cookie_domain?(domain, host_only = false)
-
# RFC 6265 #5.3
-
# When the user agent "receives a cookie":
-
28
return self == @domain if host_only
-
-
28
domain = DomainName.new(domain)
-
-
# RFC 6265 #5.1.3
-
# Do not perform subdomain matching against IP addresses.
-
28
@hostname == domain.hostname if @ipaddr
-
-
# RFC 6265 #4.1.1
-
# Domain-value must be a subdomain.
-
28
@domain && self <= domain && domain <= @domain
-
end
-
-
24
def <=>(other)
-
42
other = DomainName.new(other)
-
42
othername = other.hostname
-
42
if othername == @hostname
-
14
0
-
27
elsif @hostname.end_with?(othername) && @hostname[-othername.size - 1, 1] == "."
-
# The other is higher
-
14
-1
-
else
-
# The other is lower
-
14
1
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
# the default exception class for exceptions raised by HTTPX.
-
24
class Error < StandardError; end
-
-
24
class UnsupportedSchemeError < Error; end
-
-
24
class ConnectionError < Error; end
-
-
# Error raised when there was a timeout. Its subclasses allow for finer-grained
-
# control of which timeout happened.
-
24
class TimeoutError < Error
-
# The timeout value which caused this error to be raised.
-
24
attr_reader :timeout
-
-
# initializes the timeout exception with the +timeout+ causing the error, and the
-
# error +message+ for it.
-
24
def initialize(timeout, message)
-
440
@timeout = timeout
-
440
super(message)
-
end
-
-
# clones this error into a HTTPX::ConnectionTimeoutError.
-
24
def to_connection_error
-
21
ex = ConnectTimeoutError.new(@timeout, message)
-
21
ex.set_backtrace(backtrace)
-
21
ex
-
end
-
end
-
-
# Error raised when there was a timeout establishing the connection to a server.
-
# This may be raised due to timeouts during TCP and TLS (when applicable) connection
-
# establishment.
-
24
class ConnectTimeoutError < TimeoutError; end
-
-
# Error raised when there was a timeout while sending a request, or receiving a response
-
# from the server.
-
24
class RequestTimeoutError < TimeoutError
-
# The HTTPX::Request request object this exception refers to.
-
24
attr_reader :request
-
-
# initializes the exception with the +request+ and +response+ it refers to, and the
-
# +timeout+ causing the error, and the
-
24
def initialize(request, response, timeout)
-
358
@request = request
-
358
@response = response
-
358
super(timeout, "Timed out after #{timeout} seconds")
-
end
-
-
24
def marshal_dump
-
[message]
-
end
-
end
-
-
# Error raised when there was a timeout while receiving a response from the server.
-
24
class ReadTimeoutError < RequestTimeoutError; end
-
-
# Error raised when there was a timeout while sending a request from the server.
-
24
class WriteTimeoutError < RequestTimeoutError; end
-
-
# Error raised when there was a timeout while waiting for the HTTP/2 settings frame from the server.
-
24
class SettingsTimeoutError < TimeoutError; end
-
-
# Error raised when there was a timeout while resolving a domain to an IP.
-
24
class ResolveTimeoutError < TimeoutError; end
-
-
# Error raised when there was an error while resolving a domain to an IP.
-
24
class ResolveError < Error; end
-
-
# Error raised when there was an error while resolving a domain to an IP
-
# using a HTTPX::Resolver::Native resolver.
-
24
class NativeResolveError < ResolveError
-
24
attr_reader :connection, :host
-
-
# initializes the exception with the +connection+ it refers to, the +host+ domain
-
# which failed to resolve, and the error +message+.
-
24
def initialize(connection, host, message = "Can't resolve #{host}")
-
103
@connection = connection
-
103
@host = host
-
103
super(message)
-
end
-
end
-
-
# The exception class for HTTP responses with 4xx or 5xx status.
-
24
class HTTPError < Error
-
# The HTTPX::Response response object this exception refers to.
-
24
attr_reader :response
-
-
# Creates the instance and assigns the HTTPX::Response +response+.
-
24
def initialize(response)
-
83
@response = response
-
83
super("HTTP Error: #{@response.status} #{@response.headers}\n#{@response.body}")
-
end
-
-
# The HTTP response status.
-
#
-
# error.status #=> 404
-
24
def status
-
14
@response.status
-
end
-
end
-
-
# error raised when a request was sent a server which can't reproduce a response, and
-
# has therefore returned an HTTP response using the 421 status code.
-
24
class MisdirectedRequestError < HTTPError; end
-
end
-
# frozen_string_literal: true
-
-
24
require "uri"
-
-
24
module HTTPX
-
24
module ArrayExtensions
-
24
module FilterMap
-
refine Array do
-
# Ruby 2.7 backport
-
def filter_map
-
return to_enum(:filter_map) unless block_given?
-
-
each_with_object([]) do |item, res|
-
processed = yield(item)
-
res << processed if processed
-
end
-
end
-
23
end unless Array.method_defined?(:filter_map)
-
end
-
-
24
module Intersect
-
refine Array do
-
# Ruby 3.1 backport
-
4
def intersect?(arr)
-
if size < arr.size
-
smaller = self
-
else
-
smaller, arr = arr, self
-
end
-
(arr & smaller).size > 0
-
end
-
23
end unless Array.method_defined?(:intersect?)
-
end
-
end
-
-
24
module URIExtensions
-
# uri 0.11 backport, ships with ruby 3.1
-
24
refine URI::Generic do
-
-
24
def non_ascii_hostname
-
365
@non_ascii_hostname
-
end
-
-
24
def non_ascii_hostname=(hostname)
-
28
@non_ascii_hostname = hostname
-
end
-
-
def authority
-
7071
return host if port == default_port
-
-
533
"#{host}:#{port}"
-
23
end unless URI::HTTP.method_defined?(:authority)
-
-
def origin
-
6112
"#{scheme}://#{authority}"
-
23
end unless URI::HTTP.method_defined?(:origin)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
class Headers
-
24
class << self
-
24
def new(headers = nil)
-
20632
return headers if headers.is_a?(self)
-
-
9624
super
-
end
-
end
-
-
24
def initialize(headers = nil)
-
9624
@headers = {}
-
9624
return unless headers
-
-
9467
headers.each do |field, value|
-
49066
array_value(value).each do |v|
-
49115
add(downcased(field), v)
-
end
-
end
-
end
-
-
# cloned initialization
-
24
def initialize_clone(orig)
-
7
super
-
7
@headers = orig.instance_variable_get(:@headers).clone
-
end
-
-
# dupped initialization
-
24
def initialize_dup(orig)
-
11946
super
-
11946
@headers = orig.instance_variable_get(:@headers).dup
-
end
-
-
# freezes the headers hash
-
24
def freeze
-
12960
@headers.freeze
-
12960
super
-
end
-
-
24
def same_headers?(headers)
-
28
@headers.empty? || begin
-
28
headers.each do |k, v|
-
63
next unless key?(k)
-
-
63
return false unless v == self[k]
-
end
-
14
true
-
end
-
end
-
-
# merges headers with another header-quack.
-
# the merge rule is, if the header already exists,
-
# ignore what the +other+ headers has. Otherwise, set
-
#
-
24
def merge(other)
-
3700
headers = dup
-
3700
other.each do |field, value|
-
2856
headers[downcased(field)] = value
-
end
-
3700
headers
-
end
-
-
# returns the comma-separated values of the header field
-
# identified by +field+, or nil otherwise.
-
#
-
24
def [](field)
-
72740
a = @headers[downcased(field)] || return
-
21863
a.join(", ")
-
end
-
-
# sets +value+ (if not nil) as single value for the +field+ header.
-
#
-
24
def []=(field, value)
-
32170
return unless value
-
-
28394
@headers[downcased(field)] = array_value(value)
-
end
-
-
# deletes all values associated with +field+ header.
-
#
-
24
def delete(field)
-
225
canonical = downcased(field)
-
225
@headers.delete(canonical) if @headers.key?(canonical)
-
end
-
-
# adds additional +value+ to the existing, for header +field+.
-
#
-
24
def add(field, value)
-
49493
(@headers[downcased(field)] ||= []) << String(value)
-
end
-
-
# helper to be used when adding an header field as a value to another field
-
#
-
# h2_headers.add_header("vary", "accept-encoding")
-
# h2_headers["vary"] #=> "accept-encoding"
-
# h1_headers.add_header("vary", "accept-encoding")
-
# h1_headers["vary"] #=> "Accept-Encoding"
-
#
-
24
alias_method :add_header, :add
-
-
# returns the enumerable headers store in pairs of header field + the values in
-
# the comma-separated string format
-
#
-
24
def each(extra_headers = nil)
-
51851
return enum_for(__method__, extra_headers) { @headers.size } unless block_given?
-
-
27675
@headers.each do |field, value|
-
35572
yield(field, value.join(", ")) unless value.empty?
-
end
-
-
6046
extra_headers.each do |field, value|
-
19567
yield(field, value) unless value.empty?
-
27660
end if extra_headers
-
end
-
-
24
def ==(other)
-
16080
other == to_hash
-
end
-
-
# the headers store in Hash format
-
24
def to_hash
-
17124
Hash[to_a]
-
end
-
24
alias_method :to_h, :to_hash
-
-
# the headers store in array of pairs format
-
24
def to_a
-
17144
Array(each)
-
end
-
-
# headers as string
-
24
def to_s
-
1608
@headers.to_s
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
to_hash.inspect
-
skipped
end
-
skipped
# :nocov:
-
-
# this is internal API and doesn't abide to other public API
-
# guarantees, like downcasing strings.
-
# Please do not use this outside of core!
-
#
-
24
def key?(downcased_key)
-
50875
@headers.key?(downcased_key)
-
end
-
-
# returns the values for the +field+ header in array format.
-
# This method is more internal, and for this reason doesn't try
-
# to "correct" the user input, i.e. it doesn't downcase the key.
-
#
-
24
def get(field)
-
221
@headers[field] || EMPTY
-
end
-
-
24
private
-
-
24
def array_value(value)
-
71343
case value
-
when Array
-
77827
value.map { |val| String(val).strip }
-
else
-
46323
[String(value).strip]
-
end
-
end
-
-
24
def downcased(field)
-
206942
String(field).downcase
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "socket"
-
24
require "httpx/io/udp"
-
24
require "httpx/io/tcp"
-
24
require "httpx/io/unix"
-
-
begin
-
24
require "httpx/io/ssl"
-
rescue LoadError
-
end
-
# frozen_string_literal: true
-
-
24
require "openssl"
-
-
24
module HTTPX
-
24
TLSError = OpenSSL::SSL::SSLError
-
-
24
class SSL < TCP
-
# rubocop:disable Style/MutableConstant
-
24
TLS_OPTIONS = { alpn_protocols: %w[h2 http/1.1].freeze }
-
# https://github.com/jruby/jruby-openssl/issues/284
-
24
TLS_OPTIONS[:verify_hostname] = true if RUBY_ENGINE == "jruby"
-
# rubocop:enable Style/MutableConstant
-
24
TLS_OPTIONS.freeze
-
-
24
attr_writer :ssl_session
-
-
24
def initialize(_, _, options)
-
2509
super
-
-
2509
ctx_options = TLS_OPTIONS.merge(options.ssl)
-
2509
@sni_hostname = ctx_options.delete(:hostname) || @hostname
-
-
2509
if @keep_open && @io.is_a?(OpenSSL::SSL::SSLSocket)
-
# externally initiated ssl socket
-
19
@ctx = @io.context
-
19
@state = :negotiated
-
else
-
2490
@ctx = OpenSSL::SSL::SSLContext.new
-
2490
@ctx.set_params(ctx_options) unless ctx_options.empty?
-
2490
unless @ctx.session_cache_mode.nil? # a dummy method on JRuby
-
2170
@ctx.session_cache_mode =
-
OpenSSL::SSL::SSLContext::SESSION_CACHE_CLIENT | OpenSSL::SSL::SSLContext::SESSION_CACHE_NO_INTERNAL_STORE
-
end
-
-
2490
yield(self) if block_given?
-
end
-
-
2509
@verify_hostname = @ctx.verify_hostname
-
end
-
-
24
if OpenSSL::SSL::SSLContext.method_defined?(:session_new_cb=)
-
23
def session_new_cb(&pr)
-
6149
@ctx.session_new_cb = proc { |_, sess| pr.call(sess) }
-
end
-
else
-
# session_new_cb not implemented under JRuby
-
1
def session_new_cb; end
-
end
-
-
24
def protocol
-
2255
@io.alpn_protocol || super
-
rescue StandardError
-
6
super
-
end
-
-
24
if RUBY_ENGINE == "jruby"
-
# in jruby, alpn_protocol may return ""
-
# https://github.com/jruby/jruby-openssl/issues/287
-
1
def protocol
-
332
proto = @io.alpn_protocol
-
-
331
return super if proto.nil? || proto.empty?
-
-
330
proto
-
rescue StandardError
-
1
super
-
end
-
end
-
-
24
def can_verify_peer?
-
11
@ctx.verify_mode == OpenSSL::SSL::VERIFY_PEER
-
end
-
-
24
def verify_hostname(host)
-
13
return false if @ctx.verify_mode == OpenSSL::SSL::VERIFY_NONE
-
13
return false if !@io.respond_to?(:peer_cert) || @io.peer_cert.nil?
-
-
13
OpenSSL::SSL.verify_certificate_identity(@io.peer_cert, host)
-
end
-
-
24
def connected?
-
9502
@state == :negotiated
-
end
-
-
24
def expired?
-
super || ssl_session_expired?
-
end
-
-
24
def ssl_session_expired?
-
2552
@ssl_session.nil? || Process.clock_gettime(Process::CLOCK_REALTIME) >= (@ssl_session.time.to_f + @ssl_session.timeout)
-
end
-
-
24
def connect
-
9545
super
-
9523
return if @state == :negotiated ||
-
@state != :connected
-
-
6670
unless @io.is_a?(OpenSSL::SSL::SSLSocket)
-
2552
if (hostname_is_ip = (@ip == @sni_hostname))
-
# IPv6 address would be "[::1]", must turn to "0000:0000:0000:0000:0000:0000:0000:0001" for cert SAN check
-
28
@sni_hostname = @ip.to_string
-
# IP addresses in SNI is not valid per RFC 6066, section 3.
-
28
@ctx.verify_hostname = false
-
end
-
-
2552
@io = OpenSSL::SSL::SSLSocket.new(@io, @ctx)
-
-
2552
@io.hostname = @sni_hostname unless hostname_is_ip
-
2552
@io.session = @ssl_session unless ssl_session_expired?
-
2552
@io.sync_close = true
-
end
-
6670
try_ssl_connect
-
end
-
-
24
def try_ssl_connect
-
6670
ret = @io.connect_nonblock(exception: false)
-
6681
log(level: 3, color: :cyan) { "TLS CONNECT: #{ret}..." }
-
5957
case ret
-
when :wait_readable
-
4139
@interests = :r
-
4139
return
-
when :wait_writable
-
@interests = :w
-
return
-
end
-
2511
@io.post_connection_check(@sni_hostname) if @ctx.verify_mode != OpenSSL::SSL::VERIFY_NONE && @verify_hostname
-
2510
transition(:negotiated)
-
2510
@interests = :w
-
end
-
-
24
private
-
-
24
def transition(nextstate)
-
8644
case nextstate
-
when :negotiated
-
2510
return unless @state == :connected
-
-
when :closed
-
2478
return unless @state == :negotiated ||
-
@state == :connected
-
end
-
9958
do_transition(nextstate)
-
end
-
-
24
def log_transition_state(nextstate)
-
61
return super unless nextstate == :negotiated
-
-
14
server_cert = @io.peer_cert
-
-
12
"#{super}\n\n" \
-
2
"SSL connection using #{@io.ssl_version} / #{Array(@io.cipher).first}\n" \
-
2
"ALPN, server accepted to use #{protocol}\n" \
-
"Server certificate:\n " \
-
2
"subject: #{server_cert.subject}\n " \
-
2
"start date: #{server_cert.not_before}\n " \
-
2
"expire date: #{server_cert.not_after}\n " \
-
2
"issuer: #{server_cert.issuer}\n " \
-
"SSL certificate verify ok."
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "resolv"
-
24
require "ipaddr"
-
-
24
module HTTPX
-
24
class TCP
-
24
include Loggable
-
-
24
using URIExtensions
-
-
24
attr_reader :ip, :port, :addresses, :state, :interests
-
-
24
alias_method :host, :ip
-
-
24
def initialize(origin, addresses, options)
-
5685
@state = :idle
-
5685
@addresses = []
-
5685
@hostname = origin.host
-
5685
@options = options
-
5685
@fallback_protocol = @options.fallback_protocol
-
5685
@port = origin.port
-
5685
@interests = :w
-
5685
if @options.io
-
45
@io = case @options.io
-
when Hash
-
14
@options.io[origin.authority]
-
else
-
31
@options.io
-
end
-
45
raise Error, "Given IO objects do not match the request authority" unless @io
-
-
45
_, _, _, @ip = @io.addr
-
45
@addresses << @ip
-
45
@keep_open = true
-
45
@state = :connected
-
else
-
5640
add_addresses(addresses)
-
end
-
5685
@ip_index = @addresses.size - 1
-
end
-
-
24
def socket
-
171
@io
-
end
-
-
24
def add_addresses(addrs)
-
5819
return if addrs.empty?
-
-
18725
addrs = addrs.map { |addr| addr.is_a?(IPAddr) ? addr : IPAddr.new(addr) }
-
-
5819
ip_index = @ip_index || (@addresses.size - 1)
-
5819
if addrs.first.ipv6?
-
# should be the next in line
-
189
@addresses = [*@addresses[0, ip_index], *addrs, *@addresses[ip_index..-1]]
-
else
-
5630
@addresses.unshift(*addrs)
-
5630
@ip_index += addrs.size if @ip_index
-
end
-
end
-
-
24
def to_io
-
19201
@io.to_io
-
end
-
-
24
def protocol
-
3492
@fallback_protocol
-
end
-
-
24
def connect
-
19814
return unless closed?
-
-
15507
if !@io || @io.closed?
-
6124
transition(:idle)
-
6124
@io = build_socket
-
end
-
15507
try_connect
-
rescue Errno::ECONNREFUSED,
-
Errno::EADDRNOTAVAIL,
-
Errno::EHOSTUNREACH,
-
SocketError,
-
IOError => e
-
430
raise e if @ip_index <= 0
-
-
382
log { "failed connecting to #{@ip} (#{e.message}), trying next..." }
-
364
@ip_index -= 1
-
372
@io = build_socket
-
372
retry
-
rescue Errno::ETIMEDOUT => e
-
raise ConnectTimeoutError.new(@options.timeout[:connect_timeout], e.message) if @ip_index <= 0
-
-
log { "failed connecting to #{@ip} (#{e.message}), trying next..." }
-
@ip_index -= 1
-
@io = build_socket
-
retry
-
end
-
-
24
def try_connect
-
15507
ret = @io.connect_nonblock(Socket.sockaddr_in(@port, @ip.to_s), exception: false)
-
12642
log(level: 3, color: :cyan) { "TCP CONNECT: #{ret}..." }
-
10958
case ret
-
when :wait_readable
-
@interests = :r
-
return
-
when :wait_writable
-
6486
@interests = :w
-
6486
return
-
end
-
6066
transition(:connected)
-
6066
@interests = :w
-
rescue Errno::EALREADY
-
2525
@interests = :w
-
end
-
24
private :try_connect
-
-
24
def read(size, buffer)
-
40433
ret = @io.read_nonblock(size, buffer, exception: false)
-
40433
if ret == :wait_readable
-
7990
buffer.clear
-
7261
return 0
-
end
-
32443
return if ret.nil?
-
-
32505
log { "READ: #{buffer.bytesize} bytes..." }
-
32430
buffer.bytesize
-
end
-
-
24
def write(buffer)
-
17085
siz = @io.write_nonblock(buffer, exception: false)
-
17061
return 0 if siz == :wait_writable
-
17040
return if siz.nil?
-
-
17116
log { "WRITE: #{siz} bytes..." }
-
-
17040
buffer.shift!(siz)
-
17040
siz
-
end
-
-
24
def close
-
6691
return if @keep_open || closed?
-
-
777
begin
-
5958
@io.close
-
ensure
-
5958
transition(:closed)
-
end
-
end
-
-
24
def connected?
-
9873
@state == :connected
-
end
-
-
24
def closed?
-
26466
@state == :idle || @state == :closed
-
end
-
-
24
def expired?
-
# do not mess with external sockets
-
return false if @options.io
-
-
return true unless @addresses
-
-
resolver_addresses = Resolver.nolookup_resolve(@hostname)
-
-
(Array(resolver_addresses) & @addresses).empty?
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}: #{@ip}:#{@port} (state: #{@state})>"
-
skipped
end
-
skipped
# :nocov:
-
-
24
private
-
-
24
def build_socket
-
6496
@ip = @addresses[@ip_index]
-
6496
Socket.new(@ip.family, :STREAM, 0)
-
end
-
-
24
def transition(nextstate)
-
9327
case nextstate
-
# when :idle
-
when :connected
-
3604
return unless @state == :idle
-
when :closed
-
3480
return unless @state == :connected
-
end
-
10718
do_transition(nextstate)
-
end
-
-
24
def do_transition(nextstate)
-
20805
log(level: 1) { log_transition_state(nextstate) }
-
20676
@state = nextstate
-
end
-
-
24
def log_transition_state(nextstate)
-
112
case nextstate
-
when :connected
-
35
"Connected to #{host} (##{@io.fileno})"
-
else
-
82
"#{host} #{@state} -> #{nextstate}"
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "ipaddr"
-
-
24
module HTTPX
-
24
class UDP
-
24
include Loggable
-
-
24
def initialize(ip, port, options)
-
460
@host = ip
-
460
@port = port
-
460
@io = UDPSocket.new(IPAddr.new(ip).family)
-
460
@options = options
-
end
-
-
24
def to_io
-
1025
@io.to_io
-
end
-
-
24
def connect; end
-
-
24
def connected?
-
460
true
-
end
-
-
24
def close
-
624
@io.close
-
end
-
-
24
if RUBY_ENGINE == "jruby"
-
# In JRuby, sendmsg_nonblock is not implemented
-
1
def write(buffer)
-
52
siz = @io.send(buffer.to_s, 0, @host, @port)
-
52
log { "WRITE: #{siz} bytes..." }
-
52
buffer.shift!(siz)
-
52
siz
-
end
-
else
-
23
def write(buffer)
-
541
siz = @io.sendmsg_nonblock(buffer.to_s, 0, Socket.sockaddr_in(@port, @host.to_s), exception: false)
-
541
return 0 if siz == :wait_writable
-
541
return if siz.nil?
-
-
541
log { "WRITE: #{siz} bytes..." }
-
-
541
buffer.shift!(siz)
-
541
siz
-
end
-
end
-
-
24
def read(size, buffer)
-
809
ret = @io.recvfrom_nonblock(size, 0, buffer, exception: false)
-
809
return 0 if ret == :wait_readable
-
548
return if ret.nil?
-
-
548
log { "READ: #{buffer.bytesize} bytes..." }
-
-
548
buffer.bytesize
-
rescue IOError
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
class UNIX < TCP
-
24
using URIExtensions
-
-
24
attr_reader :path
-
-
24
alias_method :host, :path
-
-
24
def initialize(origin, path, options)
-
24
@addresses = []
-
24
@hostname = origin.host
-
24
@state = :idle
-
24
@options = options
-
24
@fallback_protocol = @options.fallback_protocol
-
24
if @options.io
-
12
@io = case @options.io
-
when Hash
-
6
@options.io[origin.authority]
-
else
-
6
@options.io
-
end
-
12
raise Error, "Given IO objects do not match the request authority" unless @io
-
-
12
@path = @io.path
-
12
@keep_open = true
-
12
@state = :connected
-
12
elsif path
-
12
@path = path
-
else
-
raise Error, "No path given where to store the socket"
-
end
-
24
@io ||= build_socket
-
end
-
-
24
def connect
-
18
return unless closed?
-
-
begin
-
18
if @io.closed?
-
6
transition(:idle)
-
6
@io = build_socket
-
end
-
18
@io.connect_nonblock(Socket.sockaddr_un(@path))
-
rescue Errno::EISCONN
-
end
-
12
transition(:connected)
-
rescue Errno::EINPROGRESS,
-
Errno::EALREADY,
-
::IO::WaitReadable
-
end
-
-
24
def expired?
-
false
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}(path: #{@path}): (state: #{@state})>"
-
skipped
end
-
skipped
# :nocov:
-
-
24
private
-
-
24
def build_socket
-
18
Socket.new(Socket::PF_UNIX, :STREAM, 0)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
module Loggable
-
24
COLORS = {
-
black: 30,
-
red: 31,
-
green: 32,
-
yellow: 33,
-
blue: 34,
-
magenta: 35,
-
cyan: 36,
-
white: 37,
-
}.freeze
-
-
24
def log(level: @options.debug_level, color: nil, &msg)
-
316054
return unless @options.debug
-
1424
return unless @options.debug_level >= level
-
-
1424
debug_stream = @options.debug
-
-
1424
message = (+"" << msg.call << "\n")
-
1424
message = "\e[#{COLORS[color]}m#{message}\e[0m" if color && debug_stream.respond_to?(:isatty) && debug_stream.isatty
-
1424
debug_stream << message
-
end
-
-
24
def log_exception(ex, level: @options.debug_level, color: nil)
-
936
return unless @options.debug
-
10
return unless @options.debug_level >= level
-
-
20
log(level: level, color: color) { ex.full_message }
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "socket"
-
-
24
module HTTPX
-
# Contains a set of options which are passed and shared across from session to its requests or
-
# responses.
-
24
class Options
-
24
BUFFER_SIZE = 1 << 14
-
24
WINDOW_SIZE = 1 << 14 # 16K
-
24
MAX_BODY_THRESHOLD_SIZE = (1 << 10) * 112 # 112K
-
24
KEEP_ALIVE_TIMEOUT = 20
-
24
SETTINGS_TIMEOUT = 10
-
24
CLOSE_HANDSHAKE_TIMEOUT = 10
-
24
CONNECT_TIMEOUT = READ_TIMEOUT = WRITE_TIMEOUT = 60
-
24
REQUEST_TIMEOUT = OPERATION_TIMEOUT = nil
-
-
# https://github.com/ruby/resolv/blob/095f1c003f6073730500f02acbdbc55f83d70987/lib/resolv.rb#L408
-
2
ip_address_families = begin
-
24
list = Socket.ip_address_list
-
98
if list.any? { |a| a.ipv6? && !a.ipv6_loopback? && !a.ipv6_linklocal? && !a.ipv6_unique_local? }
-
[Socket::AF_INET6, Socket::AF_INET]
-
else
-
24
[Socket::AF_INET]
-
end
-
rescue NotImplementedError
-
[Socket::AF_INET]
-
end
-
-
2
DEFAULT_OPTIONS = {
-
22
:max_requests => Float::INFINITY,
-
23
:debug => ENV.key?("HTTPX_DEBUG") ? $stderr : nil,
-
24
:debug_level => (ENV["HTTPX_DEBUG"] || 1).to_i,
-
:ssl => {},
-
:http2_settings => { settings_enable_push: 0 },
-
:fallback_protocol => "http/1.1",
-
:supported_compression_formats => %w[gzip deflate],
-
:decompress_response_body => true,
-
:compress_request_body => true,
-
:timeout => {
-
connect_timeout: CONNECT_TIMEOUT,
-
settings_timeout: SETTINGS_TIMEOUT,
-
close_handshake_timeout: CLOSE_HANDSHAKE_TIMEOUT,
-
operation_timeout: OPERATION_TIMEOUT,
-
keep_alive_timeout: KEEP_ALIVE_TIMEOUT,
-
read_timeout: READ_TIMEOUT,
-
write_timeout: WRITE_TIMEOUT,
-
request_timeout: REQUEST_TIMEOUT,
-
},
-
:headers_class => Class.new(Headers),
-
:headers => {},
-
:window_size => WINDOW_SIZE,
-
:buffer_size => BUFFER_SIZE,
-
:body_threshold_size => MAX_BODY_THRESHOLD_SIZE,
-
:request_class => Class.new(Request),
-
:response_class => Class.new(Response),
-
:request_body_class => Class.new(Request::Body),
-
:response_body_class => Class.new(Response::Body),
-
:connection_class => Class.new(Connection),
-
:options_class => Class.new(self),
-
:transport => nil,
-
:addresses => nil,
-
:persistent => false,
-
24
:resolver_class => (ENV["HTTPX_RESOLVER"] || :native).to_sym,
-
:resolver_options => { cache: true },
-
:ip_families => ip_address_families,
-
}.freeze
-
-
24
class << self
-
24
def new(options = {})
-
# let enhanced options go through
-
9556
return options if self == Options && options.class < self
-
7368
return options if options.is_a?(self)
-
-
3599
super
-
end
-
-
24
def method_added(meth)
-
15422
super
-
-
15422
return unless meth =~ /^option_(.+)$/
-
-
7165
optname = Regexp.last_match(1).to_sym
-
-
7165
attr_reader(optname)
-
end
-
end
-
-
# creates a new options instance from a given hash, which optionally define the following:
-
#
-
# :debug :: an object which log messages are written to (must respond to <tt><<</tt>)
-
# :debug_level :: the log level of messages (can be 1, 2, or 3).
-
# :ssl :: a hash of options which can be set as params of OpenSSL::SSL::SSLContext (see HTTPX::IO::SSL)
-
# :http2_settings :: a hash of options to be passed to a HTTP2::Connection (ex: <tt>{ max_concurrent_streams: 2 }</tt>)
-
# :fallback_protocol :: version of HTTP protocol to use by default in the absence of protocol negotiation
-
# like ALPN (defaults to <tt>"http/1.1"</tt>)
-
# :supported_compression_formats :: list of compressions supported by the transcoder layer (defaults to <tt>%w[gzip deflate]</tt>).
-
# :decompress_response_body :: whether to auto-decompress response body (defaults to <tt>true</tt>).
-
# :compress_request_body :: whether to auto-decompress response body (defaults to <tt>true</tt>)
-
# :timeout :: hash of timeout configurations (supports <tt>:connect_timeout</tt>, <tt>:settings_timeout</tt>,
-
# <tt>:operation_timeout</tt>, <tt>:keep_alive_timeout</tt>, <tt>:read_timeout</tt>, <tt>:write_timeout</tt>
-
# and <tt>:request_timeout</tt>
-
# :headers :: hash of HTTP headers (ex: <tt>{ "x-custom-foo" => "bar" }</tt>)
-
# :window_size :: number of bytes to read from a socket
-
# :buffer_size :: internal read and write buffer size in bytes
-
# :body_threshold_size :: maximum size in bytes of response payload that is buffered in memory.
-
# :request_class :: class used to instantiate a request
-
# :response_class :: class used to instantiate a response
-
# :headers_class :: class used to instantiate headers
-
# :request_body_class :: class used to instantiate a request body
-
# :response_body_class :: class used to instantiate a response body
-
# :connection_class :: class used to instantiate connections
-
# :options_class :: class used to instantiate options
-
# :transport :: type of transport to use (set to "unix" for UNIX sockets)
-
# :addresses :: bucket of peer addresses (can be a list of IP addresses, a hash of domain to list of adddresses;
-
# paths should be used for UNIX sockets instead)
-
# :io :: open socket, or domain/ip-to-socket hash, which requests should be sent to
-
# :persistent :: whether to persist connections in between requests (defaults to <tt>true</tt>)
-
# :resolver_class :: which resolver to use (defaults to <tt>:native</tt>, can also be <tt>:system<tt> for
-
# using getaddrinfo or <tt>:https</tt> for DoH resolver, or a custom class)
-
# :resolver_options :: hash of options passed to the resolver
-
# :ip_families :: which socket families are supported (system-dependent)
-
# :origin :: HTTP origin to set on requests with relative path (ex: "https://api.serv.com")
-
# :base_path :: path to prefix given relative paths with (ex: "/v2")
-
# :max_concurrent_requests :: max number of requests which can be set concurrently
-
# :max_requests :: max number of requests which can be made on socket before it reconnects.
-
#
-
# This list of options are enhanced with each loaded plugin, see the plugin docs for details.
-
24
def initialize(options = {})
-
3599
do_initialize(options)
-
3585
freeze
-
end
-
-
24
def freeze
-
9211
super
-
9211
@origin.freeze
-
9211
@base_path.freeze
-
9211
@timeout.freeze
-
9211
@headers.freeze
-
9211
@addresses.freeze
-
9211
@supported_compression_formats.freeze
-
end
-
-
24
def option_origin(value)
-
520
URI(value)
-
end
-
-
24
def option_base_path(value)
-
28
String(value)
-
end
-
-
24
def option_headers(value)
-
6424
headers_class.new(value)
-
end
-
-
24
def option_timeout(value)
-
6807
Hash[value]
-
end
-
-
24
def option_supported_compression_formats(value)
-
5906
Array(value).map(&:to_s)
-
end
-
-
24
def option_max_concurrent_requests(value)
-
844
raise TypeError, ":max_concurrent_requests must be positive" unless value.positive?
-
-
844
value
-
end
-
-
24
def option_max_requests(value)
-
5895
raise TypeError, ":max_requests must be positive" unless value.positive?
-
-
5895
value
-
end
-
-
24
def option_window_size(value)
-
5900
value = Integer(value)
-
-
5900
raise TypeError, ":window_size must be positive" unless value.positive?
-
-
5900
value
-
end
-
-
24
def option_buffer_size(value)
-
5900
value = Integer(value)
-
-
5900
raise TypeError, ":buffer_size must be positive" unless value.positive?
-
-
5900
value
-
end
-
-
24
def option_body_threshold_size(value)
-
5886
bytes = Integer(value)
-
5886
raise TypeError, ":body_threshold_size must be positive" unless bytes.positive?
-
-
5886
bytes
-
end
-
-
24
def option_transport(value)
-
42
transport = value.to_s
-
42
raise TypeError, "#{transport} is an unsupported transport type" unless %w[unix].include?(transport)
-
-
42
transport
-
end
-
-
24
def option_addresses(value)
-
37
Array(value)
-
end
-
-
24
def option_ip_families(value)
-
5886
Array(value)
-
end
-
-
24
%i[
-
ssl http2_settings
-
request_class response_class headers_class request_body_class
-
response_body_class connection_class options_class
-
io fallback_protocol debug debug_level resolver_class resolver_options
-
compress_request_body decompress_response_body
-
persistent
-
].each do |method_name|
-
432
class_eval(<<-OUT, __FILE__, __LINE__ + 1)
-
18
# sets +v+ as the value of #{method_name}
-
18
def option_#{method_name}(v); v; end # def option_smth(v); v; end
-
OUT
-
end
-
-
24
REQUEST_BODY_IVARS = %i[@headers].freeze
-
-
24
def ==(other)
-
3658
super || options_equals?(other)
-
end
-
-
24
def options_equals?(other, ignore_ivars = REQUEST_BODY_IVARS)
-
# headers and other request options do not play a role, as they are
-
# relevant only for the request.
-
2398
ivars = instance_variables - ignore_ivars
-
2398
other_ivars = other.instance_variables - ignore_ivars
-
-
2398
return false if ivars.size != other_ivars.size
-
-
1680
return false if ivars.sort != other_ivars.sort
-
-
1668
ivars.all? do |ivar|
-
23247
instance_variable_get(ivar) == other.instance_variable_get(ivar)
-
end
-
end
-
-
24
OTHER_LOOKUP = ->(obj, k, ivar_map) {
-
234035
case obj
-
when Hash
-
22067
obj[ivar_map[k]]
-
else
-
243033
obj.instance_variable_get(k)
-
end
-
}
-
24
def merge(other)
-
27563
ivar_map = nil
-
27563
other_ivars = case other
-
when Hash
-
32484
ivar_map = other.keys.to_h { |k| [:"@#{k}", k] }
-
19071
ivar_map.keys
-
else
-
8492
other.instance_variables
-
end
-
-
27563
return self if other_ivars.empty?
-
-
211934
return self if other_ivars.all? { |ivar| instance_variable_get(ivar) == OTHER_LOOKUP[other, ivar, ivar_map] }
-
-
10397
opts = dup
-
-
10397
other_ivars.each do |ivar|
-
69914
v = OTHER_LOOKUP[other, ivar, ivar_map]
-
-
69914
unless v
-
2631
opts.instance_variable_set(ivar, v)
-
2631
next
-
end
-
-
67283
v = opts.__send__(:"option_#{ivar[1..-1]}", v)
-
-
67283
orig_v = instance_variable_get(ivar)
-
-
67283
v = orig_v.merge(v) if orig_v.respond_to?(:merge) && v.respond_to?(:merge)
-
-
67283
opts.instance_variable_set(ivar, v)
-
end
-
-
10397
opts
-
end
-
-
24
def to_hash
-
2610
instance_variables.each_with_object({}) do |ivar, hs|
-
55389
hs[ivar[1..-1].to_sym] = instance_variable_get(ivar)
-
end
-
end
-
-
24
def extend_with_plugin_classes(pl)
-
5588
if defined?(pl::RequestMethods) || defined?(pl::RequestClassMethods)
-
1654
@request_class = @request_class.dup
-
1654
@request_class.__send__(:include, pl::RequestMethods) if defined?(pl::RequestMethods)
-
1654
@request_class.extend(pl::RequestClassMethods) if defined?(pl::RequestClassMethods)
-
end
-
5588
if defined?(pl::ResponseMethods) || defined?(pl::ResponseClassMethods)
-
1725
@response_class = @response_class.dup
-
1725
@response_class.__send__(:include, pl::ResponseMethods) if defined?(pl::ResponseMethods)
-
1725
@response_class.extend(pl::ResponseClassMethods) if defined?(pl::ResponseClassMethods)
-
end
-
5588
if defined?(pl::HeadersMethods) || defined?(pl::HeadersClassMethods)
-
133
@headers_class = @headers_class.dup
-
133
@headers_class.__send__(:include, pl::HeadersMethods) if defined?(pl::HeadersMethods)
-
133
@headers_class.extend(pl::HeadersClassMethods) if defined?(pl::HeadersClassMethods)
-
end
-
5588
if defined?(pl::RequestBodyMethods) || defined?(pl::RequestBodyClassMethods)
-
142
@request_body_class = @request_body_class.dup
-
142
@request_body_class.__send__(:include, pl::RequestBodyMethods) if defined?(pl::RequestBodyMethods)
-
142
@request_body_class.extend(pl::RequestBodyClassMethods) if defined?(pl::RequestBodyClassMethods)
-
end
-
5588
if defined?(pl::ResponseBodyMethods) || defined?(pl::ResponseBodyClassMethods)
-
468
@response_body_class = @response_body_class.dup
-
468
@response_body_class.__send__(:include, pl::ResponseBodyMethods) if defined?(pl::ResponseBodyMethods)
-
468
@response_body_class.extend(pl::ResponseBodyClassMethods) if defined?(pl::ResponseBodyClassMethods)
-
end
-
5588
if defined?(pl::ConnectionMethods)
-
2492
@connection_class = @connection_class.dup
-
2492
@connection_class.__send__(:include, pl::ConnectionMethods)
-
end
-
5588
return unless defined?(pl::OptionsMethods)
-
-
2204
@options_class = @options_class.dup
-
2204
@options_class.__send__(:include, pl::OptionsMethods)
-
end
-
-
24
private
-
-
24
def do_initialize(options = {})
-
3599
defaults = DEFAULT_OPTIONS.merge(options)
-
3599
defaults.each do |k, v|
-
97938
next if v.nil?
-
-
87141
option_method_name = :"option_#{k}"
-
87141
raise Error, "unknown option: #{k}" unless respond_to?(option_method_name)
-
-
87134
value = __send__(option_method_name, v)
-
87127
instance_variable_set(:"@#{k}", value)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
module Parser
-
24
class Error < Error; end
-
-
24
class HTTP1
-
24
VERSIONS = %w[1.0 1.1].freeze
-
-
24
attr_reader :status_code, :http_version, :headers
-
-
24
def initialize(observer)
-
3647
@observer = observer
-
3647
@state = :idle
-
3647
@buffer = "".b
-
3647
@headers = {}
-
end
-
-
24
def <<(chunk)
-
5921
@buffer << chunk
-
5921
parse
-
end
-
-
24
def reset!
-
10430
@state = :idle
-
10430
@headers.clear
-
10430
@content_length = nil
-
10430
@_has_trailers = nil
-
end
-
-
24
def upgrade?
-
3711
@upgrade
-
end
-
-
24
def upgrade_data
-
28
@buffer
-
end
-
-
24
private
-
-
24
def parse
-
5921
loop do
-
12506
state = @state
-
11035
case @state
-
when :idle
-
4013
parse_headline
-
when :headers, :trailers
-
4091
parse_headers
-
when :data
-
4400
parse_data
-
end
-
9248
return if @buffer.empty? || state == @state
-
end
-
end
-
-
24
def parse_headline
-
4013
idx = @buffer.index("\n")
-
4013
return unless idx
-
-
4013
(m = %r{\AHTTP(?:/(\d+\.\d+))?\s+(\d\d\d)(?:\s+(.*))?}in.match(@buffer)) ||
-
raise(Error, "wrong head line format")
-
4006
version, code, _ = m.captures
-
4006
raise(Error, "unsupported HTTP version (HTTP/#{version})") unless version && VERSIONS.include?(version)
-
-
3999
@http_version = version.split(".").map(&:to_i)
-
3999
@status_code = code.to_i
-
3999
raise(Error, "wrong status code (#{@status_code})") unless (100..599).cover?(@status_code)
-
-
3992
@buffer = @buffer.byteslice((idx + 1)..-1)
-
3992
nextstate(:headers)
-
end
-
-
24
def parse_headers
-
4093
headers = @headers
-
4093
buffer = @buffer
-
-
31202
while (idx = buffer.index("\n"))
-
# @type var line: String
-
31168
line = buffer.byteslice(0..idx)
-
31168
raise Error, "wrong header format" if line.start_with?("\s", "\t")
-
-
31161
line.lstrip!
-
31161
buffer = @buffer = buffer.byteslice((idx + 1)..-1)
-
31161
if line.empty?
-
3531
case @state
-
when :headers
-
3978
prepare_data(headers)
-
3978
@observer.on_headers(headers)
-
3438
return unless @state == :headers
-
-
# state might have been reset
-
# in the :headers callback
-
3373
nextstate(:data)
-
3373
headers.clear
-
when :trailers
-
14
@observer.on_trailers(headers)
-
14
headers.clear
-
14
nextstate(:complete)
-
end
-
3387
return
-
end
-
27169
separator_index = line.index(":")
-
27169
raise Error, "wrong header format" unless separator_index
-
-
# @type var key: String
-
27162
key = line.byteslice(0..(separator_index - 1))
-
-
27162
key.rstrip! # was lstripped previously!
-
# @type var value: String
-
27162
value = line.byteslice((separator_index + 1)..-1)
-
27162
value.strip!
-
27162
raise Error, "wrong header format" if value.nil?
-
-
27162
(headers[key.downcase] ||= []) << value
-
end
-
end
-
-
24
def parse_data
-
4400
if @buffer.respond_to?(:each)
-
170
@buffer.each do |chunk|
-
205
@observer.on_data(chunk)
-
end
-
4229
elsif @content_length
-
# @type var data: String
-
4202
data = @buffer.byteslice(0, @content_length)
-
4202
@buffer = @buffer.byteslice(@content_length..-1) || "".b
-
3699
@content_length -= data.bytesize
-
4202
@observer.on_data(data)
-
4190
data.clear
-
else
-
28
@observer.on_data(@buffer)
-
28
@buffer.clear
-
end
-
4381
return unless no_more_data?
-
-
3256
@buffer = @buffer.to_s
-
3256
if @_has_trailers
-
14
nextstate(:trailers)
-
else
-
3242
nextstate(:complete)
-
end
-
end
-
-
24
def prepare_data(headers)
-
3978
@upgrade = headers.key?("upgrade")
-
-
3978
@_has_trailers = headers.key?("trailer")
-
-
3978
if (tr_encodings = headers["transfer-encoding"])
-
100
tr_encodings.reverse_each do |tr_encoding|
-
100
tr_encoding.split(/ *, */).each do |encoding|
-
86
case encoding
-
when "chunked"
-
100
@buffer = Transcoder::Chunker::Decoder.new(@buffer, @_has_trailers)
-
end
-
end
-
end
-
else
-
3878
@content_length = headers["content-length"][0].to_i if headers.key?("content-length")
-
end
-
end
-
-
24
def no_more_data?
-
4381
if @content_length
-
4190
@content_length <= 0
-
190
elsif @buffer.respond_to?(:finished?)
-
163
@buffer.finished?
-
else
-
28
false
-
end
-
end
-
-
24
def nextstate(state)
-
10635
@state = state
-
9418
case state
-
when :headers
-
3992
@observer.on_start
-
when :complete
-
3256
@observer.on_complete
-
592
reset!
-
592
nextstate(:idle) unless @buffer.empty?
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# This plugin adds a shim +authorization+ method to the session, which will fill
-
# the HTTP Authorization header, and another, +bearer_auth+, which fill the "Bearer " prefix
-
# in its value.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Auth#auth
-
#
-
7
module Auth
-
7
module InstanceMethods
-
7
def authorization(token)
-
126
with(headers: { "authorization" => token })
-
end
-
-
7
def bearer_auth(token)
-
14
authorization("Bearer #{token}")
-
end
-
end
-
end
-
7
register_plugin :auth, Auth
-
end
-
end
-
# frozen_string_literal: true
-
-
8
require "httpx/base64"
-
-
8
module HTTPX
-
8
module Plugins
-
8
module Authentication
-
8
class Basic
-
8
def initialize(user, password, **)
-
236
@user = user
-
236
@password = password
-
end
-
-
8
def authenticate(*)
-
209
"Basic #{Base64.strict_encode64("#{@user}:#{@password}")}"
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
7
require "time"
-
7
require "securerandom"
-
7
require "digest"
-
-
7
module HTTPX
-
7
module Plugins
-
7
module Authentication
-
7
class Digest
-
7
def initialize(user, password, hashed: false, **)
-
168
@user = user
-
168
@password = password
-
168
@nonce = 0
-
168
@hashed = hashed
-
end
-
-
7
def can_authenticate?(authenticate)
-
140
authenticate && /Digest .*/.match?(authenticate)
-
end
-
-
7
def authenticate(request, authenticate)
-
140
"Digest #{generate_header(request.verb, request.path, authenticate)}"
-
end
-
-
7
private
-
-
7
def generate_header(meth, uri, authenticate)
-
# discard first token, it's Digest
-
140
auth_info = authenticate[/^(\w+) (.*)/, 2]
-
-
140
params = auth_info.split(/ *, */)
-
728
.to_h { |val| val.split("=", 2) }
-
728
.transform_values { |v| v.delete("\"") }
-
140
nonce = params["nonce"]
-
140
nc = next_nonce
-
-
# verify qop
-
140
qop = params["qop"]
-
-
140
if params["algorithm"] =~ /(.*?)(-sess)?$/
-
126
alg = Regexp.last_match(1)
-
126
algorithm = ::Digest.const_get(alg)
-
126
raise DigestError, "unknown algorithm \"#{alg}\"" unless algorithm
-
-
126
sess = Regexp.last_match(2)
-
else
-
14
algorithm = ::Digest::MD5
-
end
-
-
140
if qop || sess
-
140
cnonce = make_cnonce
-
140
nc = format("%<nonce>08x", nonce: nc)
-
end
-
-
140
a1 = if sess
-
4
[
-
28
(@hashed ? @password : algorithm.hexdigest("#{@user}:#{params["realm"]}:#{@password}")),
-
nonce,
-
cnonce,
-
3
].join ":"
-
else
-
112
@hashed ? @password : "#{@user}:#{params["realm"]}:#{@password}"
-
end
-
-
140
ha1 = algorithm.hexdigest(a1)
-
140
ha2 = algorithm.hexdigest("#{meth}:#{uri}")
-
140
request_digest = [ha1, nonce]
-
140
request_digest.push(nc, cnonce, qop) if qop
-
140
request_digest << ha2
-
140
request_digest = request_digest.join(":")
-
-
40
header = [
-
120
%(username="#{@user}"),
-
20
%(nonce="#{nonce}"),
-
20
%(uri="#{uri}"),
-
20
%(response="#{algorithm.hexdigest(request_digest)}"),
-
]
-
140
header << %(realm="#{params["realm"]}") if params.key?("realm")
-
140
header << %(algorithm=#{params["algorithm"]}) if params.key?("algorithm")
-
140
header << %(cnonce="#{cnonce}") if cnonce
-
140
header << %(nc=#{nc})
-
140
header << %(qop=#{qop}) if qop
-
140
header << %(opaque="#{params["opaque"]}") if params.key?("opaque")
-
140
header.join ", "
-
end
-
-
7
def make_cnonce
-
160
::Digest::MD5.hexdigest [
-
Time.now.to_i,
-
Process.pid,
-
SecureRandom.random_number(2**32),
-
].join ":"
-
end
-
-
7
def next_nonce
-
120
@nonce += 1
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
5
require "httpx/base64"
-
5
require "ntlm"
-
-
5
module HTTPX
-
5
module Plugins
-
5
module Authentication
-
5
class Ntlm
-
5
def initialize(user, password, domain: nil)
-
4
@user = user
-
4
@password = password
-
4
@domain = domain
-
end
-
-
5
def can_authenticate?(authenticate)
-
2
authenticate && /NTLM .*/.match?(authenticate)
-
end
-
-
5
def negotiate
-
4
"NTLM #{NTLM.negotiate(domain: @domain).to_base64}"
-
end
-
-
5
def authenticate(_req, www)
-
2
challenge = www[/NTLM (.*)/, 1]
-
-
2
challenge = Base64.decode64(challenge)
-
2
ntlm_challenge = NTLM.authenticate(challenge, @user, @domain, @password).to_base64
-
-
2
"NTLM #{ntlm_challenge}"
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
9
module HTTPX
-
9
module Plugins
-
9
module Authentication
-
9
class Socks5
-
9
def initialize(user, password, **)
-
42
@user = user
-
42
@password = password
-
end
-
-
9
def can_authenticate?(*)
-
42
@user && @password
-
end
-
-
9
def authenticate(*)
-
42
[0x01, @user.bytesize, @user, @password.bytesize, @password].pack("CCA*CA*")
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# This plugin applies AWS Sigv4 to requests, using the AWS SDK credentials and configuration.
-
#
-
# It requires the "aws-sdk-core" gem.
-
#
-
7
module AwsSdkAuthentication
-
# Mock configuration, to be used only when resolving credentials
-
7
class Configuration
-
7
attr_reader :profile
-
-
7
def initialize(profile)
-
28
@profile = profile
-
end
-
-
7
def respond_to_missing?(*)
-
14
true
-
end
-
-
7
def method_missing(*); end
-
end
-
-
#
-
# encapsulates access to an AWS SDK credentials store.
-
#
-
7
class Credentials
-
7
def initialize(aws_credentials)
-
14
@aws_credentials = aws_credentials
-
end
-
-
7
def username
-
14
@aws_credentials.access_key_id
-
end
-
-
7
def password
-
14
@aws_credentials.secret_access_key
-
end
-
-
7
def security_token
-
14
@aws_credentials.session_token
-
end
-
end
-
-
7
class << self
-
7
def load_dependencies(_klass)
-
14
require "aws-sdk-core"
-
end
-
-
7
def configure(klass)
-
14
klass.plugin(:aws_sigv4)
-
end
-
-
7
def extra_options(options)
-
14
options.merge(max_concurrent_requests: 1)
-
end
-
-
7
def credentials(profile)
-
14
mock_configuration = Configuration.new(profile)
-
14
Credentials.new(Aws::CredentialProviderChain.new(mock_configuration).resolve)
-
end
-
-
7
def region(profile)
-
# https://github.com/aws/aws-sdk-ruby/blob/version-3/gems/aws-sdk-core/lib/aws-sdk-core/plugins/regional_endpoint.rb#L62
-
14
keys = %w[AWS_REGION AMAZON_REGION AWS_DEFAULT_REGION]
-
14
env_region = ENV.values_at(*keys).compact.first
-
14
env_region = nil if env_region == ""
-
14
cfg_region = Aws.shared_config.region(profile: profile)
-
14
env_region || cfg_region
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :aws_profile :: AWS account profile to retrieve credentials from.
-
7
module OptionsMethods
-
7
def option_aws_profile(value)
-
70
String(value)
-
end
-
end
-
-
7
module InstanceMethods
-
#
-
# aws_authentication
-
# aws_authentication(credentials: Aws::Credentials.new('akid', 'secret'))
-
# aws_authentication()
-
#
-
7
def aws_sdk_authentication(
-
credentials: AwsSdkAuthentication.credentials(@options.aws_profile),
-
region: AwsSdkAuthentication.region(@options.aws_profile),
-
**options
-
)
-
-
14
aws_sigv4_authentication(
-
credentials: credentials,
-
region: region,
-
provider_prefix: "aws",
-
header_provider_field: "amz",
-
**options
-
)
-
end
-
7
alias_method :aws_auth, :aws_sdk_authentication
-
end
-
end
-
7
register_plugin :aws_sdk_authentication, AwsSdkAuthentication
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# This plugin adds AWS Sigv4 authentication.
-
#
-
# https://docs.aws.amazon.com/IAM/latest/UserGuide/signing-elements.html
-
#
-
# https://gitlab.com/os85/httpx/wikis/AWS-SigV4
-
#
-
7
module AWSSigV4
-
7
Credentials = Struct.new(:username, :password, :security_token)
-
-
# Signs requests using the AWS sigv4 signing.
-
7
class Signer
-
7
def initialize(
-
service:,
-
region:,
-
credentials: nil,
-
username: nil,
-
password: nil,
-
security_token: nil,
-
provider_prefix: "aws",
-
header_provider_field: "amz",
-
unsigned_headers: [],
-
apply_checksum_header: true,
-
algorithm: "SHA256"
-
)
-
112
@credentials = credentials || Credentials.new(username, password, security_token)
-
112
@service = service
-
112
@region = region
-
-
112
@unsigned_headers = Set.new(unsigned_headers.map(&:downcase))
-
112
@unsigned_headers << "authorization"
-
112
@unsigned_headers << "x-amzn-trace-id"
-
112
@unsigned_headers << "expect"
-
-
112
@apply_checksum_header = apply_checksum_header
-
112
@provider_prefix = provider_prefix
-
112
@header_provider_field = header_provider_field
-
-
112
@algorithm = algorithm
-
end
-
-
7
def sign!(request)
-
112
lower_provider_prefix = "#{@provider_prefix}4"
-
112
upper_provider_prefix = lower_provider_prefix.upcase
-
-
112
downcased_algorithm = @algorithm.downcase
-
-
112
datetime = (request.headers["x-#{@header_provider_field}-date"] ||= Time.now.utc.strftime("%Y%m%dT%H%M%SZ"))
-
112
date = datetime[0, 8]
-
-
112
content_hashed = request.headers["x-#{@header_provider_field}-content-#{downcased_algorithm}"] || hexdigest(request.body)
-
-
112
request.headers["x-#{@header_provider_field}-content-#{downcased_algorithm}"] ||= content_hashed if @apply_checksum_header
-
112
request.headers["x-#{@header_provider_field}-security-token"] ||= @credentials.security_token if @credentials.security_token
-
-
112
signature_headers = request.headers.each.reject do |k, _|
-
742
@unsigned_headers.include?(k)
-
end
-
# aws sigv4 needs to declare the host, regardless of protocol version
-
112
signature_headers << ["host", request.authority] unless request.headers.key?("host")
-
112
signature_headers.sort_by!(&:first)
-
-
112
signed_headers = signature_headers.map(&:first).join(";")
-
-
112
canonical_headers = signature_headers.map do |k, v|
-
# eliminate whitespace between value fields, unless it's a quoted value
-
624
"#{k}:#{v.start_with?("\"") && v.end_with?("\"") ? v : v.gsub(/\s+/, " ").strip}\n"
-
end.join
-
-
# canonical request
-
112
creq = "#{request.verb}" \
-
16
"\n#{request.canonical_path}" \
-
16
"\n#{request.canonical_query}" \
-
16
"\n#{canonical_headers}" \
-
16
"\n#{signed_headers}" \
-
16
"\n#{content_hashed}"
-
-
112
credential_scope = "#{date}" \
-
16
"/#{@region}" \
-
16
"/#{@service}" \
-
16
"/#{lower_provider_prefix}_request"
-
-
112
algo_line = "#{upper_provider_prefix}-HMAC-#{@algorithm}"
-
# string to sign
-
112
sts = "#{algo_line}" \
-
16
"\n#{datetime}" \
-
16
"\n#{credential_scope}" \
-
16
"\n#{hexdigest(creq)}"
-
-
# signature
-
112
k_date = hmac("#{upper_provider_prefix}#{@credentials.password}", date)
-
112
k_region = hmac(k_date, @region)
-
112
k_service = hmac(k_region, @service)
-
112
k_credentials = hmac(k_service, "#{lower_provider_prefix}_request")
-
112
sig = hexhmac(k_credentials, sts)
-
-
112
credential = "#{@credentials.username}/#{credential_scope}"
-
# apply signature
-
96
request.headers["authorization"] =
-
16
"#{algo_line} " \
-
16
"Credential=#{credential}, " \
-
16
"SignedHeaders=#{signed_headers}, " \
-
16
"Signature=#{sig}"
-
end
-
-
7
private
-
-
7
def hexdigest(value)
-
217
if value.respond_to?(:to_path)
-
# files, pathnames
-
7
OpenSSL::Digest.new(@algorithm).file(value.to_path).hexdigest
-
209
elsif value.respond_to?(:each)
-
98
digest = OpenSSL::Digest.new(@algorithm)
-
-
98
mb_buffer = value.each.with_object("".b) do |chunk, buffer|
-
35
buffer << chunk
-
35
break if buffer.bytesize >= 1024 * 1024
-
end
-
-
98
digest.update(mb_buffer)
-
98
value.rewind
-
98
digest.hexdigest
-
else
-
112
OpenSSL::Digest.new(@algorithm).hexdigest(value)
-
end
-
end
-
-
7
def hmac(key, value)
-
448
OpenSSL::HMAC.digest(OpenSSL::Digest.new(@algorithm), key, value)
-
end
-
-
7
def hexhmac(key, value)
-
112
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new(@algorithm), key, value)
-
end
-
end
-
-
7
class << self
-
7
def load_dependencies(*)
-
112
require "set"
-
112
require "digest/sha2"
-
112
require "openssl"
-
end
-
-
7
def configure(klass)
-
112
klass.plugin(:expect)
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :sigv4_signer :: instance of HTTPX::Plugins::AWSSigV4 used to sign requests.
-
7
module OptionsMethods
-
7
def option_sigv4_signer(value)
-
238
value.is_a?(Signer) ? value : Signer.new(value)
-
end
-
end
-
-
7
module InstanceMethods
-
7
def aws_sigv4_authentication(**options)
-
112
with(sigv4_signer: Signer.new(**options))
-
end
-
-
7
def build_request(*)
-
112
request = super
-
-
112
return request if request.headers.key?("authorization")
-
-
112
signer = request.options.sigv4_signer
-
-
112
return request unless signer
-
-
112
signer.sign!(request)
-
-
112
request
-
end
-
end
-
-
7
module RequestMethods
-
7
def canonical_path
-
112
path = uri.path.dup
-
112
path << "/" if path.empty?
-
140
path.gsub(%r{[^/]+}) { |part| CGI.escape(part.encode("UTF-8")).gsub("+", "%20").gsub("%7E", "~") }
-
end
-
-
7
def canonical_query
-
140
params = query.split("&")
-
# params = params.map { |p| p.match(/=/) ? p : p + '=' }
-
# From: https://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html#create-canonical-request
-
# Sort the parameter names by character code point in ascending order.
-
# Parameters with duplicate names should be sorted by value.
-
#
-
# Default sort <=> in JRuby will swap members
-
# occasionally when <=> is 0 (considered still sorted), but this
-
# causes our normalized query string to not match the sent querystring.
-
# When names match, we then sort by their values. When values also
-
# match then we sort by their original order
-
140
params.each.with_index.sort do |a, b|
-
56
a, a_offset = a
-
56
b, b_offset = b
-
56
a_name, a_value = a.split("=", 2)
-
56
b_name, b_value = b.split("=", 2)
-
56
if a_name == b_name
-
28
if a_value == b_value
-
14
a_offset <=> b_offset
-
else
-
14
a_value <=> b_value
-
end
-
else
-
28
a_name <=> b_name
-
end
-
end.map(&:first).join("&")
-
end
-
end
-
end
-
7
register_plugin :aws_sigv4, AWSSigV4
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# This plugin adds helper methods to implement HTTP Basic Auth (https://datatracker.ietf.org/doc/html/rfc7617)
-
#
-
# https://gitlab.com/os85/httpx/wikis/Auth#basic-auth
-
#
-
7
module BasicAuth
-
7
class << self
-
7
def load_dependencies(_klass)
-
98
require_relative "auth/basic"
-
end
-
-
7
def configure(klass)
-
98
klass.plugin(:auth)
-
end
-
end
-
-
7
module InstanceMethods
-
7
def basic_auth(user, password)
-
112
authorization(Authentication::Basic.new(user, password).authenticate)
-
end
-
end
-
end
-
7
register_plugin :basic_auth, BasicAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
5
module HTTPX
-
5
module Plugins
-
5
module Brotli
-
5
class Deflater < Transcoder::Deflater
-
5
def deflate(chunk)
-
20
return unless chunk
-
-
10
::Brotli.deflate(chunk)
-
end
-
end
-
-
5
module RequestBodyClassMethods
-
5
def initialize_deflater_body(body, encoding)
-
20
return Brotli.encode(body) if encoding == "br"
-
-
10
super
-
end
-
end
-
-
5
module ResponseBodyClassMethods
-
5
def initialize_inflater_by_encoding(encoding, response, **kwargs)
-
20
return Brotli.decode(response, **kwargs) if encoding == "br"
-
-
10
super
-
end
-
end
-
-
5
module_function
-
-
5
def load_dependencies(*)
-
20
require "brotli"
-
end
-
-
5
def self.extra_options(options)
-
20
options.merge(supported_compression_formats: %w[br] + options.supported_compression_formats)
-
end
-
-
5
def encode(body)
-
10
Deflater.new(body)
-
end
-
-
5
def decode(_response, **)
-
10
::Brotli.method(:inflate)
-
end
-
end
-
5
register_plugin :brotli, Brotli
-
end
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
module Plugins
-
#
-
# This plugin adds suppoort for callbacks around the request/response lifecycle.
-
#
-
# https://gitlab.com/os85/httpx/-/wikis/Events
-
#
-
24
module Callbacks
-
# connection closed user-space errors happen after errors can be surfaced to requests,
-
# so they need to pierce through the scheduler, which is only possible by simulating an
-
# interrupt.
-
24
class CallbackError < Exception; end # rubocop:disable Lint/InheritException
-
-
24
module InstanceMethods
-
24
include HTTPX::Callbacks
-
-
24
%i[
-
connection_opened connection_closed
-
request_error
-
request_started request_body_chunk request_completed
-
response_started response_body_chunk response_completed
-
].each do |meth|
-
216
class_eval(<<-MOD, __FILE__, __LINE__ + 1)
-
9
def on_#{meth}(&blk) # def on_connection_opened(&blk)
-
9
on(:#{meth}, &blk) # on(:connection_opened, &blk)
-
end # end
-
MOD
-
end
-
-
24
private
-
-
24
def init_connection(uri, options)
-
183
connection = super
-
183
connection.on(:open) do
-
171
emit_or_callback_error(:connection_opened, connection.origin, connection.io.socket)
-
end
-
183
connection.on(:close) do
-
170
emit_or_callback_error(:connection_closed, connection.origin) if connection.used?
-
end
-
-
183
connection
-
end
-
-
24
def set_request_callbacks(request)
-
185
super
-
-
185
request.on(:headers) do
-
157
emit_or_callback_error(:request_started, request)
-
end
-
185
request.on(:body_chunk) do |chunk|
-
14
emit_or_callback_error(:request_body_chunk, request, chunk)
-
end
-
185
request.on(:done) do
-
143
emit_or_callback_error(:request_completed, request)
-
end
-
-
185
request.on(:response_started) do |res|
-
143
if res.is_a?(Response)
-
129
emit_or_callback_error(:response_started, request, res)
-
115
res.on(:chunk_received) do |chunk|
-
135
emit_or_callback_error(:response_body_chunk, request, res, chunk)
-
end
-
else
-
14
emit_or_callback_error(:request_error, request, res.error)
-
end
-
end
-
185
request.on(:response) do |res|
-
115
emit_or_callback_error(:response_completed, request, res)
-
end
-
end
-
-
24
def emit_or_callback_error(*args)
-
1034
emit(*args)
-
rescue StandardError => e
-
105
ex = CallbackError.new(e.message)
-
105
ex.set_backtrace(e.backtrace)
-
105
raise ex
-
end
-
-
24
def receive_requests(*)
-
185
super
-
rescue CallbackError => e
-
98
raise e.cause
-
end
-
end
-
end
-
24
register_plugin :callbacks, Callbacks
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# This plugin implements a circuit breaker around connection errors.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Circuit-Breaker
-
#
-
7
module CircuitBreaker
-
7
using URIExtensions
-
-
7
def self.load_dependencies(*)
-
49
require_relative "circuit_breaker/circuit"
-
49
require_relative "circuit_breaker/circuit_store"
-
end
-
-
7
def self.extra_options(options)
-
49
options.merge(
-
circuit_breaker_max_attempts: 3,
-
circuit_breaker_reset_attempts_in: 60,
-
circuit_breaker_break_in: 60,
-
circuit_breaker_half_open_drip_rate: 1
-
)
-
end
-
-
7
module InstanceMethods
-
7
include HTTPX::Callbacks
-
-
7
def initialize(*)
-
49
super
-
49
@circuit_store = CircuitStore.new(@options)
-
end
-
-
7
def initialize_dup(orig)
-
super
-
@circuit_store = orig.instance_variable_get(:@circuit_store).dup
-
end
-
-
7
%i[circuit_open].each do |meth|
-
7
class_eval(<<-MOD, __FILE__, __LINE__ + 1)
-
1
def on_#{meth}(&blk) # def on_circuit_open(&blk)
-
1
on(:#{meth}, &blk) # on(:circuit_open, &blk)
-
end # end
-
MOD
-
end
-
-
7
private
-
-
7
def send_requests(*requests)
-
# @type var short_circuit_responses: Array[response]
-
196
short_circuit_responses = []
-
-
# run all requests through the circuit breaker, see if the circuit is
-
# open for any of them.
-
196
real_requests = requests.each_with_index.with_object([]) do |(req, idx), real_reqs|
-
196
short_circuit_response = @circuit_store.try_respond(req)
-
196
if short_circuit_response.nil?
-
154
real_reqs << req
-
154
next
-
end
-
36
short_circuit_responses[idx] = short_circuit_response
-
end
-
-
# run requests for the remainder
-
196
unless real_requests.empty?
-
154
responses = super(*real_requests)
-
-
154
real_requests.each_with_index do |request, idx|
-
132
short_circuit_responses[requests.index(request)] = responses[idx]
-
end
-
end
-
-
196
short_circuit_responses
-
end
-
-
7
def on_response(request, response)
-
154
emit(:circuit_open, request) if try_circuit_open(request, response)
-
-
154
super
-
end
-
-
7
def try_circuit_open(request, response)
-
154
if response.is_a?(ErrorResponse)
-
96
case response.error
-
when RequestTimeoutError
-
70
@circuit_store.try_open(request.uri, response)
-
else
-
42
@circuit_store.try_open(request.origin, response)
-
end
-
42
elsif (break_on = request.options.circuit_breaker_break_on) && break_on.call(response)
-
14
@circuit_store.try_open(request.uri, response)
-
else
-
28
@circuit_store.try_close(request.uri)
-
8
nil
-
end
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :circuit_breaker_max_attempts :: the number of attempts the circuit allows, before it is opened (defaults to <tt>3</tt>).
-
# :circuit_breaker_reset_attempts_in :: the time a circuit stays open at most, before it resets (defaults to <tt>60</tt>).
-
# :circuit_breaker_break_on :: callable defining an alternative rule for a response to break
-
# (i.e. <tt>->(res) { res.status == 429 } </tt>)
-
# :circuit_breaker_break_in :: the time that must elapse before an open circuit can transit to the half-open state
-
# (defaults to <tt><60</tt>).
-
# :circuit_breaker_half_open_drip_rate :: the rate of requests a circuit allows to be performed when in an half-open state
-
# (defaults to <tt>1</tt>).
-
7
module OptionsMethods
-
7
def option_circuit_breaker_max_attempts(value)
-
98
attempts = Integer(value)
-
98
raise TypeError, ":circuit_breaker_max_attempts must be positive" unless attempts.positive?
-
-
98
attempts
-
end
-
-
7
def option_circuit_breaker_reset_attempts_in(value)
-
56
timeout = Float(value)
-
56
raise TypeError, ":circuit_breaker_reset_attempts_in must be positive" unless timeout.positive?
-
-
56
timeout
-
end
-
-
7
def option_circuit_breaker_break_in(value)
-
77
timeout = Float(value)
-
77
raise TypeError, ":circuit_breaker_break_in must be positive" unless timeout.positive?
-
-
77
timeout
-
end
-
-
7
def option_circuit_breaker_half_open_drip_rate(value)
-
77
ratio = Float(value)
-
77
raise TypeError, ":circuit_breaker_half_open_drip_rate must be a number between 0 and 1" unless (0..1).cover?(ratio)
-
-
77
ratio
-
end
-
-
7
def option_circuit_breaker_break_on(value)
-
14
raise TypeError, ":circuit_breaker_break_on must be called with the response" unless value.respond_to?(:call)
-
-
14
value
-
end
-
end
-
end
-
7
register_plugin :circuit_breaker, CircuitBreaker
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins::CircuitBreaker
-
#
-
# A circuit is assigned to a given absoolute url or origin.
-
#
-
# It sets +max_attempts+, the number of attempts the circuit allows, before it is opened.
-
# It sets +reset_attempts_in+, the time a circuit stays open at most, before it resets.
-
# It sets +break_in+, the time that must elapse before an open circuit can transit to the half-open state.
-
# It sets +circuit_breaker_half_open_drip_rate+, the rate of requests a circuit allows to be performed when in an half-open state.
-
#
-
7
class Circuit
-
7
def initialize(max_attempts, reset_attempts_in, break_in, circuit_breaker_half_open_drip_rate)
-
49
@max_attempts = max_attempts
-
49
@reset_attempts_in = reset_attempts_in
-
49
@break_in = break_in
-
49
@circuit_breaker_half_open_drip_rate = circuit_breaker_half_open_drip_rate
-
49
@attempts = 0
-
-
49
total_real_attempts = @max_attempts * @circuit_breaker_half_open_drip_rate
-
49
@drip_factor = (@max_attempts / total_real_attempts).round
-
49
@state = :closed
-
end
-
-
7
def respond
-
196
try_close
-
-
168
case @state
-
when :closed
-
34
nil
-
when :half_open
-
42
@attempts += 1
-
-
# do real requests while drip rate valid
-
49
if (@real_attempts % @drip_factor).zero?
-
30
@real_attempts += 1
-
30
return
-
end
-
-
14
@response
-
when :open
-
-
28
@response
-
end
-
end
-
-
7
def try_open(response)
-
108
case @state
-
when :closed
-
105
now = Utils.now
-
-
105
if @attempts.positive?
-
# reset if error happened long ago
-
42
@attempts = 0 if now - @attempted_at > @reset_attempts_in
-
else
-
63
@attempted_at = now
-
end
-
-
90
@attempts += 1
-
-
105
return unless @attempts >= @max_attempts
-
-
56
@state = :open
-
56
@opened_at = now
-
56
@response = response
-
when :half_open
-
# open immediately
-
-
21
@state = :open
-
21
@attempted_at = @opened_at = Utils.now
-
21
@response = response
-
end
-
end
-
-
7
def try_close
-
192
case @state
-
when :closed
-
34
nil
-
when :half_open
-
-
# do not close circuit unless attempts exhausted
-
42
return unless @attempts >= @max_attempts
-
-
# reset!
-
14
@attempts = 0
-
14
@opened_at = @attempted_at = @response = nil
-
14
@state = :closed
-
-
when :open
-
63
if Utils.elapsed_time(@opened_at) > @break_in
-
35
@state = :half_open
-
35
@attempts = 0
-
35
@real_attempts = 0
-
end
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX::Plugins::CircuitBreaker
-
7
using HTTPX::URIExtensions
-
-
7
class CircuitStore
-
7
def initialize(options)
-
49
@circuits = Hash.new do |h, k|
-
42
h[k] = Circuit.new(
-
options.circuit_breaker_max_attempts,
-
options.circuit_breaker_reset_attempts_in,
-
options.circuit_breaker_break_in,
-
options.circuit_breaker_half_open_drip_rate
-
)
-
end
-
49
@circuits_mutex = Thread::Mutex.new
-
end
-
-
7
def try_open(uri, response)
-
252
circuit = @circuits_mutex.synchronize { get_circuit_for_uri(uri) }
-
-
126
circuit.try_open(response)
-
end
-
-
7
def try_close(uri)
-
28
circuit = @circuits_mutex.synchronize do
-
28
return unless @circuits.key?(uri.origin) || @circuits.key?(uri.to_s)
-
-
28
get_circuit_for_uri(uri)
-
end
-
-
28
circuit.try_close
-
end
-
-
# if circuit is open, it'll respond with the stored response.
-
# if not, nil.
-
7
def try_respond(request)
-
392
circuit = @circuits_mutex.synchronize { get_circuit_for_uri(request.uri) }
-
-
196
circuit.respond
-
end
-
-
7
private
-
-
7
def get_circuit_for_uri(uri)
-
350
if uri.respond_to?(:origin) && @circuits.key?(uri.origin)
-
252
@circuits[uri.origin]
-
else
-
98
@circuits[uri.to_s]
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
7
require "forwardable"
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# This plugin implements a persistent cookie jar for the duration of a session.
-
#
-
# It also adds a *#cookies* helper, so that you can pre-fill the cookies of a session.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Cookies
-
#
-
7
module Cookies
-
7
def self.load_dependencies(*)
-
126
require "httpx/plugins/cookies/jar"
-
126
require "httpx/plugins/cookies/cookie"
-
126
require "httpx/plugins/cookies/set_cookie_parser"
-
end
-
-
7
module InstanceMethods
-
7
extend Forwardable
-
-
7
def_delegator :@options, :cookies
-
-
7
def initialize(options = {}, &blk)
-
252
super({ cookies: Jar.new }.merge(options), &blk)
-
end
-
-
7
def wrap
-
14
return super unless block_given?
-
-
14
super do |session|
-
14
old_cookies_jar = @options.cookies.dup
-
1
begin
-
14
yield session
-
ensure
-
14
@options = @options.merge(cookies: old_cookies_jar)
-
end
-
end
-
end
-
-
7
def build_request(*)
-
280
request = super
-
280
request.headers.set_cookie(request.options.cookies[request.uri])
-
280
request
-
end
-
-
7
private
-
-
7
def on_response(_request, response)
-
280
if response && response.respond_to?(:headers) && (set_cookie = response.headers["set-cookie"])
-
-
56
log { "cookies: set-cookie is over #{Cookie::MAX_LENGTH}" } if set_cookie.bytesize > Cookie::MAX_LENGTH
-
-
56
@options.cookies.parse(set_cookie)
-
end
-
-
280
super
-
end
-
end
-
-
7
module HeadersMethods
-
7
def set_cookie(cookies)
-
280
return if cookies.empty?
-
-
238
header_value = cookies.sort.join("; ")
-
-
238
add("cookie", header_value)
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :cookies :: cookie jar for the session (can be a Hash, an Array, an instance of HTTPX::Plugins::Cookies::CookieJar)
-
7
module OptionsMethods
-
7
def option_headers(*)
-
280
value = super
-
-
280
merge_cookie_in_jar(value.delete("cookie"), @cookies) if defined?(@cookies) && value.key?("cookie")
-
-
280
value
-
end
-
-
7
def option_cookies(value)
-
420
jar = value.is_a?(Jar) ? value : Jar.new(value)
-
-
420
merge_cookie_in_jar(@headers.delete("cookie"), jar) if defined?(@headers) && @headers.key?("cookie")
-
-
420
jar
-
end
-
-
7
private
-
-
7
def merge_cookie_in_jar(cookies, jar)
-
14
cookies.each do |ck|
-
14
ck.split(/ *; */).each do |cookie|
-
28
name, value = cookie.split("=", 2)
-
28
jar.add(Cookie.new(name, value))
-
end
-
end
-
end
-
end
-
end
-
7
register_plugin :cookies, Cookies
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins::Cookies
-
# The HTTP Cookie.
-
#
-
# Contains the single cookie info: name, value and attributes.
-
7
class Cookie
-
7
include Comparable
-
# Maximum number of bytes per cookie (RFC 6265 6.1 requires 4096 at
-
# least)
-
7
MAX_LENGTH = 4096
-
-
7
attr_reader :domain, :path, :name, :value, :created_at
-
-
7
def path=(path)
-
161
path = String(path)
-
161
@path = path.start_with?("/") ? path : "/"
-
end
-
-
# See #domain.
-
7
def domain=(domain)
-
35
domain = String(domain)
-
-
35
if domain.start_with?(".")
-
14
@for_domain = true
-
14
domain = domain[1..-1]
-
end
-
-
35
return if domain.empty?
-
-
35
@domain_name = DomainName.new(domain)
-
# RFC 6265 5.3 5.
-
35
@for_domain = false if @domain_name.domain.nil? # a public suffix or IP address
-
-
35
@domain = @domain_name.hostname
-
end
-
-
# Compares the cookie with another. When there are many cookies with
-
# the same name for a URL, the value of the smallest must be used.
-
7
def <=>(other)
-
# RFC 6265 5.4
-
# Precedence: 1. longer path 2. older creation
-
608
(@name <=> other.name).nonzero? ||
-
53
(other.path.length <=> @path.length).nonzero? ||
-
31
(@created_at <=> other.created_at).nonzero? || 0
-
end
-
-
7
class << self
-
7
def new(cookie, *args)
-
441
return cookie if cookie.is_a?(self)
-
-
441
super
-
end
-
-
# Tests if +target_path+ is under +base_path+ as described in RFC
-
# 6265 5.1.4. +base_path+ must be an absolute path.
-
# +target_path+ may be empty, in which case it is treated as the
-
# root path.
-
#
-
# e.g.
-
#
-
# path_match?('/admin/', '/admin/index') == true
-
# path_match?('/admin/', '/Admin/index') == false
-
# path_match?('/admin/', '/admin/') == true
-
# path_match?('/admin/', '/admin') == false
-
#
-
# path_match?('/admin', '/admin') == true
-
# path_match?('/admin', '/Admin') == false
-
# path_match?('/admin', '/admins') == false
-
# path_match?('/admin', '/admin/') == true
-
# path_match?('/admin', '/admin/index') == true
-
7
def path_match?(base_path, target_path)
-
1183
base_path.start_with?("/") || (return false)
-
# RFC 6265 5.1.4
-
1183
bsize = base_path.size
-
1183
tsize = target_path.size
-
1183
return bsize == 1 if tsize.zero? # treat empty target_path as "/"
-
1183
return false unless target_path.start_with?(base_path)
-
1176
return true if bsize == tsize || base_path.end_with?("/")
-
-
14
target_path[bsize] == "/"
-
end
-
end
-
-
7
def initialize(arg, *attrs)
-
441
@created_at = Time.now
-
-
441
if attrs.empty?
-
21
attr_hash = Hash.try_convert(arg)
-
else
-
420
@name = arg
-
420
@value, attr_hash = attrs
-
420
attr_hash = Hash.try_convert(attr_hash)
-
end
-
-
33
attr_hash.each do |key, val|
-
273
key = key.downcase.tr("-", "_").to_sym unless key.is_a?(Symbol)
-
-
234
case key
-
when :domain, :path
-
173
__send__(:"#{key}=", val)
-
else
-
77
instance_variable_set(:"@#{key}", val)
-
end
-
440
end if attr_hash
-
-
441
@path ||= "/"
-
441
raise ArgumentError, "name must be specified" if @name.nil?
-
-
441
@name = @name.to_s
-
end
-
-
7
def expires
-
665
@expires || (@created_at && @max_age ? @created_at + @max_age : nil)
-
end
-
-
7
def expired?(time = Time.now)
-
637
return false unless expires
-
-
28
expires <= time
-
end
-
-
# Returns a string for use in the Cookie header, i.e. `name=value`
-
# or `name="value"`.
-
7
def cookie_value
-
414
"#{@name}=#{Scanner.quote(@value.to_s)}"
-
end
-
7
alias_method :to_s, :cookie_value
-
-
# Tests if it is OK to send this cookie to a given `uri`. A
-
# RuntimeError is raised if the cookie's domain is unknown.
-
7
def valid_for_uri?(uri)
-
623
uri = URI(uri)
-
# RFC 6265 5.4
-
-
623
return false if @secure && uri.scheme != "https"
-
-
616
acceptable_from_uri?(uri) && Cookie.path_match?(@path, uri.path)
-
end
-
-
7
private
-
-
# Tests if it is OK to accept this cookie if it is sent from a given
-
# URI/URL, `uri`.
-
7
def acceptable_from_uri?(uri)
-
644
uri = URI(uri)
-
-
644
host = DomainName.new(uri.host)
-
-
# RFC 6265 5.3
-
644
if host.hostname == @domain
-
14
true
-
629
elsif @for_domain # !host-only-flag
-
28
host.cookie_domain?(@domain_name)
-
else
-
602
@domain.nil?
-
end
-
end
-
-
7
module Scanner
-
7
RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/.freeze
-
-
7
module_function
-
-
7
def quote(s)
-
483
return s unless s.match(RE_BAD_CHAR)
-
-
7
"\"#{s.gsub(/([\\"])/, "\\\\\\1")}\""
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins::Cookies
-
# The Cookie Jar
-
#
-
# It holds a bunch of cookies.
-
7
class Jar
-
7
using URIExtensions
-
-
7
include Enumerable
-
-
7
def initialize_dup(orig)
-
189
super
-
189
@cookies = orig.instance_variable_get(:@cookies).dup
-
end
-
-
7
def initialize(cookies = nil)
-
469
@cookies = []
-
-
120
cookies.each do |elem|
-
154
cookie = case elem
-
when Cookie
-
14
elem
-
when Array
-
126
Cookie.new(*elem)
-
else
-
14
Cookie.new(elem)
-
end
-
-
154
@cookies << cookie
-
468
end if cookies
-
end
-
-
7
def parse(set_cookie)
-
126
SetCookieParser.call(set_cookie) do |name, value, attrs|
-
182
add(Cookie.new(name, value, attrs))
-
end
-
end
-
-
7
def add(cookie, path = nil)
-
399
c = cookie.dup
-
-
399
c.path = path if path && c.path == "/"
-
-
# If the user agent receives a new cookie with the same cookie-name, domain-value, and path-value
-
# as a cookie that it has already stored, the existing cookie is evicted and replaced with the new cookie.
-
756
@cookies.delete_if { |ck| ck.name == c.name && ck.domain == c.domain && ck.path == c.path }
-
-
399
@cookies << c
-
end
-
-
7
def [](uri)
-
413
each(uri).sort
-
end
-
-
7
def each(uri = nil, &blk)
-
1036
return enum_for(__method__, uri) unless blk
-
-
595
return @cookies.each(&blk) unless uri
-
-
413
uri = URI(uri)
-
-
413
now = Time.now
-
413
tpath = uri.path
-
-
413
@cookies.delete_if do |cookie|
-
637
if cookie.expired?(now)
-
14
true
-
else
-
623
yield cookie if cookie.valid_for_uri?(uri) && Cookie.path_match?(cookie.path, tpath)
-
623
false
-
end
-
end
-
end
-
-
7
def merge(other)
-
175
cookies_dup = dup
-
-
175
other.each do |elem|
-
189
cookie = case elem
-
when Cookie
-
175
elem
-
when Array
-
7
Cookie.new(*elem)
-
else
-
7
Cookie.new(elem)
-
end
-
-
189
cookies_dup.add(cookie)
-
end
-
-
175
cookies_dup
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
7
require "strscan"
-
7
require "time"
-
-
7
module HTTPX
-
7
module Plugins::Cookies
-
7
module SetCookieParser
-
# Whitespace.
-
7
RE_WSP = /[ \t]+/.freeze
-
-
# A pattern that matches a cookie name or attribute name which may
-
# be empty, capturing trailing whitespace.
-
7
RE_NAME = /(?!#{RE_WSP})[^,;\\"=]*/.freeze
-
-
7
RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/.freeze
-
-
# A pattern that matches the comma in a (typically date) value.
-
7
RE_COOKIE_COMMA = /,(?=#{RE_WSP}?#{RE_NAME}=)/.freeze
-
-
7
module_function
-
-
7
def scan_dquoted(scanner)
-
14
s = +""
-
-
20
until scanner.eos?
-
56
break if scanner.skip(/"/)
-
-
42
if scanner.skip(/\\/)
-
14
s << scanner.getch
-
27
elsif scanner.scan(/[^"\\]+/)
-
28
s << scanner.matched
-
end
-
end
-
-
14
s
-
end
-
-
7
def scan_value(scanner, comma_as_separator = false)
-
385
value = +""
-
-
443
until scanner.eos?
-
665
if scanner.scan(/[^,;"]+/)
-
378
value << scanner.matched
-
286
elsif scanner.skip(/"/)
-
# RFC 6265 2.2
-
# A cookie-value may be DQUOTE'd.
-
14
value << scan_dquoted(scanner)
-
272
elsif scanner.check(/;/)
-
203
break
-
69
elsif comma_as_separator && scanner.check(RE_COOKIE_COMMA)
-
56
break
-
else
-
14
value << scanner.getch
-
end
-
end
-
-
385
value.rstrip!
-
385
value
-
end
-
-
7
def scan_name_value(scanner, comma_as_separator = false)
-
385
name = scanner.scan(RE_NAME)
-
385
name.rstrip! if name
-
-
385
if scanner.skip(/=/)
-
378
value = scan_value(scanner, comma_as_separator)
-
else
-
7
scan_value(scanner, comma_as_separator)
-
7
value = nil
-
end
-
385
[name, value]
-
end
-
-
7
def call(set_cookie)
-
126
scanner = StringScanner.new(set_cookie)
-
-
# RFC 6265 4.1.1 & 5.2
-
152
until scanner.eos?
-
182
start = scanner.pos
-
182
len = nil
-
-
182
scanner.skip(RE_WSP)
-
-
182
name, value = scan_name_value(scanner, true)
-
182
value = nil if name.empty?
-
-
182
attrs = {}
-
-
211
until scanner.eos?
-
259
if scanner.skip(/,/)
-
# The comma is used as separator for concatenating multiple
-
# values of a header.
-
56
len = (scanner.pos - 1) - start
-
56
break
-
202
elsif scanner.skip(/;/)
-
203
scanner.skip(RE_WSP)
-
-
203
aname, avalue = scan_name_value(scanner, true)
-
-
203
next if aname.empty? || value.nil?
-
-
203
aname.downcase!
-
-
174
case aname
-
when "expires"
-
# RFC 6265 5.2.1
-
14
(avalue &&= Time.parse(avalue)) || next
-
when "max-age"
-
# RFC 6265 5.2.2
-
7
next unless /\A-?\d+\z/.match?(avalue)
-
-
7
avalue = Integer(avalue)
-
when "domain"
-
# RFC 6265 5.2.3
-
# An empty value SHOULD be ignored.
-
21
next if avalue.nil? || avalue.empty?
-
when "path"
-
# RFC 6265 5.2.4
-
# A relative path must be ignored rather than normalizing it
-
# to "/".
-
154
next unless avalue.start_with?("/")
-
when "secure", "httponly"
-
# RFC 6265 5.2.5, 5.2.6
-
6
avalue = true
-
end
-
174
attrs[aname] = avalue
-
end
-
end
-
-
182
len ||= scanner.pos - start
-
-
182
next if len > Cookie::MAX_LENGTH
-
-
182
yield(name, value, attrs) if name && !name.empty? && value
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# This plugin adds helper methods to implement HTTP Digest Auth (https://datatracker.ietf.org/doc/html/rfc7616)
-
#
-
# https://gitlab.com/os85/httpx/wikis/Auth#digest-auth
-
#
-
7
module DigestAuth
-
7
DigestError = Class.new(Error)
-
-
7
class << self
-
7
def extra_options(options)
-
140
options.merge(max_concurrent_requests: 1)
-
end
-
-
7
def load_dependencies(*)
-
140
require_relative "auth/digest"
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :digest :: instance of HTTPX::Plugins::Authentication::Digest, used to authenticate requests in the session.
-
7
module OptionsMethods
-
7
def option_digest(value)
-
280
raise TypeError, ":digest must be a #{Authentication::Digest}" unless value.is_a?(Authentication::Digest)
-
-
280
value
-
end
-
end
-
-
7
module InstanceMethods
-
7
def digest_auth(user, password, hashed: false)
-
140
with(digest: Authentication::Digest.new(user, password, hashed: hashed))
-
end
-
-
7
private
-
-
7
def send_requests(*requests)
-
168
requests.flat_map do |request|
-
168
digest = request.options.digest
-
-
168
next super(request) unless digest
-
-
280
probe_response = wrap { super(request).first }
-
-
140
return probe_response unless probe_response.is_a?(Response)
-
-
140
if probe_response.status == 401 && digest.can_authenticate?(probe_response.headers["www-authenticate"])
-
126
request.transition(:idle)
-
108
request.headers["authorization"] = digest.authenticate(request, probe_response.headers["www-authenticate"])
-
126
super(request)
-
else
-
14
probe_response
-
end
-
end
-
end
-
end
-
end
-
-
7
register_plugin :digest_auth, DigestAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# This plugin makes all HTTP/1.1 requests with a body send the "Expect: 100-continue".
-
#
-
# https://gitlab.com/os85/httpx/wikis/Expect#expect
-
#
-
7
module Expect
-
7
EXPECT_TIMEOUT = 2
-
-
7
class << self
-
7
def no_expect_store
-
133
@no_expect_store ||= []
-
end
-
-
7
def extra_options(options)
-
168
options.merge(expect_timeout: EXPECT_TIMEOUT)
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :expect_timeout :: time (in seconds) to wait for a 100-expect response,
-
# before retrying without the Expect header (defaults to <tt>2</tt>).
-
# :expect_threshold_size :: min threshold (in bytes) of the request payload to enable the 100-continue negotiation on.
-
7
module OptionsMethods
-
7
def option_expect_timeout(value)
-
294
seconds = Float(value)
-
294
raise TypeError, ":expect_timeout must be positive" unless seconds.positive?
-
-
294
seconds
-
end
-
-
7
def option_expect_threshold_size(value)
-
14
bytes = Integer(value)
-
14
raise TypeError, ":expect_threshold_size must be positive" unless bytes.positive?
-
-
14
bytes
-
end
-
end
-
-
7
module RequestMethods
-
7
def initialize(*)
-
196
super
-
196
return if @body.empty?
-
-
126
threshold = @options.expect_threshold_size
-
126
return if threshold && !@body.unbounded_body? && @body.bytesize < threshold
-
-
112
return if Expect.no_expect_store.include?(origin)
-
-
90
@headers["expect"] = "100-continue"
-
end
-
-
7
def response=(response)
-
161
if response.is_a?(Response) &&
-
response.status == 100 &&
-
!@headers.key?("expect") &&
-
2
(@state == :body || @state == :done)
-
-
# if we're past this point, this means that we just received a 100-Continue response,
-
# but the request doesn't have the expect flag, and is already flushing (or flushed) the body.
-
#
-
# this means that expect was deactivated for this request too soon, i.e. response took longer.
-
#
-
# so we have to reactivate it again.
-
6
@headers["expect"] = "100-continue"
-
7
@informational_status = 100
-
7
Expect.no_expect_store.delete(origin)
-
end
-
161
super
-
end
-
end
-
-
7
module ConnectionMethods
-
7
def send_request_to_parser(request)
-
98
super
-
-
98
return unless request.headers["expect"] == "100-continue"
-
-
70
expect_timeout = request.options.expect_timeout
-
-
70
return if expect_timeout.nil? || expect_timeout.infinite?
-
-
70
set_request_timeout(request, expect_timeout, :expect, %i[body response]) do
-
# expect timeout expired
-
14
if request.state == :expect && !request.expects?
-
14
Expect.no_expect_store << request.origin
-
14
request.headers.delete("expect")
-
14
consume
-
end
-
end
-
end
-
end
-
-
7
module InstanceMethods
-
7
def fetch_response(request, connections, options)
-
364
response = @responses.delete(request)
-
364
return unless response
-
-
98
if response.is_a?(Response) && response.status == 417 && request.headers.key?("expect")
-
14
response.close
-
14
request.headers.delete("expect")
-
14
request.transition(:idle)
-
14
send_request(request, connections, options)
-
12
return
-
end
-
-
84
response
-
end
-
end
-
end
-
7
register_plugin :expect, Expect
-
end
-
end
-
# frozen_string_literal: true
-
-
13
module HTTPX
-
13
InsecureRedirectError = Class.new(Error)
-
13
module Plugins
-
#
-
# This plugin adds support for automatically following redirect (status 30X) responses.
-
#
-
# It has a default upper bound of followed redirects (see *MAX_REDIRECTS* and the *max_redirects* option),
-
# after which it will return the last redirect response. It will **not** raise an exception.
-
#
-
# It doesn't follow insecure redirects (https -> http) by default (see *follow_insecure_redirects*).
-
#
-
# It doesn't propagate authorization related headers to requests redirecting to different origins
-
# (see *allow_auth_to_other_origins*) to override.
-
#
-
# It allows customization of when to redirect via the *redirect_on* callback option).
-
#
-
# https://gitlab.com/os85/httpx/wikis/Follow-Redirects
-
#
-
13
module FollowRedirects
-
13
MAX_REDIRECTS = 3
-
13
REDIRECT_STATUS = (300..399).freeze
-
13
REQUEST_BODY_HEADERS = %w[transfer-encoding content-encoding content-type content-length content-language content-md5 trailer].freeze
-
-
13
using URIExtensions
-
-
# adds support for the following options:
-
#
-
# :max_redirects :: max number of times a request will be redirected (defaults to <tt>3</tt>).
-
# :follow_insecure_redirects :: whether redirects to an "http://" URI, when coming from an "https//", are allowed
-
# (defaults to <tt>false</tt>).
-
# :allow_auth_to_other_origins :: whether auth-related headers, such as "Authorization", are propagated on redirection
-
# (defaults to <tt>false</tt>).
-
# :redirect_on :: optional callback which receives the redirect location and can halt the redirect chain if it returns <tt>false</tt>.
-
13
module OptionsMethods
-
13
def option_max_redirects(value)
-
403
num = Integer(value)
-
403
raise TypeError, ":max_redirects must be positive" if num.negative?
-
-
403
num
-
end
-
-
13
def option_follow_insecure_redirects(value)
-
21
value
-
end
-
-
13
def option_allow_auth_to_other_origins(value)
-
21
value
-
end
-
-
13
def option_redirect_on(value)
-
42
raise TypeError, ":redirect_on must be callable" unless value.respond_to?(:call)
-
-
42
value
-
end
-
end
-
-
13
module InstanceMethods
-
# returns a session with the *max_redirects* option set to +n+
-
13
def max_redirects(n)
-
42
with(max_redirects: n.to_i)
-
end
-
-
13
private
-
-
13
def fetch_response(request, connections, options)
-
133974
redirect_request = request.redirect_request
-
133974
response = super(redirect_request, connections, options)
-
133974
return unless response
-
-
495
max_redirects = redirect_request.max_redirects
-
-
495
return response unless response.is_a?(Response)
-
481
return response unless REDIRECT_STATUS.include?(response.status) && response.headers.key?("location")
-
314
return response unless max_redirects.positive?
-
-
286
redirect_uri = __get_location_from_response(response)
-
-
286
if options.redirect_on
-
28
redirect_allowed = options.redirect_on.call(redirect_uri)
-
28
return response unless redirect_allowed
-
end
-
-
# build redirect request
-
272
request_body = redirect_request.body
-
272
redirect_method = "GET"
-
272
redirect_params = {}
-
-
272
if response.status == 305 && options.respond_to?(:proxy)
-
7
request_body.rewind
-
# The requested resource MUST be accessed through the proxy given by
-
# the Location field. The Location field gives the URI of the proxy.
-
7
redirect_options = options.merge(headers: redirect_request.headers,
-
proxy: { uri: redirect_uri },
-
max_redirects: max_redirects - 1)
-
-
6
redirect_params[:body] = request_body
-
7
redirect_uri = redirect_request.uri
-
7
options = redirect_options
-
else
-
265
redirect_headers = redirect_request_headers(redirect_request.uri, redirect_uri, request.headers, options)
-
265
redirect_opts = Hash[options]
-
228
redirect_params[:max_redirects] = max_redirects - 1
-
-
265
unless request_body.empty?
-
21
if response.status == 307
-
# The method and the body of the original request are reused to perform the redirected request.
-
7
redirect_method = redirect_request.verb
-
7
request_body.rewind
-
6
redirect_params[:body] = request_body
-
else
-
# redirects are **ALWAYS** GET, so remove body-related headers
-
14
REQUEST_BODY_HEADERS.each do |h|
-
98
redirect_headers.delete(h)
-
end
-
12
redirect_params[:body] = nil
-
end
-
end
-
-
265
options = options.class.new(redirect_opts.merge(headers: redirect_headers.to_h))
-
end
-
-
272
redirect_uri = Utils.to_uri(redirect_uri)
-
-
272
if !options.follow_insecure_redirects &&
-
response.uri.scheme == "https" &&
-
redirect_uri.scheme == "http"
-
7
error = InsecureRedirectError.new(redirect_uri.to_s)
-
7
error.set_backtrace(caller)
-
6
return ErrorResponse.new(request, error)
-
end
-
-
265
retry_request = build_request(redirect_method, redirect_uri, redirect_params, options)
-
-
265
request.redirect_request = retry_request
-
-
265
redirect_after = response.headers["retry-after"]
-
-
265
if redirect_after
-
# Servers send the "Retry-After" header field to indicate how long the
-
# user agent ought to wait before making a follow-up request.
-
# When sent with any 3xx (Redirection) response, Retry-After indicates
-
# the minimum time that the user agent is asked to wait before issuing
-
# the redirected request.
-
#
-
25
redirect_after = Utils.parse_retry_after(redirect_after)
-
-
25
log { "redirecting after #{redirect_after} secs..." }
-
-
25
deactivate_connection(request, connections, options)
-
-
25
pool.after(redirect_after) do
-
25
if request.response
-
# request has terminated abruptly meanwhile
-
11
retry_request.emit(:response, request.response)
-
else
-
14
send_request(retry_request, connections, options)
-
end
-
end
-
else
-
240
send_request(retry_request, connections, options)
-
end
-
74
nil
-
end
-
-
# :nodoc:
-
13
def redirect_request_headers(original_uri, redirect_uri, headers, options)
-
265
headers = headers.dup
-
-
265
return headers if options.allow_auth_to_other_origins
-
-
258
return headers unless headers.key?("authorization")
-
-
7
return headers if original_uri.origin == redirect_uri.origin
-
-
7
headers.delete("authorization")
-
-
7
headers
-
end
-
-
# :nodoc:
-
13
def __get_location_from_response(response)
-
# @type var location_uri: http_uri
-
286
location_uri = URI(response.headers["location"])
-
286
location_uri = response.uri.merge(location_uri) if location_uri.relative?
-
286
location_uri
-
end
-
end
-
-
13
module RequestMethods
-
# returns the top-most original HTTPX::Request from the redirect chain
-
13
attr_accessor :root_request
-
-
# returns the follow-up redirect request, or itself
-
13
def redirect_request
-
133974
@redirect_request || self
-
end
-
-
# sets the follow-up redirect request
-
13
def redirect_request=(req)
-
265
@redirect_request = req
-
265
req.root_request = @root_request || self
-
265
@response = nil
-
end
-
-
13
def response
-
1639
return super unless @redirect_request && @response.nil?
-
-
57
@redirect_request.response
-
end
-
-
13
def max_redirects
-
495
@options.max_redirects || MAX_REDIRECTS
-
end
-
end
-
-
13
module ConnectionMethods
-
13
private
-
-
13
def set_request_request_timeout(request)
-
474
return unless request.root_request.nil?
-
-
225
super
-
end
-
end
-
end
-
13
register_plugin :follow_redirects, FollowRedirects
-
end
-
end
-
# frozen_string_literal: true
-
-
5
module HTTPX
-
5
GRPCError = Class.new(Error) do
-
5
attr_reader :status, :details, :metadata
-
-
5
def initialize(status, details, metadata)
-
20
@status = status
-
20
@details = details
-
20
@metadata = metadata
-
20
super("GRPC error, code=#{status}, details=#{details}, metadata=#{metadata}")
-
end
-
end
-
-
5
module Plugins
-
#
-
# This plugin adds DSL to build GRPC interfaces.
-
#
-
# https://gitlab.com/os85/httpx/wikis/GRPC
-
#
-
5
module GRPC
-
5
unless String.method_defined?(:underscore)
-
5
module StringExtensions
-
5
refine String do
-
5
def underscore
-
260
s = dup # Avoid mutating the argument, as it might be frozen.
-
260
s.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
-
260
s.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
-
260
s.tr!("-", "_")
-
260
s.downcase!
-
260
s
-
end
-
end
-
end
-
5
using StringExtensions
-
end
-
-
5
DEADLINE = 60
-
5
MARSHAL_METHOD = :encode
-
5
UNMARSHAL_METHOD = :decode
-
5
HEADERS = {
-
"content-type" => "application/grpc",
-
"te" => "trailers",
-
"accept" => "application/grpc",
-
# metadata fits here
-
# ex "foo-bin" => base64("bar")
-
}.freeze
-
-
5
class << self
-
5
def load_dependencies(*)
-
115
require "stringio"
-
115
require "httpx/plugins/grpc/grpc_encoding"
-
115
require "httpx/plugins/grpc/message"
-
115
require "httpx/plugins/grpc/call"
-
end
-
-
5
def configure(klass)
-
115
klass.plugin(:persistent)
-
115
klass.plugin(:stream)
-
end
-
-
5
def extra_options(options)
-
115
options.merge(
-
fallback_protocol: "h2",
-
grpc_rpcs: {}.freeze,
-
grpc_compression: false,
-
grpc_deadline: DEADLINE
-
)
-
end
-
end
-
-
5
module OptionsMethods
-
5
def option_grpc_service(value)
-
100
String(value)
-
end
-
-
5
def option_grpc_compression(value)
-
135
case value
-
when true, false
-
115
value
-
else
-
20
value.to_s
-
end
-
end
-
-
5
def option_grpc_rpcs(value)
-
930
Hash[value]
-
end
-
-
5
def option_grpc_deadline(value)
-
670
raise TypeError, ":grpc_deadline must be positive" unless value.positive?
-
-
670
value
-
end
-
-
5
def option_call_credentials(value)
-
15
raise TypeError, ":call_credentials must respond to #call" unless value.respond_to?(:call)
-
-
15
value
-
end
-
end
-
-
5
module ResponseMethods
-
5
attr_reader :trailing_metadata
-
-
5
def merge_headers(trailers)
-
95
@trailing_metadata = Hash[trailers]
-
95
super
-
end
-
end
-
-
5
module RequestBodyMethods
-
5
def initialize(*, **)
-
105
super
-
-
105
if (compression = @headers["grpc-encoding"])
-
10
deflater_body = self.class.initialize_deflater_body(@body, compression)
-
10
@body = Transcoder::GRPCEncoding.encode(deflater_body || @body, compressed: !deflater_body.nil?)
-
else
-
95
@body = Transcoder::GRPCEncoding.encode(@body, compressed: false)
-
end
-
end
-
end
-
-
5
module InstanceMethods
-
5
def with_channel_credentials(ca_path, key = nil, cert = nil, **ssl_opts)
-
# @type var ssl_params: ::Hash[::Symbol, untyped]
-
60
ssl_params = {
-
**ssl_opts,
-
ca_file: ca_path,
-
}
-
60
if key
-
60
key = File.read(key) if File.file?(key)
-
60
ssl_params[:key] = OpenSSL::PKey.read(key)
-
end
-
-
60
if cert
-
60
cert = File.read(cert) if File.file?(cert)
-
60
ssl_params[:cert] = OpenSSL::X509::Certificate.new(cert)
-
end
-
-
60
with(ssl: ssl_params)
-
end
-
-
5
def rpc(rpc_name, input, output, **opts)
-
260
rpc_name = rpc_name.to_s
-
260
raise Error, "rpc #{rpc_name} already defined" if @options.grpc_rpcs.key?(rpc_name)
-
-
rpc_opts = {
-
260
deadline: @options.grpc_deadline,
-
}.merge(opts)
-
-
260
local_rpc_name = rpc_name.underscore
-
-
260
session_class = Class.new(self.class) do
-
# define rpc method with ruby style name
-
260
class_eval(<<-OUT, __FILE__, __LINE__ + 1)
-
def #{local_rpc_name}(input, **opts) # def grpc_action(input, **opts)
-
rpc_execute("#{local_rpc_name}", input, **opts) # rpc_execute("grpc_action", input, **opts)
-
end # end
-
OUT
-
-
# define rpc method with original name
-
260
unless local_rpc_name == rpc_name
-
10
class_eval(<<-OUT, __FILE__, __LINE__ + 1)
-
def #{rpc_name}(input, **opts) # def grpcAction(input, **opts)
-
rpc_execute("#{local_rpc_name}", input, **opts) # rpc_execute("grpc_action", input, **opts)
-
end # end
-
OUT
-
end
-
end
-
-
260
session_class.new(@options.merge(
-
grpc_rpcs: @options.grpc_rpcs.merge(
-
local_rpc_name => [rpc_name, input, output, rpc_opts]
-
).freeze
-
))
-
end
-
-
5
def build_stub(origin, service: nil, compression: false)
-
115
scheme = @options.ssl.empty? ? "http" : "https"
-
-
115
origin = URI.parse("#{scheme}://#{origin}")
-
-
115
session = self
-
-
115
if service && service.respond_to?(:rpc_descs)
-
# it's a grpc generic service
-
50
service.rpc_descs.each do |rpc_name, rpc_desc|
-
rpc_opts = {
-
250
marshal_method: rpc_desc.marshal_method,
-
unmarshal_method: rpc_desc.unmarshal_method,
-
}
-
-
250
input = rpc_desc.input
-
250
input = input.type if input.respond_to?(:type)
-
-
250
output = rpc_desc.output
-
250
if output.respond_to?(:type)
-
100
rpc_opts[:stream] = true
-
100
output = output.type
-
end
-
-
250
session = session.rpc(rpc_name, input, output, **rpc_opts)
-
end
-
-
50
service = service.service_name
-
end
-
-
115
session.with(origin: origin, grpc_service: service, grpc_compression: compression)
-
end
-
-
5
def execute(rpc_method, input,
-
deadline: DEADLINE,
-
metadata: nil,
-
**opts)
-
105
grpc_request = build_grpc_request(rpc_method, input, deadline: deadline, metadata: metadata, **opts)
-
105
response = request(grpc_request, **opts)
-
105
response.raise_for_status unless opts[:stream]
-
95
GRPC::Call.new(response)
-
end
-
-
5
private
-
-
5
def rpc_execute(rpc_name, input, **opts)
-
50
rpc_name, input_enc, output_enc, rpc_opts = @options.grpc_rpcs[rpc_name]
-
-
50
exec_opts = rpc_opts.merge(opts)
-
-
50
marshal_method ||= exec_opts.delete(:marshal_method) || MARSHAL_METHOD
-
50
unmarshal_method ||= exec_opts.delete(:unmarshal_method) || UNMARSHAL_METHOD
-
-
50
messages = if input.respond_to?(:each)
-
20
Enumerator.new do |y|
-
20
input.each do |message|
-
40
y << input_enc.__send__(marshal_method, message)
-
end
-
end
-
else
-
30
input_enc.__send__(marshal_method, input)
-
end
-
-
50
call = execute(rpc_name, messages, **exec_opts)
-
-
50
call.decoder = output_enc.method(unmarshal_method)
-
-
50
call
-
end
-
-
5
def build_grpc_request(rpc_method, input, deadline:, metadata: nil, **)
-
105
uri = @options.origin.dup
-
105
rpc_method = "/#{rpc_method}" unless rpc_method.start_with?("/")
-
105
rpc_method = "/#{@options.grpc_service}#{rpc_method}" if @options.grpc_service
-
105
uri.path = rpc_method
-
-
105
headers = HEADERS.merge(
-
"grpc-accept-encoding" => ["identity", *@options.supported_compression_formats]
-
)
-
105
unless deadline == Float::INFINITY
-
# convert to milliseconds
-
105
deadline = (deadline * 1000.0).to_i
-
105
headers["grpc-timeout"] = "#{deadline}m"
-
end
-
-
105
headers = headers.merge(metadata.transform_keys(&:to_s)) if metadata
-
-
# prepare compressor
-
105
compression = @options.grpc_compression == true ? "gzip" : @options.grpc_compression
-
-
105
headers["grpc-encoding"] = compression if compression
-
-
105
headers.merge!(@options.call_credentials.call.transform_keys(&:to_s)) if @options.call_credentials
-
-
105
build_request("POST", uri, headers: headers, body: input)
-
end
-
end
-
end
-
5
register_plugin :grpc, GRPC
-
end
-
end
-
# frozen_string_literal: true
-
-
5
module HTTPX
-
5
module Plugins
-
5
module GRPC
-
# Encapsulates call information
-
5
class Call
-
5
attr_writer :decoder
-
-
5
def initialize(response)
-
95
@response = response
-
130
@decoder = ->(z) { z }
-
95
@consumed = false
-
95
@grpc_response = nil
-
end
-
-
5
def inspect
-
"#GRPC::Call(#{grpc_response})"
-
end
-
-
5
def to_s
-
55
grpc_response.to_s
-
end
-
-
5
def metadata
-
response.headers
-
end
-
-
5
def trailing_metadata
-
60
return unless @consumed
-
-
40
@response.trailing_metadata
-
end
-
-
5
private
-
-
5
def grpc_response
-
155
@grpc_response ||= if @response.respond_to?(:each)
-
20
Enumerator.new do |y|
-
20
Message.stream(@response).each do |message|
-
40
y << @decoder.call(message)
-
end
-
20
@consumed = true
-
end
-
else
-
75
@consumed = true
-
75
@decoder.call(Message.unary(@response))
-
end
-
end
-
-
5
def respond_to_missing?(meth, *args, &blk)
-
20
grpc_response.respond_to?(meth, *args) || super
-
end
-
-
5
def method_missing(meth, *args, &blk)
-
40
return grpc_response.__send__(meth, *args, &blk) if grpc_response.respond_to?(meth)
-
-
super
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
5
module HTTPX
-
5
module Transcoder
-
5
module GRPCEncoding
-
5
class Deflater
-
5
extend Forwardable
-
-
5
attr_reader :content_type
-
-
5
def initialize(body, compressed:)
-
105
@content_type = body.content_type
-
105
@body = BodyReader.new(body)
-
105
@compressed = compressed
-
end
-
-
5
def bytesize
-
335
return @body.bytesize if @body.respond_to?(:bytesize)
-
-
Float::INFINITY
-
end
-
-
5
def read(length = nil, outbuf = nil)
-
220
buf = @body.read(length, outbuf)
-
-
210
return unless buf
-
-
115
compressed_flag = @compressed ? 1 : 0
-
-
115
buf = outbuf if outbuf
-
-
115
buf.prepend([compressed_flag, buf.bytesize].pack("CL>"))
-
115
buf
-
end
-
end
-
-
5
class Inflater
-
5
def initialize(response)
-
75
@response = response
-
75
@grpc_encodings = nil
-
end
-
-
5
def call(message, &blk)
-
95
data = "".b
-
-
95
until message.empty?
-
95
compressed, size = message.unpack("CL>")
-
-
95
encoded_data = message.byteslice(5..size + 5 - 1)
-
-
95
if compressed == 1
-
10
grpc_encodings.reverse_each do |encoding|
-
10
decoder = @response.body.class.initialize_inflater_by_encoding(encoding, @response, bytesize: encoded_data.bytesize)
-
10
encoded_data = decoder.call(encoded_data)
-
-
10
blk.call(encoded_data) if blk
-
-
10
data << encoded_data
-
end
-
else
-
85
blk.call(encoded_data) if blk
-
-
85
data << encoded_data
-
end
-
-
95
message = message.byteslice((size + 5)..-1)
-
end
-
-
95
data
-
end
-
-
5
private
-
-
5
def grpc_encodings
-
10
@grpc_encodings ||= @response.headers.get("grpc-encoding")
-
end
-
end
-
-
5
def self.encode(*args, **kwargs)
-
105
Deflater.new(*args, **kwargs)
-
end
-
-
5
def self.decode(response)
-
75
Inflater.new(response)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
5
module HTTPX
-
5
module Plugins
-
5
module GRPC
-
# Encoding module for GRPC responses
-
#
-
# Can encode and decode grpc messages.
-
5
module Message
-
5
module_function
-
-
# decodes a unary grpc response
-
5
def unary(response)
-
75
verify_status(response)
-
-
55
decoder = Transcoder::GRPCEncoding.decode(response)
-
-
55
decoder.call(response.to_s)
-
end
-
-
# lazy decodes a grpc stream response
-
5
def stream(response, &block)
-
40
return enum_for(__method__, response) unless block
-
-
20
decoder = Transcoder::GRPCEncoding.decode(response)
-
-
20
response.each do |frame|
-
40
decoder.call(frame, &block)
-
end
-
-
20
verify_status(response)
-
end
-
-
5
def cancel(request)
-
request.emit(:refuse, :client_cancellation)
-
end
-
-
# interprets the grpc call trailing metadata, and raises an
-
# exception in case of error code
-
5
def verify_status(response)
-
# return standard errors if need be
-
95
response.raise_for_status
-
-
95
status = Integer(response.headers["grpc-status"])
-
95
message = response.headers["grpc-message"]
-
-
95
return if status.zero?
-
-
20
response.close
-
20
raise GRPCError.new(status, message, response.trailing_metadata)
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# This plugin adds support for upgrading a plaintext HTTP/1.1 connection to HTTP/2
-
# (https://datatracker.ietf.org/doc/html/rfc7540#section-3.2)
-
#
-
# https://gitlab.com/os85/httpx/wikis/Connection-Upgrade#h2c
-
#
-
7
module H2C
-
7
VALID_H2C_VERBS = %w[GET OPTIONS HEAD].freeze
-
-
7
class << self
-
7
def load_dependencies(klass)
-
14
klass.plugin(:upgrade)
-
end
-
-
7
def call(connection, request, response)
-
14
connection.upgrade_to_h2c(request, response)
-
end
-
-
7
def extra_options(options)
-
14
options.merge(max_concurrent_requests: 1, upgrade_handlers: options.upgrade_handlers.merge("h2c" => self))
-
end
-
end
-
-
7
module InstanceMethods
-
7
def send_requests(*requests)
-
21
upgrade_request, *remainder = requests
-
-
21
return super unless VALID_H2C_VERBS.include?(upgrade_request.verb) && upgrade_request.scheme == "http"
-
-
21
connection = pool.find_connection(upgrade_request.uri, upgrade_request.options)
-
-
21
return super if connection && connection.upgrade_protocol == "h2c"
-
-
# build upgrade request
-
14
upgrade_request.headers.add("connection", "upgrade")
-
14
upgrade_request.headers.add("connection", "http2-settings")
-
12
upgrade_request.headers["upgrade"] = "h2c"
-
12
upgrade_request.headers["http2-settings"] = ::HTTP2::Client.settings_header(upgrade_request.options.http2_settings)
-
-
14
super(upgrade_request, *remainder)
-
end
-
end
-
-
7
class H2CParser < Connection::HTTP2
-
7
def upgrade(request, response)
-
# skip checks, it is assumed that this is the first
-
# request in the connection
-
14
stream = @connection.upgrade
-
-
# on_settings
-
14
handle_stream(stream, request)
-
12
@streams[request] = stream
-
-
# clean up data left behind in the buffer, if the server started
-
# sending frames
-
14
data = response.read
-
14
@connection << data
-
end
-
end
-
-
7
module ConnectionMethods
-
7
using URIExtensions
-
-
7
def upgrade_to_h2c(request, response)
-
14
prev_parser = @parser
-
-
14
if prev_parser
-
14
prev_parser.reset
-
12
@inflight -= prev_parser.requests.size
-
end
-
-
14
@parser = H2CParser.new(@write_buffer, @options)
-
14
set_parser_callbacks(@parser)
-
12
@inflight += 1
-
14
@parser.upgrade(request, response)
-
14
@upgrade_protocol = "h2c"
-
-
14
prev_parser.requests.each do |req|
-
14
req.transition(:idle)
-
14
send(req)
-
end
-
end
-
-
7
private
-
-
7
def send_request_to_parser(request)
-
49
super
-
-
49
return unless request.headers["upgrade"] == "h2c" && parser.is_a?(Connection::HTTP1)
-
-
14
max_concurrent_requests = parser.max_concurrent_requests
-
-
14
return if max_concurrent_requests == 1
-
-
parser.max_concurrent_requests = 1
-
request.once(:response) do
-
parser.max_concurrent_requests = max_concurrent_requests
-
end
-
end
-
end
-
end
-
7
register_plugin(:h2c, H2C)
-
end
-
end
-
# frozen_string_literal: true
-
-
5
module HTTPX
-
5
module Plugins
-
#
-
# https://gitlab.com/os85/httpx/wikis/Auth#ntlm-auth
-
#
-
5
module NTLMAuth
-
5
class << self
-
5
def load_dependencies(_klass)
-
2
require_relative "auth/ntlm"
-
end
-
-
5
def extra_options(options)
-
2
options.merge(max_concurrent_requests: 1)
-
end
-
end
-
-
5
module OptionsMethods
-
5
def option_ntlm(value)
-
8
raise TypeError, ":ntlm must be a #{Authentication::Ntlm}" unless value.is_a?(Authentication::Ntlm)
-
-
8
value
-
end
-
end
-
-
5
module InstanceMethods
-
5
def ntlm_auth(user, password, domain = nil)
-
4
with(ntlm: Authentication::Ntlm.new(user, password, domain: domain))
-
end
-
-
5
private
-
-
5
def send_requests(*requests)
-
8
requests.flat_map do |request|
-
8
ntlm = request.options.ntlm
-
-
8
if ntlm
-
4
request.headers["authorization"] = ntlm.negotiate
-
8
probe_response = wrap { super(request).first }
-
-
4
return probe_response unless probe_response.is_a?(Response)
-
-
4
if probe_response.status == 401 && ntlm.can_authenticate?(probe_response.headers["www-authenticate"])
-
2
request.transition(:idle)
-
2
request.headers["authorization"] = ntlm.authenticate(request, probe_response.headers["www-authenticate"])
-
2
super(request)
-
else
-
2
probe_response
-
end
-
else
-
4
super(request)
-
end
-
end
-
end
-
end
-
end
-
5
register_plugin :ntlm_auth, NTLMAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# https://gitlab.com/os85/httpx/wikis/OAuth
-
#
-
7
module OAuth
-
7
class << self
-
7
def load_dependencies(_klass)
-
70
require_relative "auth/basic"
-
end
-
end
-
-
7
SUPPORTED_GRANT_TYPES = %w[client_credentials refresh_token].freeze
-
7
SUPPORTED_AUTH_METHODS = %w[client_secret_basic client_secret_post].freeze
-
-
7
class OAuthSession
-
7
attr_reader :grant_type, :client_id, :client_secret, :access_token, :refresh_token, :scope
-
-
7
def initialize(
-
issuer:,
-
client_id:,
-
client_secret:,
-
access_token: nil,
-
refresh_token: nil,
-
scope: nil,
-
token_endpoint: nil,
-
response_type: nil,
-
grant_type: nil,
-
token_endpoint_auth_method: nil
-
)
-
70
@issuer = URI(issuer)
-
70
@client_id = client_id
-
70
@client_secret = client_secret
-
70
@token_endpoint = URI(token_endpoint) if token_endpoint
-
70
@response_type = response_type
-
70
@scope = case scope
-
when String
-
28
scope.split
-
when Array
-
28
scope
-
end
-
70
@access_token = access_token
-
70
@refresh_token = refresh_token
-
70
@token_endpoint_auth_method = String(token_endpoint_auth_method) if token_endpoint_auth_method
-
70
@grant_type = grant_type || (@refresh_token ? "refresh_token" : "client_credentials")
-
-
70
unless @token_endpoint_auth_method.nil? || SUPPORTED_AUTH_METHODS.include?(@token_endpoint_auth_method)
-
14
raise Error, "#{@token_endpoint_auth_method} is not a supported auth method"
-
end
-
-
56
return if SUPPORTED_GRANT_TYPES.include?(@grant_type)
-
-
raise Error, "#{@grant_type} is not a supported grant type"
-
end
-
-
7
def token_endpoint
-
56
@token_endpoint || "#{@issuer}/token"
-
end
-
-
7
def token_endpoint_auth_method
-
84
@token_endpoint_auth_method || "client_secret_basic"
-
end
-
-
7
def load(http)
-
28
return if @grant_type && @scope
-
-
metadata = http.get("#{@issuer}/.well-known/oauth-authorization-server").raise_for_status.json
-
-
@token_endpoint = metadata["token_endpoint"]
-
@scope = metadata["scopes_supported"]
-
@grant_type = Array(metadata["grant_types_supported"]).find { |gr| SUPPORTED_GRANT_TYPES.include?(gr) }
-
@token_endpoint_auth_method = Array(metadata["token_endpoint_auth_methods_supported"]).find do |am|
-
SUPPORTED_AUTH_METHODS.include?(am)
-
end
-
nil
-
end
-
-
7
def merge(other)
-
56
obj = dup
-
-
48
case other
-
when OAuthSession
-
28
other.instance_variables.each do |ivar|
-
238
val = other.instance_variable_get(ivar)
-
238
next unless val
-
-
182
obj.instance_variable_set(ivar, val)
-
end
-
when Hash
-
28
other.each do |k, v|
-
56
obj.instance_variable_set(:"@#{k}", v) if obj.instance_variable_defined?(:"@#{k}")
-
end
-
end
-
56
obj
-
end
-
end
-
-
7
module OptionsMethods
-
7
def option_oauth_session(value)
-
144
case value
-
when Hash
-
OAuthSession.new(**value)
-
when OAuthSession
-
168
value
-
else
-
raise TypeError, ":oauth_session must be a #{OAuthSession}"
-
end
-
end
-
end
-
-
7
module InstanceMethods
-
7
def oauth_auth(**args)
-
70
with(oauth_session: OAuthSession.new(**args))
-
end
-
-
7
def with_access_token
-
28
oauth_session = @options.oauth_session
-
-
28
oauth_session.load(self)
-
-
28
grant_type = oauth_session.grant_type
-
-
28
headers = {}
-
28
form_post = { "grant_type" => grant_type, "scope" => Array(oauth_session.scope).join(" ") }.compact
-
-
# auth
-
24
case oauth_session.token_endpoint_auth_method
-
when "client_secret_post"
-
12
form_post["client_id"] = oauth_session.client_id
-
12
form_post["client_secret"] = oauth_session.client_secret
-
when "client_secret_basic"
-
12
headers["authorization"] = Authentication::Basic.new(oauth_session.client_id, oauth_session.client_secret).authenticate
-
end
-
-
24
case grant_type
-
when "client_credentials"
-
# do nothing
-
when "refresh_token"
-
12
form_post["refresh_token"] = oauth_session.refresh_token
-
end
-
-
28
token_request = build_request("POST", oauth_session.token_endpoint, headers: headers, form: form_post)
-
28
token_request.headers.delete("authorization") unless oauth_session.token_endpoint_auth_method == "client_secret_basic"
-
-
28
token_response = request(token_request)
-
28
token_response.raise_for_status
-
-
28
payload = token_response.json
-
-
28
access_token = payload["access_token"]
-
28
refresh_token = payload["refresh_token"]
-
-
28
with(oauth_session: oauth_session.merge(access_token: access_token, refresh_token: refresh_token))
-
end
-
-
7
def build_request(*)
-
84
request = super
-
-
84
return request if request.headers.key?("authorization")
-
-
70
oauth_session = @options.oauth_session
-
-
70
return request unless oauth_session && oauth_session.access_token
-
-
48
request.headers["authorization"] = "Bearer #{oauth_session.access_token}"
-
-
56
request
-
end
-
end
-
end
-
7
register_plugin :oauth, OAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
9
module HTTPX
-
9
module Plugins
-
# This plugin implements a session that persists connections over the duration of the process.
-
#
-
# This will improve connection reuse in a long-running process.
-
#
-
# One important caveat to note is, although this session might not close connections,
-
# other sessions from the same process that don't have this plugin turned on might.
-
#
-
# This session will still be able to work with it, as if, when expecting a connection
-
# terminated by a different session, it will just retry on a new one and keep it open.
-
#
-
# This plugin is also not recommendable when connecting to >9000 (like, a lot) different origins.
-
# So when you use this, make sure that you don't fall into this trap.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Persistent
-
#
-
9
module Persistent
-
9
def self.load_dependencies(klass)
-
354
max_retries = if klass.default_options.respond_to?(:max_retries)
-
7
[klass.default_options.max_retries, 1].max
-
else
-
347
1
-
end
-
354
klass.plugin(:retries, max_retries: max_retries, retry_change_requests: true)
-
end
-
-
9
def self.extra_options(options)
-
354
options.merge(persistent: true)
-
end
-
end
-
9
register_plugin :persistent, Persistent
-
end
-
end
-
# frozen_string_literal: true
-
-
9
module HTTPX
-
9
class HTTPProxyError < ConnectionError; end
-
-
9
module Plugins
-
#
-
# This plugin adds support for proxies. It ships with support for:
-
#
-
# * HTTP proxies
-
# * HTTPS proxies
-
# * Socks4/4a proxies
-
# * Socks5 proxies
-
#
-
# https://gitlab.com/os85/httpx/wikis/Proxy
-
#
-
9
module Proxy
-
9
Error = HTTPProxyError
-
9
PROXY_ERRORS = [TimeoutError, IOError, SystemCallError, Error].freeze
-
-
9
class << self
-
9
def configure(klass)
-
295
klass.plugin(:"proxy/http")
-
295
klass.plugin(:"proxy/socks4")
-
295
klass.plugin(:"proxy/socks5")
-
end
-
-
9
def extra_options(options)
-
295
options.merge(supported_proxy_protocols: [])
-
end
-
end
-
-
9
class Parameters
-
9
attr_reader :uri, :username, :password, :scheme
-
-
9
def initialize(uri:, scheme: nil, username: nil, password: nil, **extra)
-
377
@uri = uri.is_a?(URI::Generic) ? uri : URI(uri)
-
377
@username = username || @uri.user
-
377
@password = password || @uri.password
-
-
377
return unless @username && @password
-
-
222
scheme ||= case @uri.scheme
-
when "socks5"
-
42
@uri.scheme
-
when "http", "https"
-
97
"basic"
-
else
-
42
return
-
end
-
-
180
@scheme = scheme
-
-
180
auth_scheme = scheme.to_s.capitalize
-
-
180
require_relative "auth/#{scheme}" unless defined?(Authentication) && Authentication.const_defined?(auth_scheme, false)
-
-
180
@authenticator = Authentication.const_get(auth_scheme).new(@username, @password, **extra)
-
end
-
-
9
def can_authenticate?(*args)
-
154
return false unless @authenticator
-
-
56
@authenticator.can_authenticate?(*args)
-
end
-
-
9
def authenticate(*args)
-
139
return unless @authenticator
-
-
139
@authenticator.authenticate(*args)
-
end
-
-
9
def ==(other)
-
71
case other
-
when Parameters
-
53
@uri == other.uri &&
-
@username == other.username &&
-
@password == other.password &&
-
@scheme == other.scheme
-
when URI::Generic, String
-
21
proxy_uri = @uri.dup
-
21
proxy_uri.user = @username
-
21
proxy_uri.password = @password
-
21
other_uri = other.is_a?(URI::Generic) ? other : URI.parse(other)
-
21
proxy_uri == other_uri
-
else
-
7
super
-
end
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :proxy :: proxy options defining *:uri*, *:username*, *:password* or
-
# *:scheme* (i.e. <tt>{ uri: "http://proxy" }</tt>)
-
9
module OptionsMethods
-
9
def option_proxy(value)
-
933
value.is_a?(Parameters) ? value : Hash[value]
-
end
-
-
9
def option_supported_proxy_protocols(value)
-
1487
raise TypeError, ":supported_proxy_protocols must be an Array" unless value.is_a?(Array)
-
-
1487
value.map(&:to_s)
-
end
-
end
-
-
9
module InstanceMethods
-
9
private
-
-
9
def find_connection(request, connections, options)
-
365
return super unless options.respond_to?(:proxy)
-
-
365
uri = request.uri
-
-
365
proxy_options = proxy_options(uri, options)
-
-
344
return super(request, connections, proxy_options) unless proxy_options.proxy
-
-
328
connection = pool.find_connection(uri, proxy_options) || init_connection(uri, proxy_options)
-
328
unless connections.nil? || connections.include?(connection)
-
320
connections << connection
-
320
set_connection_callbacks(connection, connections, options)
-
end
-
328
connection
-
end
-
-
9
def proxy_options(request_uri, options)
-
386
proxy_opts = if (next_proxy = request_uri.find_proxy)
-
4
{ uri: next_proxy }
-
else
-
382
proxy = options.proxy
-
-
382
return options unless proxy
-
-
373
return options.merge(proxy: nil) unless proxy.key?(:uri)
-
-
373
@_proxy_uris ||= Array(proxy[:uri])
-
-
373
next_proxy = @_proxy_uris.first
-
373
raise Error, "Failed to connect to proxy" unless next_proxy
-
-
359
next_proxy = URI(next_proxy)
-
-
1
raise Error,
-
359
"#{next_proxy.scheme}: unsupported proxy protocol" unless options.supported_proxy_protocols.include?(next_proxy.scheme)
-
-
352
if proxy.key?(:no_proxy)
-
-
14
no_proxy = proxy[:no_proxy]
-
14
no_proxy = no_proxy.join(",") if no_proxy.is_a?(Array)
-
-
14
return options.merge(proxy: nil) unless URI::Generic.use_proxy?(request_uri.host, next_proxy.host,
-
next_proxy.port, no_proxy)
-
end
-
-
345
proxy.merge(uri: next_proxy)
-
end
-
-
349
proxy = Parameters.new(**proxy_opts)
-
-
349
options.merge(proxy: proxy)
-
end
-
-
9
def fetch_response(request, connections, options)
-
1288
response = super
-
-
1288
if response.is_a?(ErrorResponse) && proxy_error?(request, response)
-
85
return response unless @_proxy_uris
-
-
84
@_proxy_uris.shift
-
-
# return last error response if no more proxies to try
-
84
return response if @_proxy_uris.empty?
-
-
14
log { "failed connecting to proxy, trying next..." }
-
14
request.transition(:idle)
-
14
send_request(request, connections, options)
-
12
return
-
end
-
1203
response
-
end
-
-
9
def proxy_error?(_request, response)
-
127
error = response.error
-
109
case error
-
when NativeResolveError
-
14
return false unless @_proxy_uris && !@_proxy_uris.empty?
-
-
14
proxy_uri = URI(@_proxy_uris.first)
-
-
14
origin = error.connection.origin
-
-
# failed resolving proxy domain
-
14
origin.host == proxy_uri.host && origin.port == proxy_uri.port
-
when ResolveError
-
return false unless @_proxy_uris && !@_proxy_uris.empty?
-
-
proxy_uri = URI(@_proxy_uris.first)
-
-
error.message.end_with?(proxy_uri.to_s)
-
when *PROXY_ERRORS
-
# timeout errors connecting to proxy
-
113
true
-
else
-
false
-
end
-
end
-
end
-
-
9
module ConnectionMethods
-
9
using URIExtensions
-
-
9
def initialize(*)
-
336
super
-
336
return unless @options.proxy
-
-
# redefining the connection origin as the proxy's URI,
-
# as this will be used as the tcp peer ip.
-
320
proxy_uri = URI(@options.proxy.uri)
-
320
@origin.host = proxy_uri.host
-
320
@origin.port = proxy_uri.port
-
end
-
-
9
def coalescable?(connection)
-
10
return super unless @options.proxy
-
-
10
if @io.protocol == "h2" &&
-
@origin.scheme == "https" &&
-
connection.origin.scheme == "https" &&
-
@io.can_verify_peer?
-
# in proxied connections, .origin is the proxy ; Given names
-
# are stored in .origins, this is what is used.
-
5
origin = URI(connection.origins.first)
-
5
@io.verify_hostname(origin.host)
-
else
-
5
@origin == connection.origin
-
end
-
end
-
-
9
def connecting?
-
3913
return super unless @options.proxy
-
-
3771
super || @state == :connecting || @state == :connected
-
end
-
-
9
def call
-
894
super
-
-
894
return unless @options.proxy
-
-
767
case @state
-
when :connecting
-
174
consume
-
end
-
end
-
-
9
def reset
-
450
return super unless @options.proxy
-
-
420
@state = :open
-
-
420
super
-
420
emit(:close)
-
end
-
-
9
private
-
-
9
def initialize_type(uri, options)
-
336
return super unless options.proxy
-
-
320
"tcp"
-
end
-
-
9
def connect
-
912
return super unless @options.proxy
-
-
765
case @state
-
when :idle
-
623
transition(:connecting)
-
when :connected
-
259
transition(:open)
-
end
-
end
-
-
9
def handle_transition(nextstate)
-
2136
return super unless @options.proxy
-
-
1785
case nextstate
-
when :closing
-
# this is a hack so that we can use the super method
-
# and it'll think that the current state is open
-
477
@state = :open if @state == :connecting
-
end
-
2058
super
-
end
-
end
-
end
-
9
register_plugin :proxy, Proxy
-
end
-
-
9
class ProxySSL < SSL
-
9
def initialize(tcp, request_uri, options)
-
78
@io = tcp.to_io
-
78
super(request_uri, tcp.addresses, options)
-
78
@hostname = request_uri.host
-
78
@state = :connected
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
9
module HTTPX
-
9
module Plugins
-
9
module Proxy
-
9
module HTTP
-
9
class << self
-
9
def extra_options(options)
-
295
options.merge(supported_proxy_protocols: options.supported_proxy_protocols + %w[http])
-
end
-
end
-
-
9
module InstanceMethods
-
9
def with_proxy_basic_auth(opts)
-
7
with(proxy: opts.merge(scheme: "basic"))
-
end
-
-
9
def with_proxy_digest_auth(opts)
-
21
with(proxy: opts.merge(scheme: "digest"))
-
end
-
-
9
def with_proxy_ntlm_auth(opts)
-
7
with(proxy: opts.merge(scheme: "ntlm"))
-
end
-
-
9
def fetch_response(request, connections, options)
-
1288
response = super
-
-
1288
if response &&
-
response.is_a?(Response) &&
-
response.status == 407 &&
-
!request.headers.key?("proxy-authorization") &&
-
response.headers.key?("proxy-authenticate")
-
-
21
uri = request.uri
-
-
21
proxy_options = proxy_options(uri, options)
-
21
connection = connections.find do |conn|
-
21
conn.match?(uri, proxy_options)
-
end
-
-
21
if connection && connection.options.proxy.can_authenticate?(response.headers["proxy-authenticate"])
-
7
request.transition(:idle)
-
6
request.headers["proxy-authorization"] =
-
connection.options.proxy.authenticate(request, response.headers["proxy-authenticate"])
-
7
send_request(request, connections)
-
7
return
-
end
-
end
-
-
1281
response
-
end
-
end
-
-
9
module ConnectionMethods
-
9
def connecting?
-
3913
super || @state == :connecting || @state == :connected
-
end
-
-
9
private
-
-
9
def handle_transition(nextstate)
-
2345
return super unless @options.proxy && @options.proxy.uri.scheme == "http"
-
-
1064
case nextstate
-
when :connecting
-
266
return unless @state == :idle
-
-
266
@io.connect
-
266
return unless @io.connected?
-
-
133
@parser || begin
-
126
@parser = self.class.parser_type(@io.protocol).new(@write_buffer, @options.merge(max_concurrent_requests: 1))
-
126
parser = @parser
-
126
parser.extend(ProxyParser)
-
126
parser.on(:response, &method(:__http_on_connect))
-
176
parser.on(:close) { transition(:closing) }
-
126
parser.on(:reset) do
-
14
if parser.empty?
-
7
reset
-
else
-
7
transition(:closing)
-
7
transition(:closed)
-
-
7
parser.reset if @parser
-
7
transition(:idle)
-
7
transition(:connecting)
-
end
-
end
-
126
__http_proxy_connect(parser)
-
end
-
133
return if @state == :connected
-
when :connected
-
119
return unless @state == :idle || @state == :connecting
-
-
104
case @state
-
when :connecting
-
43
@parser.close
-
43
@parser = nil
-
when :idle
-
76
@parser.callbacks.clear
-
76
set_parser_callbacks(@parser)
-
end
-
end
-
1004
super
-
end
-
-
9
def __http_proxy_connect(parser)
-
126
req = @pending.first
-
126
if req && req.uri.scheme == "https"
-
# if the first request after CONNECT is to an https address, it is assumed that
-
# all requests in the queue are not only ALL HTTPS, but they also share the certificate,
-
# and therefore, will share the connection.
-
#
-
50
connect_request = ConnectRequest.new(req.uri, @options)
-
44
@inflight += 1
-
50
parser.send(connect_request)
-
else
-
76
handle_transition(:connected)
-
end
-
end
-
-
9
def __http_on_connect(request, response)
-
50
@inflight -= 1
-
57
if response.is_a?(Response) && response.status == 200
-
43
req = @pending.first
-
43
request_uri = req.uri
-
43
@io = ProxySSL.new(@io, request_uri, @options)
-
43
transition(:connected)
-
43
throw(:called)
-
13
elsif response.is_a?(Response) &&
-
response.status == 407 &&
-
!request.headers.key?("proxy-authorization") &&
-
@options.proxy.can_authenticate?(response.headers["proxy-authenticate"])
-
-
7
request.transition(:idle)
-
6
request.headers["proxy-authorization"] = @options.proxy.authenticate(request, response.headers["proxy-authenticate"])
-
7
@parser.send(request)
-
6
@inflight += 1
-
else
-
7
pending = @pending + @parser.pending
-
18
while (req = pending.shift)
-
7
req.emit(:response, response)
-
end
-
7
reset
-
end
-
end
-
end
-
-
9
module ProxyParser
-
9
def join_headline(request)
-
126
return super if request.verb == "CONNECT"
-
-
60
"#{request.verb} #{request.uri} HTTP/#{@version.join(".")}"
-
end
-
-
9
def set_protocol_headers(request)
-
133
extra_headers = super
-
-
133
proxy_params = @options.proxy
-
133
if proxy_params.scheme == "basic"
-
# opt for basic auth
-
73
extra_headers["proxy-authorization"] = proxy_params.authenticate(extra_headers)
-
end
-
133
extra_headers["proxy-connection"] = extra_headers.delete("connection") if extra_headers.key?("connection")
-
133
extra_headers
-
end
-
end
-
-
9
class ConnectRequest < Request
-
9
def initialize(uri, options)
-
50
super("CONNECT", uri, options)
-
50
@headers.delete("accept")
-
end
-
-
9
def path
-
56
"#{@uri.hostname}:#{@uri.port}"
-
end
-
end
-
end
-
end
-
9
register_plugin :"proxy/http", Proxy::HTTP
-
end
-
end
-
# frozen_string_literal: true
-
-
9
require "resolv"
-
9
require "ipaddr"
-
-
9
module HTTPX
-
9
class Socks4Error < HTTPProxyError; end
-
-
9
module Plugins
-
9
module Proxy
-
9
module Socks4
-
9
VERSION = 4
-
9
CONNECT = 1
-
9
GRANTED = 0x5A
-
9
PROTOCOLS = %w[socks4 socks4a].freeze
-
-
9
Error = Socks4Error
-
-
9
class << self
-
9
def extra_options(options)
-
295
options.merge(supported_proxy_protocols: options.supported_proxy_protocols + PROTOCOLS)
-
end
-
end
-
-
9
module ConnectionMethods
-
9
def interests
-
3310
if @state == :connecting
-
return @write_buffer.empty? ? :r : :w
-
end
-
-
3310
super
-
end
-
-
9
private
-
-
9
def handle_transition(nextstate)
-
2401
return super unless @options.proxy && PROTOCOLS.include?(@options.proxy.uri.scheme)
-
-
364
case nextstate
-
when :connecting
-
112
return unless @state == :idle
-
-
112
@io.connect
-
112
return unless @io.connected?
-
-
56
req = @pending.first
-
56
return unless req
-
-
56
request_uri = req.uri
-
56
@write_buffer << Packet.connect(@options.proxy, request_uri)
-
56
__socks4_proxy_connect
-
when :connected
-
42
return unless @state == :connecting
-
-
42
@parser = nil
-
end
-
369
log(level: 1) { "SOCKS4: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
-
369
super
-
end
-
-
9
def __socks4_proxy_connect
-
56
@parser = SocksParser.new(@write_buffer, @options)
-
56
@parser.once(:packet, &method(:__socks4_on_packet))
-
end
-
-
9
def __socks4_on_packet(packet)
-
56
_version, status, _port, _ip = packet.unpack("CCnN")
-
56
if status == GRANTED
-
42
req = @pending.first
-
42
request_uri = req.uri
-
42
@io = ProxySSL.new(@io, request_uri, @options) if request_uri.scheme == "https"
-
42
transition(:connected)
-
42
throw(:called)
-
else
-
14
on_socks4_error("socks error: #{status}")
-
end
-
end
-
-
9
def on_socks4_error(message)
-
14
ex = Error.new(message)
-
14
ex.set_backtrace(caller)
-
14
on_error(ex)
-
14
throw(:called)
-
end
-
end
-
-
9
class SocksParser
-
9
include HTTPX::Callbacks
-
-
9
def initialize(buffer, options)
-
56
@buffer = buffer
-
56
@options = options
-
end
-
-
9
def close; end
-
-
9
def consume(*); end
-
-
9
def empty?
-
14
true
-
end
-
-
9
def <<(packet)
-
56
emit(:packet, packet)
-
end
-
end
-
-
9
module Packet
-
9
module_function
-
-
9
def connect(parameters, uri)
-
56
packet = [VERSION, CONNECT, uri.port].pack("CCn")
-
-
48
case parameters.uri.scheme
-
when "socks4"
-
42
socks_host = uri.host
-
5
begin
-
84
ip = IPAddr.new(socks_host)
-
42
packet << ip.hton
-
rescue IPAddr::InvalidAddressError
-
42
socks_host = Resolv.getaddress(socks_host)
-
42
retry
-
end
-
42
packet << [parameters.username].pack("Z*")
-
when "socks4a"
-
14
packet << "\x0\x0\x0\x1" << [parameters.username].pack("Z*") << uri.host << "\x0"
-
end
-
56
packet
-
end
-
end
-
end
-
end
-
9
register_plugin :"proxy/socks4", Proxy::Socks4
-
end
-
end
-
# frozen_string_literal: true
-
-
9
module HTTPX
-
9
class Socks5Error < HTTPProxyError; end
-
-
9
module Plugins
-
9
module Proxy
-
9
module Socks5
-
9
VERSION = 5
-
9
NOAUTH = 0
-
9
PASSWD = 2
-
9
NONE = 0xff
-
9
CONNECT = 1
-
9
IPV4 = 1
-
9
DOMAIN = 3
-
9
IPV6 = 4
-
9
SUCCESS = 0
-
-
9
Error = Socks5Error
-
-
9
class << self
-
9
def load_dependencies(*)
-
295
require_relative "../auth/socks5"
-
end
-
-
9
def extra_options(options)
-
295
options.merge(supported_proxy_protocols: options.supported_proxy_protocols + %w[socks5])
-
end
-
end
-
-
9
module ConnectionMethods
-
9
def call
-
894
super
-
-
894
return unless @options.proxy && @options.proxy.uri.scheme == "socks5"
-
-
236
case @state
-
when :connecting,
-
:negotiating,
-
:authenticating
-
87
consume
-
end
-
end
-
-
9
def connecting?
-
3913
super || @state == :authenticating || @state == :negotiating
-
end
-
-
9
def interests
-
5209
if @state == :connecting || @state == :authenticating || @state == :negotiating
-
1694
return @write_buffer.empty? ? :r : :w
-
end
-
-
3310
super
-
end
-
-
9
private
-
-
9
def handle_transition(nextstate)
-
2653
return super unless @options.proxy && @options.proxy.uri.scheme == "socks5"
-
-
803
case nextstate
-
when :connecting
-
252
return unless @state == :idle
-
-
252
@io.connect
-
252
return unless @io.connected?
-
-
126
@write_buffer << Packet.negotiate(@options.proxy)
-
126
__socks5_proxy_connect
-
when :authenticating
-
42
return unless @state == :connecting
-
-
42
@write_buffer << Packet.authenticate(@options.proxy)
-
when :negotiating
-
168
return unless @state == :connecting || @state == :authenticating
-
-
42
req = @pending.first
-
42
request_uri = req.uri
-
42
@write_buffer << Packet.connect(request_uri)
-
when :connected
-
28
return unless @state == :negotiating
-
-
28
@parser = nil
-
end
-
685
log(level: 1) { "SOCKS5: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
-
685
super
-
end
-
-
9
def __socks5_proxy_connect
-
126
@parser = SocksParser.new(@write_buffer, @options)
-
126
@parser.on(:packet, &method(:__socks5_on_packet))
-
126
transition(:negotiating)
-
end
-
-
9
def __socks5_on_packet(packet)
-
180
case @state
-
when :connecting
-
126
version, method = packet.unpack("CC")
-
126
__socks5_check_version(version)
-
108
case method
-
when PASSWD
-
42
transition(:authenticating)
-
12
nil
-
when NONE
-
70
__on_socks5_error("no supported authorization methods")
-
else
-
14
transition(:negotiating)
-
end
-
when :authenticating
-
42
_, status = packet.unpack("CC")
-
42
return transition(:negotiating) if status == SUCCESS
-
-
14
__on_socks5_error("socks authentication error: #{status}")
-
when :negotiating
-
42
version, reply, = packet.unpack("CC")
-
42
__socks5_check_version(version)
-
42
__on_socks5_error("socks5 negotiation error: #{reply}") unless reply == SUCCESS
-
28
req = @pending.first
-
28
request_uri = req.uri
-
28
@io = ProxySSL.new(@io, request_uri, @options) if request_uri.scheme == "https"
-
28
transition(:connected)
-
28
throw(:called)
-
end
-
end
-
-
9
def __socks5_check_version(version)
-
168
__on_socks5_error("invalid SOCKS version (#{version})") if version != 5
-
end
-
-
9
def __on_socks5_error(message)
-
98
ex = Error.new(message)
-
98
ex.set_backtrace(caller)
-
98
on_error(ex)
-
98
throw(:called)
-
end
-
end
-
-
9
class SocksParser
-
9
include HTTPX::Callbacks
-
-
9
def initialize(buffer, options)
-
126
@buffer = buffer
-
126
@options = options
-
end
-
-
9
def close; end
-
-
9
def consume(*); end
-
-
9
def empty?
-
98
true
-
end
-
-
9
def <<(packet)
-
210
emit(:packet, packet)
-
end
-
end
-
-
9
module Packet
-
9
module_function
-
-
9
def negotiate(parameters)
-
126
methods = [NOAUTH]
-
126
methods << PASSWD if parameters.can_authenticate?
-
126
methods.unshift(methods.size)
-
126
methods.unshift(VERSION)
-
126
methods.pack("C*")
-
end
-
-
9
def authenticate(parameters)
-
42
parameters.authenticate
-
end
-
-
9
def connect(uri)
-
42
packet = [VERSION, CONNECT, 0].pack("C*")
-
5
begin
-
42
ip = IPAddr.new(uri.host)
-
-
14
ipcode = ip.ipv6? ? IPV6 : IPV4
-
-
14
packet << [ipcode].pack("C") << ip.hton
-
rescue IPAddr::InvalidAddressError
-
28
packet << [DOMAIN, uri.host.bytesize, uri.host].pack("CCA*")
-
end
-
42
packet << [uri.port].pack("n")
-
42
packet
-
end
-
end
-
end
-
end
-
9
register_plugin :"proxy/socks5", Proxy::Socks5
-
end
-
end
-
# frozen_string_literal: true
-
-
5
require "httpx/plugins/proxy"
-
-
5
module HTTPX
-
5
module Plugins
-
5
module Proxy
-
5
module SSH
-
5
class << self
-
5
def load_dependencies(*)
-
10
require "net/ssh/gateway"
-
end
-
end
-
-
5
module OptionsMethods
-
5
def option_proxy(value)
-
20
Hash[value]
-
end
-
end
-
-
5
module InstanceMethods
-
5
def request(*args, **options)
-
10
raise ArgumentError, "must perform at least one request" if args.empty?
-
-
10
requests = args.first.is_a?(Request) ? args : build_requests(*args, options)
-
-
10
request = requests.first or return super
-
-
10
request_options = request.options
-
-
10
return super unless request_options.proxy
-
-
10
ssh_options = request_options.proxy
-
10
ssh_uris = ssh_options.delete(:uri)
-
10
ssh_uri = URI.parse(ssh_uris.shift)
-
-
10
return super unless ssh_uri.scheme == "ssh"
-
-
10
ssh_username = ssh_options.delete(:username)
-
10
ssh_options[:port] ||= ssh_uri.port || 22
-
10
if request_options.debug
-
ssh_options[:verbose] = request_options.debug_level == 2 ? :debug : :info
-
end
-
-
10
request_uri = URI(requests.first.uri)
-
10
@_gateway = Net::SSH::Gateway.new(ssh_uri.host, ssh_username, ssh_options)
-
begin
-
10
@_gateway.open(request_uri.host, request_uri.port) do |local_port|
-
10
io = build_gateway_socket(local_port, request_uri, request_options)
-
10
super(*args, **options.merge(io: io))
-
end
-
ensure
-
10
@_gateway.shutdown!
-
end
-
end
-
-
5
private
-
-
5
def build_gateway_socket(port, request_uri, options)
-
10
case request_uri.scheme
-
when "https"
-
5
ctx = OpenSSL::SSL::SSLContext.new
-
5
ctx_options = SSL::TLS_OPTIONS.merge(options.ssl)
-
5
ctx.set_params(ctx_options) unless ctx_options.empty?
-
5
sock = TCPSocket.open("localhost", port)
-
5
io = OpenSSL::SSL::SSLSocket.new(sock, ctx)
-
5
io.hostname = request_uri.host
-
5
io.sync_close = true
-
5
io.connect
-
5
io.post_connection_check(request_uri.host) if ctx.verify_mode != OpenSSL::SSL::VERIFY_NONE
-
5
io
-
when "http"
-
5
TCPSocket.open("localhost", port)
-
else
-
raise TypeError, "unexpected scheme: #{request_uri.scheme}"
-
end
-
end
-
end
-
-
5
module ConnectionMethods
-
# should not coalesce connections here, as the IP is the IP of the proxy
-
5
def coalescable?(*)
-
return super unless @options.proxy
-
-
false
-
end
-
end
-
end
-
end
-
5
register_plugin :"proxy/ssh", Proxy::SSH
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# This plugin adds support for HTTP/2 Push responses.
-
#
-
# In order to benefit from this, requests are sent one at a time, so that
-
# no push responses are received after corresponding request has been sent.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Server-Push
-
#
-
7
module PushPromise
-
7
def self.extra_options(options)
-
14
options.merge(http2_settings: { settings_enable_push: 1 },
-
max_concurrent_requests: 1)
-
end
-
-
7
module ResponseMethods
-
7
def pushed?
-
14
@__pushed
-
end
-
-
7
def mark_as_pushed!
-
7
@__pushed = true
-
end
-
end
-
-
7
module InstanceMethods
-
7
private
-
-
7
def promise_headers
-
14
@promise_headers ||= {}
-
end
-
-
7
def on_promise(parser, stream)
-
14
stream.on(:promise_headers) do |h|
-
14
__on_promise_request(parser, stream, h)
-
end
-
14
stream.on(:headers) do |h|
-
7
__on_promise_response(parser, stream, h)
-
end
-
end
-
-
7
def __on_promise_request(parser, stream, h)
-
14
log(level: 1, color: :yellow) do
-
skipped
# :nocov:
-
skipped
h.map { |k, v| "#{stream.id}: -> PROMISE HEADER: #{k}: #{v}" }.join("\n")
-
skipped
# :nocov:
-
end
-
14
headers = @options.headers_class.new(h)
-
14
path = headers[":path"]
-
14
authority = headers[":authority"]
-
-
21
request = parser.pending.find { |r| r.authority == authority && r.path == path }
-
14
if request
-
7
request.merge_headers(headers)
-
6
promise_headers[stream] = request
-
7
parser.pending.delete(request)
-
6
parser.streams[request] = stream
-
7
request.transition(:done)
-
else
-
7
stream.refuse
-
end
-
end
-
-
7
def __on_promise_response(parser, stream, h)
-
7
request = promise_headers.delete(stream)
-
7
return unless request
-
-
7
parser.__send__(:on_stream_headers, stream, request, h)
-
7
response = request.response
-
7
response.mark_as_pushed!
-
7
stream.on(:data, &parser.method(:on_stream_data).curry(3)[stream, request])
-
7
stream.on(:close, &parser.method(:on_stream_close).curry(3)[stream, request])
-
end
-
end
-
end
-
7
register_plugin(:push_promise, PushPromise)
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# This plugin adds support for retrying requests when the request:
-
#
-
# * is rate limited;
-
# * when the server is unavailable (503);
-
# * when a 3xx request comes with a "retry-after" value
-
#
-
# https://gitlab.com/os85/httpx/wikis/Rate-Limiter
-
#
-
7
module RateLimiter
-
7
class << self
-
7
RATE_LIMIT_CODES = [429, 503].freeze
-
-
7
def configure(klass)
-
56
klass.plugin(:retries,
-
retry_change_requests: true,
-
7
retry_on: method(:retry_on_rate_limited_response),
-
retry_after: method(:retry_after_rate_limit))
-
end
-
-
7
def retry_on_rate_limited_response(response)
-
112
return false unless response.is_a?(Response)
-
-
112
status = response.status
-
-
112
RATE_LIMIT_CODES.include?(status)
-
end
-
-
# Servers send the "Retry-After" header field to indicate how long the
-
# user agent ought to wait before making a follow-up request. When
-
# sent with a 503 (Service Unavailable) response, Retry-After indicates
-
# how long the service is expected to be unavailable to the client.
-
# When sent with any 3xx (Redirection) response, Retry-After indicates
-
# the minimum time that the user agent is asked to wait before issuing
-
# the redirected request.
-
#
-
7
def retry_after_rate_limit(_, response)
-
56
return unless response.is_a?(Response)
-
-
56
retry_after = response.headers["retry-after"]
-
-
56
return unless retry_after
-
-
28
Utils.parse_retry_after(retry_after)
-
end
-
end
-
end
-
-
7
register_plugin :rate_limiter, RateLimiter
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# This plugin adds support for retrying requests when certain errors happen.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Response-Cache
-
#
-
7
module ResponseCache
-
7
CACHEABLE_VERBS = %w[GET HEAD].freeze
-
7
CACHEABLE_STATUS_CODES = [200, 203, 206, 300, 301, 410].freeze
-
7
private_constant :CACHEABLE_VERBS
-
7
private_constant :CACHEABLE_STATUS_CODES
-
-
7
class << self
-
7
def load_dependencies(*)
-
154
require_relative "response_cache/store"
-
end
-
-
7
def cacheable_request?(request)
-
217
CACHEABLE_VERBS.include?(request.verb) &&
-
(
-
217
!request.headers.key?("cache-control") || !request.headers.get("cache-control").include?("no-store")
-
)
-
end
-
-
7
def cacheable_response?(response)
-
147
response.is_a?(Response) &&
-
(
-
147
response.cache_control.nil? ||
-
# TODO: !response.cache_control.include?("private") && is shared cache
-
!response.cache_control.include?("no-store")
-
) &&
-
CACHEABLE_STATUS_CODES.include?(response.status) &&
-
# RFC 2616 13.4 - A response received with a status code of 200, 203, 206, 300, 301 or
-
# 410 MAY be stored by a cache and used in reply to a subsequent
-
# request, subject to the expiration mechanism, unless a cache-control
-
# directive prohibits caching. However, a cache that does not support
-
# the Range and Content-Range headers MUST NOT cache 206 (Partial
-
# Content) responses.
-
response.status != 206 && (
-
114
response.headers.key?("etag") || response.headers.key?("last-modified") || response.fresh?
-
)
-
end
-
-
7
def cached_response?(response)
-
70
response.is_a?(Response) && response.status == 304
-
end
-
-
7
def extra_options(options)
-
154
options.merge(response_cache_store: Store.new)
-
end
-
end
-
-
7
module OptionsMethods
-
7
def option_response_cache_store(value)
-
154
raise TypeError, "must be an instance of #{Store}" unless value.is_a?(Store)
-
-
154
value
-
end
-
end
-
-
7
module InstanceMethods
-
7
def clear_response_cache
-
14
@options.response_cache_store.clear
-
end
-
-
7
def build_request(*)
-
70
request = super
-
70
return request unless ResponseCache.cacheable_request?(request) && @options.response_cache_store.cached?(request)
-
-
28
@options.response_cache_store.prepare(request)
-
-
28
request
-
end
-
-
7
def fetch_response(request, *)
-
236
response = super
-
-
236
return unless response
-
-
70
if ResponseCache.cached_response?(response)
-
28
log { "returning cached response for #{request.uri}" }
-
28
cached_response = @options.response_cache_store.lookup(request)
-
-
28
response.copy_from_cached(cached_response)
-
-
else
-
42
@options.response_cache_store.cache(request, response)
-
end
-
-
70
response
-
end
-
end
-
-
7
module RequestMethods
-
7
def response_cache_key
-
448
@response_cache_key ||= Digest::SHA1.hexdigest("httpx-response-cache-#{@verb}-#{@uri}")
-
end
-
end
-
-
7
module ResponseMethods
-
7
def copy_from_cached(other)
-
# 304 responses do not have content-type, which are needed for decoding.
-
28
@headers = @headers.class.new(other.headers.merge(@headers))
-
-
28
@body = other.body.dup
-
-
28
@body.rewind
-
end
-
-
# A response is fresh if its age has not yet exceeded its freshness lifetime.
-
7
def fresh?
-
224
if cache_control
-
35
return false if cache_control.include?("no-cache")
-
-
# check age: max-age
-
42
max_age = cache_control.find { |directive| directive.start_with?("s-maxage") }
-
-
42
max_age ||= cache_control.find { |directive| directive.start_with?("max-age") }
-
-
21
max_age = max_age[/age=(\d+)/, 1] if max_age
-
-
21
max_age = max_age.to_i if max_age
-
-
21
return max_age > age if max_age
-
end
-
-
# check age: expires
-
189
if @headers.key?("expires")
-
2
begin
-
21
expires = Time.httpdate(@headers["expires"])
-
rescue ArgumentError
-
7
return true
-
end
-
-
12
return (expires - Time.now).to_i.positive?
-
end
-
-
168
true
-
end
-
-
7
def cache_control
-
483
return @cache_control if defined?(@cache_control)
-
-
48
@cache_control = begin
-
336
return unless @headers.key?("cache-control")
-
-
35
@headers["cache-control"].split(/ *, */)
-
end
-
end
-
-
7
def vary
-
245
return @vary if defined?(@vary)
-
-
28
@vary = begin
-
196
return unless @headers.key?("vary")
-
-
14
@headers["vary"].split(/ *, */)
-
end
-
end
-
-
7
private
-
-
7
def age
-
21
return @headers["age"].to_i if @headers.key?("age")
-
-
21
(Time.now - date).to_i
-
end
-
-
7
def date
-
21
@date ||= Time.httpdate(@headers["date"])
-
rescue NoMethodError, ArgumentError
-
7
Time.now
-
end
-
end
-
end
-
7
register_plugin :response_cache, ResponseCache
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX::Plugins
-
7
module ResponseCache
-
7
class Store
-
7
def initialize
-
217
@store = {}
-
217
@store_mutex = Thread::Mutex.new
-
end
-
-
7
def clear
-
28
@store_mutex.synchronize { @store.clear }
-
end
-
-
7
def lookup(request)
-
273
responses = _get(request)
-
-
273
return unless responses
-
-
210
responses.find(&method(:match_by_vary?).curry(2)[request])
-
end
-
-
7
def cached?(request)
-
98
lookup(request)
-
end
-
-
7
def cache(request, response)
-
147
return unless ResponseCache.cacheable_request?(request) && ResponseCache.cacheable_response?(response)
-
-
133
_set(request, response)
-
end
-
-
7
def prepare(request)
-
70
cached_response = lookup(request)
-
-
70
return unless cached_response
-
-
49
return unless match_by_vary?(request, cached_response)
-
-
49
if !request.headers.key?("if-modified-since") && (last_modified = cached_response.headers["last-modified"])
-
28
request.headers.add("if-modified-since", last_modified)
-
end
-
-
49
if !request.headers.key?("if-none-match") && (etag = cached_response.headers["etag"]) # rubocop:disable Style/GuardClause
-
49
request.headers.add("if-none-match", etag)
-
end
-
end
-
-
7
private
-
-
7
def match_by_vary?(request, response)
-
245
vary = response.vary
-
-
245
return true unless vary
-
-
63
original_request = response.instance_variable_get(:@request)
-
-
63
return request.headers.same_headers?(original_request.headers) if vary == %w[*]
-
-
35
vary.all? do |cache_field|
-
35
cache_field.downcase!
-
35
!original_request.headers.key?(cache_field) || request.headers[cache_field] == original_request.headers[cache_field]
-
end
-
end
-
-
7
def _get(request)
-
273
@store_mutex.synchronize do
-
273
responses = @store[request.response_cache_key]
-
-
273
return unless responses
-
-
210
responses.select! do |res|
-
210
!res.body.closed? && res.fresh?
-
end
-
-
210
responses
-
end
-
end
-
-
7
def _set(request, response)
-
133
@store_mutex.synchronize do
-
133
responses = (@store[request.response_cache_key] ||= [])
-
-
133
responses.reject! do |res|
-
14
res.body.closed? || !res.fresh? || match_by_vary?(request, res)
-
end
-
-
133
responses << response
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
14
module HTTPX
-
14
module Plugins
-
#
-
# This plugin adds support for retrying requests when errors happen.
-
#
-
# It has a default max number of retries (see *MAX_RETRIES* and the *max_retries* option),
-
# after which it will return the last response, error or not. It will **not** raise an exception.
-
#
-
# It does not retry which are not considered idempotent (see *retry_change_requests* to override).
-
#
-
# https://gitlab.com/os85/httpx/wikis/Retries
-
#
-
14
module Retries
-
14
MAX_RETRIES = 3
-
# TODO: pass max_retries in a configure/load block
-
-
14
IDEMPOTENT_METHODS = %w[GET OPTIONS HEAD PUT DELETE].freeze
-
2
RETRYABLE_ERRORS = [
-
12
IOError,
-
EOFError,
-
Errno::ECONNRESET,
-
Errno::ECONNABORTED,
-
Errno::EPIPE,
-
Errno::EINVAL,
-
Errno::ETIMEDOUT,
-
Parser::Error,
-
TLSError,
-
TimeoutError,
-
ConnectionError,
-
Connection::HTTP2::GoawayError,
-
].freeze
-
14
DEFAULT_JITTER = ->(interval) { interval * ((rand + 1) * 0.5) }
-
-
14
if ENV.key?("HTTPX_NO_JITTER")
-
14
def self.extra_options(options)
-
588
options.merge(max_retries: MAX_RETRIES)
-
end
-
else
-
def self.extra_options(options)
-
options.merge(max_retries: MAX_RETRIES, retry_jitter: DEFAULT_JITTER)
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :max_retries :: max number of times a request will be retried (defaults to <tt>3</tt>).
-
# :retry_change_requests :: whether idempotent requests are retried (defaults to <tt>false</tt>).
-
# :retry_after:: seconds after which a request is retried; can also be a callable object (i.e. <tt>->(req, res) { ... } </tt>)
-
# :retry_jitter :: number of seconds applied to *:retry_after* (must be a callable, i.e. <tt>->(retry_after) { ... } </tt>).
-
# :retry_on :: callable which alternatively defines a different rule for when a response is to be retried
-
# (i.e. <tt>->(res) { ... }</tt>).
-
14
module OptionsMethods
-
14
def option_retry_after(value)
-
# return early if callable
-
182
unless value.respond_to?(:call)
-
84
value = Float(value)
-
84
raise TypeError, ":retry_after must be positive" unless value.positive?
-
end
-
-
182
value
-
end
-
-
14
def option_retry_jitter(value)
-
# return early if callable
-
42
raise TypeError, ":retry_jitter must be callable" unless value.respond_to?(:call)
-
-
42
value
-
end
-
-
14
def option_max_retries(value)
-
1799
num = Integer(value)
-
1799
raise TypeError, ":max_retries must be positive" unless num >= 0
-
-
1799
num
-
end
-
-
14
def option_retry_change_requests(v)
-
954
v
-
end
-
-
14
def option_retry_on(value)
-
201
raise TypeError, ":retry_on must be called with the response" unless value.respond_to?(:call)
-
-
201
value
-
end
-
end
-
-
14
module InstanceMethods
-
14
def max_retries(n)
-
84
with(max_retries: n)
-
end
-
-
14
private
-
-
14
def fetch_response(request, connections, options)
-
2078621
response = super
-
-
2078621
if response &&
-
request.retries.positive? &&
-
__repeatable_request?(request, options) &&
-
(
-
96
(
-
221
response.is_a?(ErrorResponse) && __retryable_error?(response.error)
-
) ||
-
(
-
159
options.retry_on && options.retry_on.call(response)
-
)
-
)
-
397
__try_partial_retry(request, response)
-
397
log { "failed to get response, #{request.retries} tries to go..." }
-
397
request.retries -= 1
-
397
request.transition(:idle)
-
-
397
retry_after = options.retry_after
-
397
retry_after = retry_after.call(request, response) if retry_after.respond_to?(:call)
-
-
397
if retry_after
-
# apply jitter
-
84
if (jitter = request.options.retry_jitter)
-
14
retry_after = jitter.call(retry_after)
-
end
-
-
84
retry_start = Utils.now
-
84
log { "retrying after #{retry_after} secs..." }
-
-
84
deactivate_connection(request, connections, options)
-
-
84
pool.after(retry_after) do
-
84
if request.response
-
# request has terminated abruptly meanwhile
-
request.emit(:response, request.response)
-
else
-
84
log { "retrying (elapsed time: #{Utils.elapsed_time(retry_start)})!!" }
-
84
send_request(request, connections, options)
-
end
-
end
-
else
-
313
send_request(request, connections, options)
-
end
-
-
343
return
-
end
-
2078224
response
-
end
-
-
14
def __repeatable_request?(request, options)
-
817
IDEMPOTENT_METHODS.include?(request.verb) || options.retry_change_requests
-
end
-
-
14
def __retryable_error?(ex)
-
2866
RETRYABLE_ERRORS.any? { |klass| ex.is_a?(klass) }
-
end
-
-
14
def proxy_error?(request, response)
-
56
super && !request.retries.positive?
-
end
-
-
#
-
# Atttempt to set the request to perform a partial range request.
-
# This happens if the peer server accepts byte-range requests, and
-
# the last response contains some body payload.
-
#
-
14
def __try_partial_retry(request, response)
-
397
response = response.response if response.is_a?(ErrorResponse)
-
-
397
return unless response
-
-
178
unless response.headers.key?("accept-ranges") &&
-
response.headers["accept-ranges"] == "bytes" && # there's nothing else supported though...
-
14
(original_body = response.body)
-
164
response.close if response.respond_to?(:close)
-
142
return
-
end
-
-
14
request.partial_response = response
-
-
14
size = original_body.bytesize
-
-
12
request.headers["range"] = "bytes=#{size}-"
-
end
-
end
-
-
14
module RequestMethods
-
14
attr_accessor :retries
-
-
14
attr_writer :partial_response
-
-
14
def initialize(*args)
-
606
super
-
606
@retries = @options.max_retries
-
end
-
-
14
def response=(response)
-
1017
if @partial_response
-
14
if response.is_a?(Response) && response.status == 206
-
14
response.from_partial_response(@partial_response)
-
else
-
@partial_response.close
-
end
-
14
@partial_response = nil
-
end
-
-
1017
super
-
end
-
end
-
-
14
module ResponseMethods
-
14
def from_partial_response(response)
-
14
@status = response.status
-
14
@headers = response.headers
-
14
@body = response.body
-
end
-
end
-
end
-
14
register_plugin :retries, Retries
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
class ServerSideRequestForgeryError < Error; end
-
-
7
module Plugins
-
#
-
# This plugin adds support for preventing Server-Side Request Forgery attacks.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Server-Side-Request-Forgery-Filter
-
#
-
7
module SsrfFilter
-
7
module IPAddrExtensions
-
7
refine IPAddr do
-
7
def prefixlen
-
112
mask_addr = @mask_addr
-
112
raise "Invalid mask" if mask_addr.zero?
-
-
371
mask_addr >>= 1 while (mask_addr & 0x1).zero?
-
-
112
length = 0
-
365
while mask_addr & 0x1 == 0x1
-
1518
length += 1
-
1518
mask_addr >>= 1
-
end
-
-
112
length
-
end
-
end
-
end
-
-
7
using IPAddrExtensions
-
-
# https://en.wikipedia.org/wiki/Reserved_IP_addresses
-
2
IPV4_BLACKLIST = [
-
5
IPAddr.new("0.0.0.0/8"), # Current network (only valid as source address)
-
IPAddr.new("10.0.0.0/8"), # Private network
-
IPAddr.new("100.64.0.0/10"), # Shared Address Space
-
IPAddr.new("127.0.0.0/8"), # Loopback
-
IPAddr.new("169.254.0.0/16"), # Link-local
-
IPAddr.new("172.16.0.0/12"), # Private network
-
IPAddr.new("192.0.0.0/24"), # IETF Protocol Assignments
-
IPAddr.new("192.0.2.0/24"), # TEST-NET-1, documentation and examples
-
IPAddr.new("192.88.99.0/24"), # IPv6 to IPv4 relay (includes 2002::/16)
-
IPAddr.new("192.168.0.0/16"), # Private network
-
IPAddr.new("198.18.0.0/15"), # Network benchmark tests
-
IPAddr.new("198.51.100.0/24"), # TEST-NET-2, documentation and examples
-
IPAddr.new("203.0.113.0/24"), # TEST-NET-3, documentation and examples
-
IPAddr.new("224.0.0.0/4"), # IP multicast (former Class D network)
-
IPAddr.new("240.0.0.0/4"), # Reserved (former Class E network)
-
IPAddr.new("255.255.255.255"), # Broadcast
-
].freeze
-
-
3
IPV6_BLACKLIST = ([
-
5
IPAddr.new("::1/128"), # Loopback
-
IPAddr.new("64:ff9b::/96"), # IPv4/IPv6 translation (RFC 6052)
-
IPAddr.new("100::/64"), # Discard prefix (RFC 6666)
-
IPAddr.new("2001::/32"), # Teredo tunneling
-
IPAddr.new("2001:10::/28"), # Deprecated (previously ORCHID)
-
IPAddr.new("2001:20::/28"), # ORCHIDv2
-
IPAddr.new("2001:db8::/32"), # Addresses used in documentation and example source code
-
IPAddr.new("2002::/16"), # 6to4
-
IPAddr.new("fc00::/7"), # Unique local address
-
IPAddr.new("fe80::/10"), # Link-local address
-
IPAddr.new("ff00::/8"), # Multicast
-
] + IPV4_BLACKLIST.flat_map do |ipaddr|
-
112
prefixlen = ipaddr.prefixlen
-
-
112
ipv4_compatible = ipaddr.ipv4_compat.mask(96 + prefixlen)
-
112
ipv4_mapped = ipaddr.ipv4_mapped.mask(80 + prefixlen)
-
-
112
[ipv4_compatible, ipv4_mapped]
-
end).freeze
-
-
7
class << self
-
7
def extra_options(options)
-
61
options.merge(allowed_schemes: %w[https http])
-
end
-
-
7
def unsafe_ip_address?(ipaddr)
-
82
range = ipaddr.to_range
-
82
return true if range.first != range.last
-
-
96
return IPV6_BLACKLIST.any? { |r| r.include?(ipaddr) } if ipaddr.ipv6?
-
-
822
IPV4_BLACKLIST.any? { |r| r.include?(ipaddr) } # then it's IPv4
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :allowed_schemes :: list of URI schemes allowed (defaults to <tt>["https", "http"]</tt>)
-
7
module OptionsMethods
-
7
def option_allowed_schemes(value)
-
68
Array(value)
-
end
-
end
-
-
7
module InstanceMethods
-
7
def send_requests(*requests)
-
75
responses = requests.map do |request|
-
75
next if @options.allowed_schemes.include?(request.uri.scheme)
-
-
7
error = ServerSideRequestForgeryError.new("#{request.uri} URI scheme not allowed")
-
7
error.set_backtrace(caller)
-
7
response = ErrorResponse.new(request, error)
-
7
request.emit(:response, response)
-
7
response
-
end
-
150
allowed_requests = requests.select { |req| responses[requests.index(req)].nil? }
-
75
allowed_responses = super(*allowed_requests)
-
75
allowed_responses.each_with_index do |res, idx|
-
68
req = allowed_requests[idx]
-
58
responses[requests.index(req)] = res
-
end
-
-
75
responses
-
end
-
end
-
-
7
module ConnectionMethods
-
7
def initialize(*)
-
begin
-
68
super
-
8
rescue ServerSideRequestForgeryError => e
-
# may raise when IPs are passed as options via :addresses
-
14
throw(:resolve_error, e)
-
end
-
end
-
-
7
def addresses=(addrs)
-
150
addrs = addrs.map { |addr| addr.is_a?(IPAddr) ? addr : IPAddr.new(addr) }
-
-
68
addrs.reject!(&SsrfFilter.method(:unsafe_ip_address?))
-
-
68
raise ServerSideRequestForgeryError, "#{@origin.host} has no public IP addresses" if addrs.empty?
-
-
14
super
-
end
-
end
-
end
-
-
7
register_plugin :ssrf_filter, SsrfFilter
-
end
-
end
-
# frozen_string_literal: true
-
-
12
module HTTPX
-
12
class StreamResponse
-
12
def initialize(request, session)
-
147
@request = request
-
147
@session = session
-
147
@response = nil
-
end
-
-
12
def each(&block)
-
189
return enum_for(__method__) unless block
-
-
133
@request.stream = self
-
-
13
begin
-
133
@on_chunk = block
-
-
133
if @request.response
-
# if we've already started collecting the payload, yield it first
-
# before proceeding.
-
14
body = @request.response.body
-
-
14
body.each do |chunk|
-
14
on_chunk(chunk)
-
end
-
end
-
-
133
response.raise_for_status
-
ensure
-
133
@on_chunk = nil
-
end
-
end
-
-
12
def each_line
-
94
return enum_for(__method__) unless block_given?
-
-
47
line = "".b
-
-
47
each do |chunk|
-
38
line << chunk
-
-
106
while (idx = line.index("\n"))
-
47
yield line.byteslice(0..idx - 1)
-
-
47
line = line.byteslice(idx + 1..-1)
-
end
-
end
-
-
19
yield line unless line.empty?
-
end
-
-
# This is a ghost method. It's to be used ONLY internally, when processing streams
-
12
def on_chunk(chunk)
-
187
raise NoMethodError unless @on_chunk
-
-
187
@on_chunk.call(chunk)
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<StreamResponse:#{object_id}>"
-
skipped
end
-
skipped
# :nocov:
-
-
12
def to_s
-
14
response.to_s
-
end
-
-
12
private
-
-
12
def response
-
463
return @response if @response
-
-
177
@request.response || begin
-
147
@response = @session.request(@request)
-
end
-
end
-
-
12
def respond_to_missing?(meth, *args)
-
14
response.respond_to?(meth, *args) || super
-
end
-
-
12
def method_missing(meth, *args, &block)
-
151
return super unless response.respond_to?(meth)
-
-
151
response.__send__(meth, *args, &block)
-
end
-
end
-
-
12
module Plugins
-
#
-
# This plugin adds support for stream response (text/event-stream).
-
#
-
# https://gitlab.com/os85/httpx/wikis/Stream
-
#
-
12
module Stream
-
12
def self.extra_options(options)
-
256
options.merge(timeout: { read_timeout: Float::INFINITY, operation_timeout: 60 })
-
end
-
-
12
module InstanceMethods
-
12
def request(*args, stream: false, **options)
-
407
return super(*args, **options) unless stream
-
-
161
requests = args.first.is_a?(Request) ? args : build_requests(*args, options)
-
161
raise Error, "only 1 response at a time is supported for streaming requests" unless requests.size == 1
-
-
147
request = requests.first
-
-
147
StreamResponse.new(request, self)
-
end
-
end
-
-
12
module RequestMethods
-
12
attr_accessor :stream
-
end
-
-
12
module ResponseMethods
-
12
def stream
-
241
request = @request.root_request if @request.respond_to?(:root_request)
-
241
request ||= @request
-
-
241
request.stream
-
end
-
end
-
-
12
module ResponseBodyMethods
-
12
def initialize(*)
-
241
super
-
241
@stream = @response.stream
-
end
-
-
12
def write(chunk)
-
320
return super unless @stream
-
-
196
return 0 if chunk.empty?
-
-
173
chunk = decode_chunk(chunk)
-
-
173
@stream.on_chunk(chunk.dup)
-
-
173
chunk.size
-
end
-
-
12
private
-
-
12
def transition(*)
-
155
return if @stream
-
-
155
super
-
end
-
end
-
end
-
12
register_plugin :stream, Stream
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# This plugin helps negotiating a new protocol from an HTTP/1.1 connection, via the
-
# Upgrade header.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Upgrade
-
#
-
7
module Upgrade
-
7
class << self
-
7
def configure(klass)
-
28
klass.plugin(:"upgrade/h2")
-
end
-
-
7
def extra_options(options)
-
28
options.merge(upgrade_handlers: {})
-
end
-
end
-
-
7
module OptionsMethods
-
7
def option_upgrade_handlers(value)
-
77
raise TypeError, ":upgrade_handlers must be a Hash" unless value.is_a?(Hash)
-
-
77
value
-
end
-
end
-
-
7
module InstanceMethods
-
7
def fetch_response(request, connections, options)
-
236
response = super
-
-
236
if response
-
77
return response unless response.is_a?(Response)
-
-
77
return response unless response.headers.key?("upgrade")
-
-
28
upgrade_protocol = response.headers["upgrade"].split(/ *, */).first
-
-
28
return response unless upgrade_protocol && options.upgrade_handlers.key?(upgrade_protocol)
-
-
28
protocol_handler = options.upgrade_handlers[upgrade_protocol]
-
-
28
return response unless protocol_handler
-
-
28
log { "upgrading to #{upgrade_protocol}..." }
-
28
connection = find_connection(request, connections, options)
-
-
# do not upgrade already upgraded connections
-
28
return if connection.upgrade_protocol == upgrade_protocol
-
-
28
protocol_handler.call(connection, request, response)
-
-
# keep in the loop if the server is switching, unless
-
# the connection has been hijacked, in which case you want
-
# to terminante immediately
-
28
return if response.status == 101 && !connection.hijacked
-
end
-
-
173
response
-
end
-
-
7
def close(*args)
-
35
return super if args.empty?
-
-
21
connections, = args
-
-
21
pool.close(connections.reject(&:hijacked))
-
end
-
end
-
-
7
module ConnectionMethods
-
7
attr_reader :upgrade_protocol, :hijacked
-
-
7
def hijack_io
-
7
@hijacked = true
-
end
-
end
-
end
-
7
register_plugin(:upgrade, Upgrade)
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# This plugin adds support for upgrading an HTTP/1.1 connection to HTTP/2
-
# via an Upgrade: h2 response declaration
-
#
-
# https://gitlab.com/os85/httpx/wikis/Connection-Upgrade#h2
-
#
-
7
module H2
-
7
class << self
-
7
def extra_options(options)
-
28
options.merge(upgrade_handlers: options.upgrade_handlers.merge("h2" => self))
-
end
-
-
7
def call(connection, _request, _response)
-
7
connection.upgrade_to_h2
-
end
-
end
-
-
7
module ConnectionMethods
-
7
using URIExtensions
-
-
7
def upgrade_to_h2
-
7
prev_parser = @parser
-
-
7
if prev_parser
-
7
prev_parser.reset
-
6
@inflight -= prev_parser.requests.size
-
end
-
-
7
@parser = Connection::HTTP2.new(@write_buffer, @options)
-
7
set_parser_callbacks(@parser)
-
7
@upgrade_protocol = "h2"
-
-
# what's happening here:
-
# a deviation from the state machine is done to perform the actions when a
-
# connection is closed, without transitioning, so the connection is kept in the pool.
-
# the state is reset to initial, so that the socket reconnect works out of the box,
-
# while the parser is already here.
-
7
purge_after_closed
-
7
transition(:idle)
-
-
7
prev_parser.requests.each do |req|
-
req.transition(:idle)
-
send(req)
-
end
-
end
-
end
-
end
-
7
register_plugin(:"upgrade/h2", H2)
-
end
-
end
-
# frozen_string_literal: true
-
-
7
module HTTPX
-
7
module Plugins
-
#
-
# This plugin implements convenience methods for performing WEBDAV requests.
-
#
-
# https://gitlab.com/os85/httpx/wikis/WebDav
-
#
-
7
module WebDav
-
7
module InstanceMethods
-
7
def copy(src, dest)
-
14
request("COPY", src, headers: { "destination" => @options.origin.merge(dest) })
-
end
-
-
7
def move(src, dest)
-
14
request("MOVE", src, headers: { "destination" => @options.origin.merge(dest) })
-
end
-
-
7
def lock(path, timeout: nil, &blk)
-
42
headers = {}
-
36
headers["timeout"] = if timeout && timeout.positive?
-
14
"Second-#{timeout}"
-
else
-
28
"Infinite, Second-4100000000"
-
end
-
42
xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" \
-
"<D:lockinfo xmlns:D=\"DAV:\">" \
-
"<D:lockscope><D:exclusive/></D:lockscope>" \
-
"<D:locktype><D:write/></D:locktype>" \
-
"<D:owner>null</D:owner>" \
-
"</D:lockinfo>"
-
42
response = request("LOCK", path, headers: headers, xml: xml)
-
-
42
return response unless response.is_a?(Response)
-
-
42
return response unless blk && response.status == 200
-
-
14
lock_token = response.headers["lock-token"]
-
-
1
begin
-
14
blk.call(response)
-
ensure
-
14
unlock(path, lock_token)
-
end
-
end
-
-
7
def unlock(path, lock_token)
-
28
request("UNLOCK", path, headers: { "lock-token" => lock_token })
-
end
-
-
7
def mkcol(dir)
-
14
request("MKCOL", dir)
-
end
-
-
7
def propfind(path, xml = nil)
-
56
body = case xml
-
when :acl
-
14
'<?xml version="1.0" encoding="utf-8" ?><D:propfind xmlns:D="DAV:"><D:prop><D:owner/>' \
-
"<D:supported-privilege-set/><D:current-user-privilege-set/><D:acl/></D:prop></D:propfind>"
-
when nil
-
28
'<?xml version="1.0" encoding="utf-8"?><DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
-
else
-
14
xml
-
end
-
-
56
request("PROPFIND", path, headers: { "depth" => "1" }, xml: body)
-
end
-
-
7
def proppatch(path, xml)
-
4
body = "<?xml version=\"1.0\"?>" \
-
12
"<D:propertyupdate xmlns:D=\"DAV:\" xmlns:Z=\"http://ns.example.com/standards/z39.50/\">#{xml}</D:propertyupdate>"
-
14
request("PROPPATCH", path, xml: body)
-
end
-
# %i[ orderpatch acl report search]
-
end
-
end
-
7
register_plugin(:webdav, WebDav)
-
end
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
module ResponsePatternMatchExtensions
-
24
def deconstruct
-
36
[@status, @headers, @body]
-
end
-
-
24
def deconstruct_keys(_keys)
-
60
{ status: @status, headers: @headers, body: @body }
-
end
-
end
-
-
24
module ErrorResponsePatternMatchExtensions
-
24
def deconstruct
-
10
[@error]
-
end
-
-
24
def deconstruct_keys(_keys)
-
30
{ error: @error }
-
end
-
end
-
-
24
module HeadersPatternMatchExtensions
-
24
def deconstruct
-
6
to_a
-
end
-
end
-
-
24
Headers.include HeadersPatternMatchExtensions
-
24
Response.include ResponsePatternMatchExtensions
-
24
ErrorResponse.include ErrorResponsePatternMatchExtensions
-
end
-
# frozen_string_literal: true
-
-
24
require "forwardable"
-
24
require "httpx/selector"
-
24
require "httpx/connection"
-
24
require "httpx/resolver"
-
-
24
module HTTPX
-
24
class Pool
-
24
using ArrayExtensions::FilterMap
-
24
extend Forwardable
-
-
24
def_delegator :@timers, :after
-
-
24
def initialize
-
548
@resolvers = {}
-
548
@timers = Timers.new
-
548
@selector = Selector.new
-
548
@connections = []
-
end
-
-
24
def wrap
-
425
connections = @connections
-
425
@connections = []
-
-
46
begin
-
425
yield self
-
ensure
-
425
@connections.unshift(*connections)
-
end
-
end
-
-
24
def empty?
-
786
@connections.empty?
-
end
-
-
24
def next_tick
-
2229253
catch(:jump_tick) do
-
2229253
timeout = next_timeout
-
2229253
if timeout && timeout.negative?
-
@timers.fire
-
throw(:jump_tick)
-
end
-
-
1068202
begin
-
2229253
@selector.select(timeout, &:call)
-
2229138
@timers.fire
-
rescue TimeoutError => e
-
5
@timers.fire(e)
-
end
-
end
-
rescue StandardError => e
-
24
@connections.each do |connection|
-
28
connection.emit(:error, e)
-
end
-
rescue Exception # rubocop:disable Lint/RescueException
-
91
@connections.each(&:force_reset)
-
84
raise
-
end
-
-
24
def close(connections = @connections)
-
5619
return if connections.empty?
-
-
5477
connections = connections.reject(&:inflight?)
-
5477
connections.each(&:terminate)
-
11097
next_tick until connections.none? { |c| c.state != :idle && @connections.include?(c) }
-
-
# close resolvers
-
5470
outstanding_connections = @connections
-
5470
resolver_connections = @resolvers.each_value.flat_map(&:connections).compact
-
4753
outstanding_connections -= resolver_connections
-
-
5470
return unless outstanding_connections.empty?
-
-
2928
@resolvers.each_value do |resolver|
-
2768
resolver.close unless resolver.closed?
-
end
-
# for https resolver
-
2928
resolver_connections.each(&:terminate)
-
2963
next_tick until resolver_connections.none? { |c| c.state != :idle && @connections.include?(c) }
-
end
-
-
24
def init_connection(connection, _options)
-
5922
connection.timers = @timers
-
5922
connection.on(:activate) do
-
493
select_connection(connection)
-
end
-
5922
connection.on(:exhausted) do
-
6
case connection.state
-
when :closed
-
7
connection.idling
-
7
@connections << connection
-
7
select_connection(connection)
-
when :closing
-
connection.once(:close) do
-
connection.idling
-
@connections << connection
-
select_connection(connection)
-
end
-
end
-
end
-
5922
connection.on(:close) do
-
6616
unregister_connection(connection)
-
end
-
5922
connection.on(:terminate) do
-
5280
unregister_connection(connection, true)
-
end
-
5922
resolve_connection(connection) unless connection.family
-
end
-
-
24
def deactivate(*connections)
-
978
connections.each do |connection|
-
1013
connection.deactivate
-
1013
deselect_connection(connection) if connection.state == :inactive
-
end
-
end
-
-
# opens a connection to the IP reachable through +uri+.
-
# Many hostnames are reachable through the same IP, so we try to
-
# maximize pipelining by opening as few connections as possible.
-
#
-
24
def find_connection(uri, options)
-
7437
conn = @connections.find do |connection|
-
12583
connection.match?(uri, options)
-
end
-
-
7437
return unless conn
-
-
1373
case conn.state
-
when :closed
-
396
conn.idling
-
396
select_connection(conn)
-
when :closing
-
conn.once(:close) do
-
conn.idling
-
select_connection(conn)
-
end
-
end
-
-
1494
conn
-
end
-
-
24
private
-
-
24
def resolve_connection(connection)
-
5942
@connections << connection unless @connections.include?(connection)
-
-
5942
if connection.addresses || connection.open?
-
#
-
# there are two cases in which we want to activate initialization of
-
# connection immediately:
-
#
-
# 1. when the connection already has addresses, i.e. it doesn't need to
-
# resolve a name (not the same as name being an IP, yet)
-
# 2. when the connection is initialized with an external already open IO.
-
#
-
206
connection.once(:connect_error, &connection.method(:handle_error))
-
206
on_resolver_connection(connection)
-
197
return
-
end
-
-
5736
find_resolver_for(connection) do |resolver|
-
400
resolver << try_clone_connection(connection, resolver.family)
-
390
next if resolver.empty?
-
-
319
select_connection(resolver)
-
end
-
end
-
-
24
def try_clone_connection(connection, family)
-
400
connection.family ||= family
-
-
400
return connection if connection.family == family
-
-
new_connection = connection.class.new(connection.origin, connection.options)
-
new_connection.family = family
-
-
connection.once(:tcp_open) { new_connection.force_reset }
-
connection.once(:connect_error) do |err|
-
if new_connection.connecting?
-
new_connection.merge(connection)
-
connection.emit(:cloned, new_connection)
-
connection.force_reset
-
else
-
connection.__send__(:handle_error, err)
-
end
-
end
-
-
new_connection.once(:tcp_open) do |new_conn|
-
if new_conn != connection
-
new_conn.merge(connection)
-
connection.force_reset
-
end
-
end
-
new_connection.once(:connect_error) do |err|
-
if connection.connecting?
-
# main connection has the requests
-
connection.merge(new_connection)
-
new_connection.emit(:cloned, connection)
-
new_connection.force_reset
-
else
-
new_connection.__send__(:handle_error, err)
-
end
-
end
-
-
init_connection(new_connection, connection.options)
-
new_connection
-
end
-
-
24
def on_resolver_connection(connection)
-
5927
@connections << connection unless @connections.include?(connection)
-
5927
found_connection = @connections.find do |ch|
-
15857
ch != connection && ch.mergeable?(connection)
-
end
-
5927
return register_connection(connection) unless found_connection
-
-
23
if found_connection.open?
-
22
coalesce_connections(found_connection, connection)
-
22
throw(:coalesced, found_connection) unless @connections.include?(connection)
-
else
-
1
found_connection.once(:open) do
-
1
coalesce_connections(found_connection, connection)
-
end
-
end
-
end
-
-
24
def on_resolver_error(connection, error)
-
160
return connection.emit(:connect_error, error) if connection.connecting? && connection.callbacks_for?(:connect_error)
-
-
160
connection.emit(:error, error)
-
end
-
-
24
def on_resolver_close(resolver)
-
205
resolver_type = resolver.class
-
205
return if resolver.closed?
-
-
205
@resolvers.delete(resolver_type)
-
-
205
deselect_connection(resolver)
-
205
resolver.close unless resolver.closed?
-
end
-
-
24
def register_connection(connection)
-
5916
select_connection(connection)
-
end
-
-
24
def unregister_connection(connection, cleanup = !connection.used?)
-
11916
@connections.delete(connection) if cleanup
-
11916
deselect_connection(connection)
-
end
-
-
24
def select_connection(connection)
-
7131
@selector.register(connection)
-
end
-
-
24
def deselect_connection(connection)
-
12683
@selector.deregister(connection)
-
end
-
-
24
def coalesce_connections(conn1, conn2)
-
23
return register_connection(conn2) unless conn1.coalescable?(conn2)
-
-
11
conn2.emit(:tcp_open, conn1)
-
11
conn1.merge(conn2)
-
11
@connections.delete(conn2)
-
end
-
-
24
def next_timeout
-
1128608
[
-
32442
@timers.wait_interval,
-
*@resolvers.values.reject(&:closed?).filter_map(&:timeout),
-
*@connections.filter_map(&:timeout),
-
1068202
].compact.min
-
end
-
-
24
def find_resolver_for(connection)
-
5736
connection_options = connection.options
-
5736
resolver_type = connection_options.resolver_class
-
5736
resolver_type = Resolver.resolver_for(resolver_type)
-
-
5736
@resolvers[resolver_type] ||= begin
-
668
resolver_manager = if resolver_type.multi?
-
647
Resolver::Multi.new(resolver_type, connection_options)
-
else
-
21
resolver_type.new(connection_options)
-
end
-
668
resolver_manager.on(:resolve, &method(:on_resolver_connection))
-
668
resolver_manager.on(:error, &method(:on_resolver_error))
-
668
resolver_manager.on(:close, &method(:on_resolver_close))
-
668
resolver_manager
-
end
-
-
5736
manager = @resolvers[resolver_type]
-
-
5736
(manager.is_a?(Resolver::Multi) && manager.early_resolve(connection)) || manager.resolvers.each do |resolver|
-
400
resolver.pool = self
-
400
yield resolver
-
end
-
-
5687
manager
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
module Punycode
-
24
module_function
-
-
begin
-
24
require "idnx"
-
-
23
def encode_hostname(hostname)
-
28
Idnx.to_punycode(hostname)
-
end
-
rescue LoadError
-
1
def encode_hostname(hostname)
-
1
warn "#{hostname} cannot be converted to punycode. Install the " \
-
"\"idnx\" gem: https://github.com/HoneyryderChuck/idnx"
-
-
1
hostname
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "delegate"
-
24
require "forwardable"
-
-
24
module HTTPX
-
# Defines how an HTTP request is handled internally, both in terms of making attributes accessible,
-
# as well as maintaining the state machine which manages streaming the request onto the wire.
-
24
class Request
-
24
extend Forwardable
-
24
include Callbacks
-
24
using URIExtensions
-
-
# default value used for "user-agent" header, when not overridden.
-
24
USER_AGENT = "httpx.rb/#{VERSION}"
-
-
# the upcased string HTTP verb for this request.
-
24
attr_reader :verb
-
-
# the absolute URI object for this request.
-
24
attr_reader :uri
-
-
# an HTTPX::Headers object containing the request HTTP headers.
-
24
attr_reader :headers
-
-
# an HTTPX::Request::Body object containing the request body payload (or +nil+, whenn there is none).
-
24
attr_reader :body
-
-
# a symbol describing which frame is currently being flushed.
-
24
attr_reader :state
-
-
# an HTTPX::Options object containing request options.
-
24
attr_reader :options
-
-
# the corresponding HTTPX::Response object, when there is one.
-
24
attr_reader :response
-
-
# Exception raised during enumerable body writes.
-
24
attr_reader :drain_error
-
-
# The IP address from the peer server.
-
24
attr_accessor :peer_address
-
-
24
attr_writer :persistent
-
-
# will be +true+ when request body has been completely flushed.
-
24
def_delegator :@body, :empty?
-
-
# initializes the instance with the given +verb+ (an upppercase String, ex. 'GEt'),
-
# an absolute or relative +uri+ (either as String or URI::HTTP object), the
-
# request +options+ (instance of HTTPX::Options) and an optional Hash of +params+.
-
#
-
# Besides any of the options documented in HTTPX::Options (which would override or merge with what
-
# +options+ sets), it accepts also the following:
-
#
-
# :params :: hash or array of key-values which will be encoded and set in the query string of request uris.
-
# :body :: to be encoded in the request body payload. can be a String, an IO object (i.e. a File), or an Enumerable.
-
# :form :: hash of array of key-values which will be form-urlencoded- or multipart-encoded in requests body payload.
-
# :json :: hash of array of key-values which will be JSON-encoded in requests body payload.
-
# :xml :: Nokogiri XML nodes which will be encoded in requests body payload.
-
#
-
# :body, :form, :json and :xml are all mutually exclusive, i.e. only one of them gets picked up.
-
24
def initialize(verb, uri, options, params = EMPTY_HASH)
-
7975
@verb = verb.to_s.upcase
-
7975
@uri = Utils.to_uri(uri)
-
-
7974
@headers = options.headers.dup
-
7974
merge_headers(params.delete(:headers)) if params.key?(:headers)
-
-
7974
@headers["user-agent"] ||= USER_AGENT
-
7974
@headers["accept"] ||= "*/*"
-
-
# forego compression in the Range request case
-
7974
if @headers.key?("range")
-
7
@headers.delete("accept-encoding")
-
else
-
7967
@headers["accept-encoding"] ||= options.supported_compression_formats
-
end
-
-
7974
@query_params = params.delete(:params) if params.key?(:params)
-
-
7974
@body = options.request_body_class.new(@headers, options, **params)
-
-
7967
@options = @body.options
-
-
7967
if @uri.relative? || @uri.host.nil?
-
524
origin = @options.origin
-
524
raise(Error, "invalid URI: #{@uri}") unless origin
-
-
504
base_path = @options.base_path
-
-
504
@uri = origin.merge("#{base_path}#{@uri}")
-
end
-
-
7947
@state = :idle
-
7947
@response = nil
-
7947
@peer_address = nil
-
7947
@persistent = @options.persistent
-
end
-
-
# the read timeout defined for this requet.
-
24
def read_timeout
-
17419
@options.timeout[:read_timeout]
-
end
-
-
# the write timeout defined for this requet.
-
24
def write_timeout
-
17419
@options.timeout[:write_timeout]
-
end
-
-
# the request timeout defined for this requet.
-
24
def request_timeout
-
17170
@options.timeout[:request_timeout]
-
end
-
-
24
def persistent?
-
3951
@persistent
-
end
-
-
# if the request contains trailer headers
-
24
def trailers?
-
2448
defined?(@trailers)
-
end
-
-
# returns an instance of HTTPX::Headers containing the trailer headers
-
24
def trailers
-
77
@trailers ||= @options.headers_class.new
-
end
-
-
# returns +:r+ or +:w+, depending on whether the request is waiting for a response or flushing.
-
24
def interests
-
20598
return :r if @state == :done || @state == :expect
-
-
2725
:w
-
end
-
-
# merges +h+ into the instance of HTTPX::Headers of the request.
-
24
def merge_headers(h)
-
671
@headers = @headers.merge(h)
-
end
-
-
# the URI scheme of the request +uri+.
-
24
def scheme
-
2941
@uri.scheme
-
end
-
-
# sets the +response+ on this request.
-
24
def response=(response)
-
7549
return unless response
-
-
7549
if response.is_a?(Response) && response.status < 200
-
# deal with informational responses
-
-
140
if response.status == 100 && @headers.key?("expect")
-
119
@informational_status = response.status
-
119
return
-
end
-
-
# 103 Early Hints advertises resources in document to browsers.
-
# not very relevant for an HTTP client, discard.
-
21
return if response.status >= 103
-
end
-
-
7430
@response = response
-
-
7430
emit(:response_started, response)
-
end
-
-
# returnns the URI path of the request +uri+.
-
24
def path
-
7041
path = uri.path.dup
-
7041
path = +"" if path.nil?
-
7041
path << "/" if path.empty?
-
7041
path << "?#{query}" unless query.empty?
-
7041
path
-
end
-
-
# returs the URI authority of the request.
-
#
-
# session.build_request("GET", "https://google.com/query").authority #=> "google.com"
-
# session.build_request("GET", "http://internal:3182/a").authority #=> "internal:3182"
-
24
def authority
-
7081
@uri.authority
-
end
-
-
# returs the URI origin of the request.
-
#
-
# session.build_request("GET", "https://google.com/query").authority #=> "https://google.com"
-
# session.build_request("GET", "http://internal:3182/a").authority #=> "http://internal:3182"
-
24
def origin
-
3160
@uri.origin
-
end
-
-
# returs the URI query string of the request (when available).
-
#
-
# session.build_request("GET", "https://search.com").query #=> ""
-
# session.build_request("GET", "https://search.com?q=a").query #=> "q=a"
-
# session.build_request("GET", "https://search.com", params: { q: "a"}).query #=> "q=a"
-
# session.build_request("GET", "https://search.com?q=a", params: { foo: "bar"}).query #=> "q=a&foo&bar"
-
24
def query
-
7814
return @query if defined?(@query)
-
-
6523
query = []
-
6523
if (q = @query_params)
-
132
query << Transcoder::Form.encode(q)
-
end
-
6523
query << @uri.query if @uri.query
-
6523
@query = query.join("&")
-
end
-
-
# consumes and returns the next available chunk of request body that can be sent
-
24
def drain_body
-
7727
return nil if @body.nil?
-
-
7727
@drainer ||= @body.each
-
7727
chunk = @drainer.next.dup
-
-
5241
emit(:body_chunk, chunk)
-
5241
chunk
-
rescue StopIteration
-
2476
nil
-
rescue StandardError => e
-
10
@drain_error = e
-
10
nil
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<HTTPX::Request:#{object_id} " \
-
skipped
"#{@verb} " \
-
skipped
"#{uri} " \
-
skipped
"@headers=#{@headers} " \
-
skipped
"@body=#{@body}>"
-
skipped
end
-
skipped
# :nocov:
-
-
# moves on to the +nextstate+ of the request state machine (when all preconditions are met)
-
24
def transition(nextstate)
-
28677
case nextstate
-
when :idle
-
606
@body.rewind
-
606
@response = nil
-
606
@drainer = nil
-
when :headers
-
8882
return unless @state == :idle
-
when :body
-
8868
return unless @state == :headers ||
-
@state == :expect
-
-
7190
if @headers.key?("expect")
-
438
if @informational_status && @informational_status == 100
-
# check for 100 Continue response, and deallocate the var
-
# if @informational_status == 100
-
# @response = nil
-
# end
-
else
-
326
return if @state == :expect # do not re-set it
-
-
126
nextstate = :expect
-
end
-
end
-
when :trailers
-
7176
return unless @state == :body
-
when :done
-
7183
return if @state == :expect
-
end
-
28174
@state = nextstate
-
28174
emit(@state, self)
-
6772
nil
-
end
-
-
# whether the request supports the 100-continue handshake and already processed the 100 response.
-
24
def expects?
-
6607
@headers["expect"] == "100-continue" && @informational_status == 100 && !@response
-
end
-
end
-
end
-
-
24
require_relative "request/body"
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
# Implementation of the HTTP Request body as a delegator which iterates (responds to +each+) payload chunks.
-
24
class Request::Body < SimpleDelegator
-
24
class << self
-
24
def new(_, options, body: nil, **params)
-
7981
if body.is_a?(self)
-
# request derives its options from body
-
14
body.options = options.merge(params)
-
12
return body
-
end
-
-
7967
super
-
end
-
end
-
-
24
attr_accessor :options
-
-
# inits the instance with the request +headers+, +options+ and +params+, which contain the payload definition.
-
# it wraps the given body with the appropriate encoder on initialization.
-
#
-
# ..., json: { foo: "bar" }) #=> json encoder
-
# ..., form: { foo: "bar" }) #=> form urlencoded encoder
-
# ..., form: { foo: Pathname.open("path/to/file") }) #=> multipart urlencoded encoder
-
# ..., form: { foo: File.open("path/to/file") }) #=> multipart urlencoded encoder
-
# ..., form: { body: "bla") }) #=> raw data encoder
-
24
def initialize(headers, options, body: nil, form: nil, json: nil, xml: nil, **params)
-
7967
@headers = headers
-
7967
@options = options.merge(params)
-
-
7967
@body = if body
-
1043
Transcoder::Body.encode(body)
-
6923
elsif form
-
1302
Transcoder::Form.encode(form)
-
5621
elsif json
-
63
Transcoder::JSON.encode(json)
-
5558
elsif xml
-
119
Transcoder::Xml.encode(xml)
-
end
-
-
7967
if @body
-
2527
if @options.compress_request_body && @headers.key?("content-encoding")
-
-
69
@headers.get("content-encoding").each do |encoding|
-
69
@body = self.class.initialize_deflater_body(@body, encoding)
-
end
-
end
-
-
2527
@headers["content-type"] ||= @body.content_type
-
2527
@headers["content-length"] = @body.bytesize unless unbounded_body?
-
end
-
-
7960
super(@body)
-
end
-
-
# consumes and yields the request payload in chunks.
-
24
def each(&block)
-
5210
return enum_for(__method__) unless block
-
2605
return if @body.nil?
-
-
2542
body = stream(@body)
-
2542
if body.respond_to?(:read)
-
1087
::IO.copy_stream(body, ProcIO.new(block))
-
1454
elsif body.respond_to?(:each)
-
346
body.each(&block)
-
else
-
1109
block[body.to_s]
-
end
-
end
-
-
# if the +@body+ is rewindable, it rewinnds it.
-
24
def rewind
-
718
return if empty?
-
-
133
@body.rewind if @body.respond_to?(:rewind)
-
end
-
-
# return +true+ if the +body+ has been fully drained (or does nnot exist).
-
24
def empty?
-
15546
return true if @body.nil?
-
6912
return false if chunked?
-
-
6828
@body.bytesize.zero?
-
end
-
-
# returns the +@body+ payload size in bytes.
-
24
def bytesize
-
2764
return 0 if @body.nil?
-
-
112
@body.bytesize
-
end
-
-
# sets the body to yield using chunked trannsfer encoding format.
-
24
def stream(body)
-
2542
return body unless chunked?
-
-
84
Transcoder::Chunker.encode(body.enum_for(:each))
-
end
-
-
# returns whether the body yields infinitely.
-
24
def unbounded_body?
-
3017
return @unbounded_body if defined?(@unbounded_body)
-
-
2527
@unbounded_body = !@body.nil? && (chunked? || @body.bytesize == Float::INFINITY)
-
end
-
-
# returns whether the chunked transfer encoding header is set.
-
24
def chunked?
-
16109
@headers["transfer-encoding"] == "chunked"
-
end
-
-
# sets the chunked transfer encoding header.
-
24
def chunk!
-
28
@headers.add("transfer-encoding", "chunked")
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<HTTPX::Request::Body:#{object_id} " \
-
skipped
"#{unbounded_body? ? "stream" : "@bytesize=#{bytesize}"}>"
-
skipped
end
-
skipped
# :nocov:
-
-
24
class << self
-
# returns the +body+ wrapped with the correct deflater accordinng to the given +encodisng+.
-
24
def initialize_deflater_body(body, encoding)
-
62
case encoding
-
when "gzip"
-
34
Transcoder::GZIP.encode(body)
-
when "deflate"
-
14
Transcoder::Deflate.encode(body)
-
when "identity"
-
14
body
-
else
-
7
body
-
end
-
end
-
end
-
end
-
-
# Wrapper yielder which can be used with functions which expect an IO writer.
-
24
class ProcIO
-
24
def initialize(block)
-
1087
@block = block
-
end
-
-
# Implementation the IO write protocol, which yield the given chunk to +@block+.
-
24
def write(data)
-
2995
@block.call(data.dup)
-
2988
data.bytesize
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "resolv"
-
24
require "ipaddr"
-
-
24
module HTTPX
-
24
module Resolver
-
24
RESOLVE_TIMEOUT = [2, 3].freeze
-
-
24
require "httpx/resolver/resolver"
-
24
require "httpx/resolver/system"
-
24
require "httpx/resolver/native"
-
24
require "httpx/resolver/https"
-
24
require "httpx/resolver/multi"
-
-
24
@lookup_mutex = Thread::Mutex.new
-
173
@lookups = Hash.new { |h, k| h[k] = [] }
-
-
24
@identifier_mutex = Thread::Mutex.new
-
24
@identifier = 1
-
24
@system_resolver = Resolv::Hosts.new
-
-
24
module_function
-
-
24
def resolver_for(resolver_type)
-
5021
case resolver_type
-
5617
when :native then Native
-
28
when :system then System
-
62
when :https then HTTPS
-
else
-
64
return resolver_type if resolver_type.is_a?(Class) && resolver_type < Resolver
-
-
7
raise Error, "unsupported resolver type (#{resolver_type})"
-
end
-
end
-
-
24
def nolookup_resolve(hostname)
-
5611
ip_resolve(hostname) || cached_lookup(hostname) || system_resolve(hostname)
-
end
-
-
24
def ip_resolve(hostname)
-
5611
[IPAddr.new(hostname)]
-
rescue ArgumentError
-
end
-
-
24
def system_resolve(hostname)
-
467
ips = @system_resolver.getaddresses(hostname)
-
467
return if ips.empty?
-
-
579
ips.map { |ip| IPAddr.new(ip) }
-
rescue IOError
-
end
-
-
24
def cached_lookup(hostname)
-
5329
now = Utils.now
-
5329
@lookup_mutex.synchronize do
-
5329
lookup(hostname, now)
-
end
-
end
-
-
24
def cached_lookup_set(hostname, family, entries)
-
204
now = Utils.now
-
204
entries.each do |entry|
-
256
entry["TTL"] += now
-
end
-
204
@lookup_mutex.synchronize do
-
175
case family
-
when Socket::AF_INET6
-
35
@lookups[hostname].concat(entries)
-
when Socket::AF_INET
-
169
@lookups[hostname].unshift(*entries)
-
end
-
204
entries.each do |entry|
-
256
next unless entry["name"] != hostname
-
-
24
case family
-
when Socket::AF_INET6
-
7
@lookups[entry["name"]] << entry
-
when Socket::AF_INET
-
19
@lookups[entry["name"]].unshift(entry)
-
end
-
end
-
end
-
end
-
-
# do not use directly!
-
24
def lookup(hostname, ttl)
-
5336
return unless @lookups.key?(hostname)
-
-
4864
entries = @lookups[hostname] = @lookups[hostname].select do |address|
-
11631
address["TTL"] > ttl
-
end
-
-
4864
ips = entries.flat_map do |address|
-
11621
if address.key?("alias")
-
7
lookup(address["alias"], ttl)
-
else
-
11614
IPAddr.new(address["data"])
-
end
-
end.compact
-
-
4864
ips unless ips.empty?
-
end
-
-
24
def generate_id
-
1326
@identifier_mutex.synchronize { @identifier = (@identifier + 1) & 0xFFFF }
-
end
-
-
24
def encode_dns_query(hostname, type: Resolv::DNS::Resource::IN::A, message_id: generate_id)
-
611
Resolv::DNS::Message.new.tap do |query|
-
663
query.id = message_id
-
663
query.rd = 1
-
663
query.add_question(hostname, type)
-
103
end.encode
-
end
-
-
24
def decode_dns_answer(payload)
-
51
begin
-
608
message = Resolv::DNS::Message.decode(payload)
-
rescue Resolv::DNS::DecodeError => e
-
5
return :decode_error, e
-
end
-
-
# no domain was found
-
603
return :no_domain_found if message.rcode == Resolv::DNS::RCode::NXDomain
-
-
241
return :message_truncated if message.tc == 1
-
-
231
return :dns_error, message.rcode if message.rcode != Resolv::DNS::RCode::NoError
-
-
221
addresses = []
-
-
221
message.each_answer do |question, _, value|
-
866
case value
-
when Resolv::DNS::Resource::IN::CNAME
-
18
addresses << {
-
"name" => question.to_s,
-
"TTL" => value.ttl,
-
"alias" => value.name.to_s,
-
}
-
when Resolv::DNS::Resource::IN::A,
-
Resolv::DNS::Resource::IN::AAAA
-
876
addresses << {
-
21
"name" => question.to_s,
-
"TTL" => value.ttl,
-
"data" => value.address.to_s,
-
}
-
end
-
end
-
-
221
[:ok, addresses]
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "resolv"
-
24
require "uri"
-
24
require "cgi"
-
24
require "forwardable"
-
24
require "httpx/base64"
-
-
24
module HTTPX
-
24
class Resolver::HTTPS < Resolver::Resolver
-
24
extend Forwardable
-
24
using URIExtensions
-
-
24
module DNSExtensions
-
24
refine Resolv::DNS do
-
24
def generate_candidates(name)
-
35
@config.generate_candidates(name)
-
end
-
end
-
end
-
24
using DNSExtensions
-
-
24
NAMESERVER = "https://1.1.1.1/dns-query"
-
-
2
DEFAULTS = {
-
22
uri: NAMESERVER,
-
use_get: false,
-
}.freeze
-
-
24
def_delegators :@resolver_connection, :state, :connecting?, :to_io, :call, :close, :terminate
-
-
24
def initialize(_, options)
-
40
super
-
40
@resolver_options = DEFAULTS.merge(@options.resolver_options)
-
40
@queries = {}
-
40
@requests = {}
-
40
@connections = []
-
40
@uri = URI(@resolver_options[:uri])
-
40
@uri_addresses = nil
-
40
@resolver = Resolv::DNS.new
-
40
@resolver.timeouts = @resolver_options.fetch(:timeouts, Resolver::RESOLVE_TIMEOUT)
-
40
@resolver.lazy_initialize
-
end
-
-
24
def <<(connection)
-
75
return if @uri.origin == connection.origin.to_s
-
-
40
@uri_addresses ||= HTTPX::Resolver.nolookup_resolve(@uri.host) || @resolver.getaddresses(@uri.host)
-
-
40
if @uri_addresses.empty?
-
5
ex = ResolveError.new("Can't resolve DNS server #{@uri.host}")
-
5
ex.set_backtrace(caller)
-
5
connection.force_reset
-
5
throw(:resolve_error, ex)
-
end
-
-
35
resolve(connection)
-
end
-
-
24
def closed?
-
199
true
-
end
-
-
24
def empty?
-
70
true
-
end
-
-
24
def resolver_connection
-
90
@resolver_connection ||= @pool.find_connection(@uri, @options) || begin
-
35
@building_connection = true
-
35
connection = @options.connection_class.new(@uri, @options.merge(ssl: { alpn_protocols: %w[h2] }))
-
35
@pool.init_connection(connection, @options)
-
# only explicity emit addresses if connection didn't pre-resolve, i.e. it's not an IP.
-
35
catch(:coalesced) do
-
35
@building_connection = false
-
35
emit_addresses(connection, @family, @uri_addresses) unless connection.addresses
-
35
connection
-
end
-
end
-
end
-
-
24
private
-
-
24
def resolve(connection = @connections.first, hostname = nil)
-
55
return if @building_connection
-
55
return unless connection
-
-
55
hostname ||= @queries.key(connection)
-
-
55
if hostname.nil?
-
35
hostname = connection.origin.host
-
35
log { "resolver: resolve IDN #{connection.origin.non_ascii_hostname} as #{hostname}" } if connection.origin.non_ascii_hostname
-
-
35
hostname = @resolver.generate_candidates(hostname).each do |name|
-
105
@queries[name.to_s] = connection
-
end.first.to_s
-
else
-
20
@queries[hostname] = connection
-
end
-
55
log { "resolver: query #{FAMILY_TYPES[RECORD_TYPES[@family]]} for #{hostname}" }
-
-
begin
-
55
request = build_request(hostname)
-
55
request.on(:response, &method(:on_response).curry(2)[request])
-
55
request.on(:promise, &method(:on_promise))
-
55
@requests[request] = hostname
-
55
resolver_connection.send(request)
-
55
@connections << connection
-
rescue ResolveError, Resolv::DNS::EncodeError => e
-
reset_hostname(hostname)
-
emit_resolve_error(connection, connection.origin.host, e)
-
end
-
end
-
-
24
def on_response(request, response)
-
55
response.raise_for_status
-
rescue StandardError => e
-
5
hostname = @requests.delete(request)
-
5
connection = reset_hostname(hostname)
-
5
emit_resolve_error(connection, connection.origin.host, e)
-
else
-
# @type var response: HTTPX::Response
-
50
parse(request, response)
-
ensure
-
55
@requests.delete(request)
-
end
-
-
24
def on_promise(_, stream)
-
log(level: 2) { "#{stream.id}: refusing stream!" }
-
stream.refuse
-
end
-
-
24
def parse(request, response)
-
50
code, result = decode_response_body(response)
-
-
50
case code
-
when :ok
-
15
parse_addresses(result, request)
-
when :no_domain_found
-
# Indicates no such domain was found.
-
-
30
host = @requests.delete(request)
-
30
connection = reset_hostname(host, reset_candidates: false)
-
-
30
unless @queries.value?(connection)
-
10
emit_resolve_error(connection)
-
10
return
-
end
-
-
20
resolve
-
when :dns_error
-
host = @requests.delete(request)
-
connection = reset_hostname(host)
-
-
emit_resolve_error(connection)
-
when :decode_error
-
5
host = @requests.delete(request)
-
5
connection = reset_hostname(host)
-
5
emit_resolve_error(connection, connection.origin.host, result)
-
end
-
end
-
-
24
def parse_addresses(answers, request)
-
15
if answers.empty?
-
# no address found, eliminate candidates
-
host = @requests.delete(request)
-
connection = reset_hostname(host)
-
emit_resolve_error(connection)
-
return
-
-
else
-
35
answers = answers.group_by { |answer| answer["name"] }
-
15
answers.each do |hostname, addresses|
-
20
addresses = addresses.flat_map do |address|
-
20
if address.key?("alias")
-
5
alias_address = answers[address["alias"]]
-
5
if alias_address.nil?
-
reset_hostname(address["name"])
-
if catch(:coalesced) { early_resolve(connection, hostname: address["alias"]) }
-
@connections.delete(connection)
-
else
-
resolve(connection, address["alias"])
-
return # rubocop:disable Lint/NonLocalExitFromIterator
-
end
-
else
-
5
alias_address
-
end
-
else
-
15
address
-
end
-
end.compact
-
20
next if addresses.empty?
-
-
20
hostname.delete_suffix!(".") if hostname.end_with?(".")
-
20
connection = reset_hostname(hostname, reset_candidates: false)
-
20
next unless connection # probably a retried query for which there's an answer
-
-
15
@connections.delete(connection)
-
-
# eliminate other candidates
-
45
@queries.delete_if { |_, conn| connection == conn }
-
-
15
Resolver.cached_lookup_set(hostname, @family, addresses) if @resolver_options[:cache]
-
45
catch(:coalesced) { emit_addresses(connection, @family, addresses.map { |addr| addr["data"] }) }
-
end
-
end
-
15
return if @connections.empty?
-
-
resolve
-
end
-
-
24
def build_request(hostname)
-
50
uri = @uri.dup
-
50
rklass = @options.request_class
-
50
payload = Resolver.encode_dns_query(hostname, type: @record_type)
-
-
50
if @resolver_options[:use_get]
-
5
params = URI.decode_www_form(uri.query.to_s)
-
5
params << ["type", FAMILY_TYPES[@record_type]]
-
5
params << ["dns", Base64.urlsafe_encode64(payload, padding: false)]
-
5
uri.query = URI.encode_www_form(params)
-
5
request = rklass.new("GET", uri, @options)
-
else
-
45
request = rklass.new("POST", uri, @options, body: [payload])
-
45
request.headers["content-type"] = "application/dns-message"
-
end
-
50
request.headers["accept"] = "application/dns-message"
-
50
request
-
end
-
-
24
def decode_response_body(response)
-
45
case response.headers["content-type"]
-
when "application/dns-udpwireformat",
-
"application/dns-message"
-
45
Resolver.decode_dns_answer(response.to_s)
-
else
-
raise Error, "unsupported DNS mime-type (#{response.headers["content-type"]})"
-
end
-
end
-
-
24
def reset_hostname(hostname, reset_candidates: true)
-
60
connection = @queries.delete(hostname)
-
-
60
return connection unless connection && reset_candidates
-
-
# eliminate other candidates
-
30
candidates = @queries.select { |_, conn| connection == conn }.keys
-
30
@queries.delete_if { |h, _| candidates.include?(h) }
-
-
10
connection
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "forwardable"
-
24
require "resolv"
-
-
24
module HTTPX
-
24
class Resolver::Multi
-
24
include Callbacks
-
24
using ArrayExtensions::FilterMap
-
-
24
attr_reader :resolvers
-
-
24
def initialize(resolver_type, options)
-
647
@options = options
-
647
@resolver_options = @options.resolver_options
-
-
647
@resolvers = options.ip_families.map do |ip_family|
-
647
resolver = resolver_type.new(ip_family, options)
-
647
resolver.on(:resolve, &method(:on_resolver_connection))
-
647
resolver.on(:error, &method(:on_resolver_error))
-
831
resolver.on(:close) { on_resolver_close(resolver) }
-
647
resolver
-
end
-
-
647
@errors = Hash.new { |hs, k| hs[k] = [] }
-
end
-
-
24
def closed?
-
2231078
@resolvers.all?(&:closed?)
-
end
-
-
24
def timeout
-
2227950
@resolvers.filter_map(&:timeout).min
-
end
-
-
24
def close
-
2733
@resolvers.each(&:close)
-
end
-
-
24
def connections
-
10520
@resolvers.filter_map { |r| r.resolver_connection if r.respond_to?(:resolver_connection) }
-
end
-
-
24
def early_resolve(connection)
-
5715
hostname = connection.origin.host
-
5715
addresses = @resolver_options[:cache] && (connection.addresses || HTTPX::Resolver.nolookup_resolve(hostname))
-
5715
return unless addresses
-
-
5529
addresses.group_by(&:family).sort { |(f1, _), (f2, _)| f2 <=> f1 }.each do |family, addrs|
-
# try to match the resolver by family. However, there are cases where that's not possible, as when
-
# the system does not have IPv6 connectivity, but it does support IPv6 via loopback/link-local.
-
11030
resolver = @resolvers.find { |r| r.family == family } || @resolvers.first
-
-
5515
next unless resolver # this should ever happen
-
-
# it does not matter which resolver it is, as early-resolve code is shared.
-
5515
resolver.emit_addresses(connection, family, addrs, true)
-
end
-
end
-
-
24
private
-
-
24
def on_resolver_connection(connection)
-
5711
emit(:resolve, connection)
-
end
-
-
24
def on_resolver_error(connection, error)
-
149
emit(:error, connection, error)
-
end
-
-
24
def on_resolver_close(resolver)
-
184
emit(:close, resolver)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "forwardable"
-
24
require "resolv"
-
-
24
module HTTPX
-
24
class Resolver::Native < Resolver::Resolver
-
24
extend Forwardable
-
24
using URIExtensions
-
-
2
DEFAULTS = {
-
22
nameserver: nil,
-
**Resolv::DNS::Config.default_config_hash,
-
packet_size: 512,
-
timeouts: Resolver::RESOLVE_TIMEOUT,
-
}.freeze
-
-
24
DNS_PORT = 53
-
-
24
def_delegator :@connections, :empty?
-
-
24
attr_reader :state
-
-
24
def initialize(family, options)
-
607
super
-
607
@ns_index = 0
-
607
@resolver_options = DEFAULTS.merge(@options.resolver_options)
-
607
@socket_type = @resolver_options.fetch(:socket_type, :udp)
-
607
@nameserver = if (nameserver = @resolver_options[:nameserver])
-
602
nameserver = nameserver[family] if nameserver.is_a?(Hash)
-
602
Array(nameserver)
-
end
-
607
@ndots = @resolver_options.fetch(:ndots, 1)
-
1821
@search = Array(@resolver_options[:search]).map { |srch| srch.scan(/[^.]+/) }
-
607
@_timeouts = Array(@resolver_options[:timeouts])
-
1858
@timeouts = Hash.new { |timeouts, host| timeouts[host] = @_timeouts.dup }
-
607
@connections = []
-
607
@queries = {}
-
607
@read_buffer = "".b
-
607
@write_buffer = Buffer.new(@resolver_options[:packet_size])
-
607
@state = :idle
-
end
-
-
24
def close
-
2917
transition(:closed)
-
end
-
-
24
def closed?
-
2231247
@state == :closed
-
end
-
-
24
def to_io
-
1060
@io.to_io
-
end
-
-
24
def call
-
836
case @state
-
when :open
-
920
consume
-
end
-
148
nil
-
rescue Errno::EHOSTUNREACH => e
-
15
@ns_index += 1
-
15
nameserver = @nameserver
-
15
if nameserver && @ns_index < nameserver.size
-
10
log { "resolver: failed resolving on nameserver #{@nameserver[@ns_index - 1]} (#{e.message})" }
-
10
transition(:idle)
-
10
@timeouts.clear
-
else
-
5
handle_error(e)
-
end
-
rescue NativeResolveError => e
-
103
handle_error(e)
-
end
-
-
24
def interests
-
1086436
case @state
-
when :idle
-
2788
transition(:open)
-
when :closed
-
196
transition(:idle)
-
196
transition(:open)
-
end
-
-
2213391
calculate_interests
-
end
-
-
24
def <<(connection)
-
304
if @nameserver.nil?
-
5
ex = ResolveError.new("No available nameserver")
-
5
ex.set_backtrace(caller)
-
5
connection.force_reset
-
5
throw(:resolve_error, ex)
-
else
-
299
@connections << connection
-
299
resolve
-
end
-
end
-
-
24
def timeout
-
2227950
return if @connections.empty?
-
-
3494
@start_timeout = Utils.now
-
3494
hosts = @queries.keys
-
3494
@timeouts.values_at(*hosts).reject(&:empty?).map(&:first).min
-
end
-
-
24
def handle_socket_timeout(interval)
-
80
do_retry(interval)
-
end
-
-
24
private
-
-
24
def calculate_interests
-
2215098
return :w unless @write_buffer.empty?
-
-
2213786
return :r unless @queries.empty?
-
-
2193294
nil
-
end
-
-
24
def consume
-
905
dread if calculate_interests == :r
-
802
do_retry
-
802
dwrite if calculate_interests == :w
-
end
-
-
24
def do_retry(loop_time = nil)
-
882
return if @queries.empty? || !@start_timeout
-
-
669
loop_time ||= Utils.elapsed_time(@start_timeout)
-
-
669
query = @queries.first
-
-
669
return unless query
-
-
669
h, connection = query
-
669
host = connection.origin.host
-
669
timeout = (@timeouts[host][0] -= loop_time)
-
-
669
return unless timeout <= 0
-
-
60
@timeouts[host].shift
-
-
60
if !@timeouts[host].empty?
-
35
log { "resolver: timeout after #{timeout}s, retry(#{@timeouts[host].first}) #{host}..." }
-
# must downgrade to tcp AND retry on same host as last
-
35
downgrade_socket
-
35
resolve(connection, h)
-
25
elsif @ns_index + 1 < @nameserver.size
-
# try on the next nameserver
-
5
@ns_index += 1
-
5
log { "resolver: failed resolving #{host} on nameserver #{@nameserver[@ns_index - 1]} (timeout error)" }
-
5
transition(:idle)
-
5
@timeouts.clear
-
5
resolve(connection, h)
-
else
-
-
20
@timeouts.delete(host)
-
20
reset_hostname(h, reset_candidates: false)
-
-
20
return unless @queries.empty?
-
-
5
@connections.delete(connection)
-
# This loop_time passed to the exception is bogus. Ideally we would pass the total
-
# resolve timeout, including from the previous retries.
-
5
raise ResolveTimeoutError.new(loop_time, "Timed out while resolving #{connection.origin.host}")
-
end
-
end
-
-
24
def dread(wsize = @resolver_options[:packet_size])
-
563
loop do
-
834
wsize = @large_packet.capacity if @large_packet
-
-
834
siz = @io.read(wsize, @read_buffer)
-
-
834
unless siz
-
ex = EOFError.new("descriptor closed")
-
ex.set_backtrace(caller)
-
raise ex
-
end
-
-
834
return unless siz.positive?
-
-
573
if @socket_type == :tcp
-
# packet may be incomplete, need to keep draining from the socket
-
25
if @large_packet
-
# large packet buffer already exists, continue pumping
-
10
@large_packet << @read_buffer
-
-
10
next unless @large_packet.full?
-
-
10
parse(@large_packet.to_s)
-
10
@large_packet = nil
-
# downgrade to udp again
-
10
downgrade_socket
-
10
return
-
else
-
15
size = @read_buffer[0, 2].unpack1("n")
-
15
buffer = @read_buffer.byteslice(2..-1)
-
-
15
if size > @read_buffer.bytesize
-
# only do buffer logic if it's worth it, and the whole packet isn't here already
-
10
@large_packet = Buffer.new(size)
-
10
@large_packet << buffer
-
-
10
next
-
else
-
5
parse(buffer)
-
end
-
end
-
else # udp
-
548
parse(@read_buffer)
-
end
-
-
450
return if @state == :closed
-
end
-
end
-
-
24
def dwrite
-
608
loop do
-
1216
return if @write_buffer.empty?
-
-
608
siz = @io.write(@write_buffer)
-
-
608
unless siz
-
ex = EOFError.new("descriptor closed")
-
ex.set_backtrace(caller)
-
raise ex
-
end
-
-
608
return unless siz.positive?
-
-
608
return if @state == :closed
-
end
-
end
-
-
24
def parse(buffer)
-
563
code, result = Resolver.decode_dns_answer(buffer)
-
-
505
case code
-
when :ok
-
206
parse_addresses(result)
-
when :no_domain_found
-
# Indicates no such domain was found.
-
332
hostname, connection = @queries.first
-
332
reset_hostname(hostname, reset_candidates: false)
-
-
332
unless @queries.value?(connection)
-
83
@connections.delete(connection)
-
83
raise NativeResolveError.new(connection, connection.origin.host, "name or service not known")
-
end
-
-
249
resolve
-
when :message_truncated
-
# TODO: what to do if it's already tcp??
-
10
return if @socket_type == :tcp
-
-
10
@socket_type = :tcp
-
-
10
hostname, _ = @queries.first
-
10
reset_hostname(hostname)
-
10
transition(:closed)
-
when :dns_error
-
10
hostname, connection = @queries.first
-
10
reset_hostname(hostname)
-
10
@connections.delete(connection)
-
10
ex = NativeResolveError.new(connection, connection.origin.host, "unknown DNS error (error code #{result})")
-
10
raise ex
-
when :decode_error
-
5
hostname, connection = @queries.first
-
5
reset_hostname(hostname)
-
5
@connections.delete(connection)
-
5
ex = NativeResolveError.new(connection, connection.origin.host, result.message)
-
5
ex.set_backtrace(result.backtrace)
-
5
raise ex
-
end
-
end
-
-
24
def parse_addresses(addresses)
-
206
if addresses.empty?
-
# no address found, eliminate candidates
-
5
hostname, connection = @queries.first
-
5
reset_hostname(hostname)
-
5
@connections.delete(connection)
-
5
raise NativeResolveError.new(connection, connection.origin.host)
-
else
-
201
address = addresses.first
-
201
name = address["name"]
-
-
201
connection = @queries.delete(name)
-
-
201
unless connection
-
orig_name = name
-
# absolute name
-
name_labels = Resolv::DNS::Name.create(name).to_a
-
name = @queries.each_key.first { |hname| name_labels == Resolv::DNS::Name.create(hname).to_a }
-
-
# probably a retried query for which there's an answer
-
unless name
-
@timeouts.delete(orig_name)
-
return
-
end
-
-
address["name"] = name
-
connection = @queries.delete(name)
-
end
-
-
201
if address.key?("alias") # CNAME
-
16
hostname_alias = address["alias"]
-
# clean up intermediate queries
-
16
@timeouts.delete(name) unless connection.origin.host == name
-
-
32
if catch(:coalesced) { early_resolve(connection, hostname: hostname_alias) }
-
1
@connections.delete(connection)
-
else
-
15
if @socket_type == :tcp
-
# must downgrade to udp if tcp
-
5
@socket_type = @resolver_options.fetch(:socket_type, :udp)
-
5
transition(:idle)
-
5
transition(:open)
-
end
-
15
log { "resolver: ALIAS #{hostname_alias} for #{name}" }
-
15
resolve(connection, hostname_alias)
-
15
return
-
end
-
else
-
185
reset_hostname(name, connection: connection)
-
185
@timeouts.delete(connection.origin.host)
-
185
@connections.delete(connection)
-
185
Resolver.cached_lookup_set(connection.origin.host, @family, addresses) if @resolver_options[:cache]
-
902
catch(:coalesced) { emit_addresses(connection, @family, addresses.map { |addr| addr["data"] }) }
-
end
-
end
-
186
return emit(:close) if @connections.empty?
-
-
2
resolve
-
end
-
-
24
def resolve(connection = @connections.first, hostname = nil)
-
615
raise Error, "no URI to resolve" unless connection
-
-
615
return unless @write_buffer.empty?
-
-
613
hostname ||= @queries.key(connection)
-
-
613
if hostname.nil?
-
309
hostname = connection.origin.host
-
309
log { "resolver: resolve IDN #{connection.origin.non_ascii_hostname} as #{hostname}" } if connection.origin.non_ascii_hostname
-
-
309
hostname = generate_candidates(hostname).each do |name|
-
1112
@queries[name] = connection
-
end.first
-
else
-
277
@queries[hostname] = connection
-
end
-
613
log { "resolver: query #{@record_type.name.split("::").last} for #{hostname}" }
-
51
begin
-
613
@write_buffer << encode_dns_query(hostname)
-
rescue Resolv::DNS::EncodeError => e
-
emit_resolve_error(connection, hostname, e)
-
end
-
end
-
-
24
def encode_dns_query(hostname)
-
613
message_id = Resolver.generate_id
-
613
msg = Resolver.encode_dns_query(hostname, type: @record_type, message_id: message_id)
-
613
msg[0, 2] = [msg.size, message_id].pack("nn") if @socket_type == :tcp
-
613
msg
-
end
-
-
24
def generate_candidates(name)
-
309
return [name] if name.end_with?(".")
-
-
309
candidates = []
-
309
name_parts = name.scan(/[^.]+/)
-
309
candidates = [name] if @ndots <= name_parts.size - 1
-
927
candidates.concat(@search.map { |domain| [*name_parts, *domain].join(".") })
-
309
fname = "#{name}."
-
309
candidates << fname unless candidates.include?(fname)
-
-
309
candidates
-
end
-
-
24
def build_socket
-
475
ip, port = @nameserver[@ns_index]
-
475
port ||= DNS_PORT
-
-
390
case @socket_type
-
when :udp
-
460
log { "resolver: server: udp://#{ip}:#{port}..." }
-
460
UDP.new(ip, port, @options)
-
when :tcp
-
15
log { "resolver: server: tcp://#{ip}:#{port}..." }
-
15
origin = URI("tcp://#{ip}:#{port}")
-
15
TCP.new(origin, [ip], @options)
-
end
-
end
-
-
24
def downgrade_socket
-
45
return unless @socket_type == :tcp
-
-
5
@socket_type = @resolver_options.fetch(:socket_type, :udp)
-
5
transition(:idle)
-
5
transition(:open)
-
end
-
-
24
def transition(nextstate)
-
5384
case nextstate
-
when :idle
-
221
if @io
-
221
@io.close
-
221
@io = nil
-
end
-
when :open
-
2994
return unless @state == :idle
-
-
2994
@io ||= build_socket
-
-
2994
@io.connect
-
2994
return unless @io.connected?
-
-
475
resolve if @queries.empty? && !@connections.empty?
-
when :closed
-
2927
return unless @state == :open
-
-
423
@io.close if @io
-
423
@start_timeout = nil
-
423
@write_buffer.clear
-
423
@read_buffer.clear
-
end
-
1119
@state = nextstate
-
end
-
-
24
def handle_error(error)
-
108
if error.respond_to?(:connection) &&
-
error.respond_to?(:host)
-
103
emit_resolve_error(error.connection, error.host, error)
-
else
-
5
@queries.each do |host, connection|
-
20
emit_resolve_error(connection, host, error)
-
end
-
end
-
end
-
-
24
def reset_hostname(hostname, connection: @queries.delete(hostname), reset_candidates: true)
-
567
@timeouts.delete(hostname)
-
567
@timeouts.delete(hostname)
-
-
567
return unless connection && reset_candidates
-
-
# eliminate other candidates
-
860
candidates = @queries.select { |_, conn| connection == conn }.keys
-
860
@queries.delete_if { |h, _| candidates.include?(h) }
-
# reset timeouts
-
888
@timeouts.delete_if { |h, _| candidates.include?(h) }
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "resolv"
-
24
require "ipaddr"
-
-
24
module HTTPX
-
24
class Resolver::Resolver
-
24
include Callbacks
-
24
include Loggable
-
-
24
using ArrayExtensions::Intersect
-
-
2
RECORD_TYPES = {
-
22
Socket::AF_INET6 => Resolv::DNS::Resource::IN::AAAA,
-
Socket::AF_INET => Resolv::DNS::Resource::IN::A,
-
}.freeze
-
-
2
FAMILY_TYPES = {
-
22
Resolv::DNS::Resource::IN::AAAA => "AAAA",
-
Resolv::DNS::Resource::IN::A => "A",
-
}.freeze
-
-
24
class << self
-
24
def multi?
-
647
true
-
end
-
end
-
-
24
attr_reader :family
-
-
24
attr_writer :pool
-
-
24
def initialize(family, options)
-
668
@family = family
-
668
@record_type = RECORD_TYPES[family]
-
668
@options = options
-
end
-
-
24
def close; end
-
-
24
alias_method :terminate, :close
-
-
24
def closed?
-
true
-
end
-
-
24
def empty?
-
true
-
end
-
-
24
def emit_addresses(connection, family, addresses, early_resolve = false)
-
5761
addresses.map! do |address|
-
12839
address.is_a?(IPAddr) ? address : IPAddr.new(address.to_s)
-
end
-
-
# double emission check, but allow early resolution to work
-
5761
return if !early_resolve && connection.addresses && !addresses.intersect?(connection.addresses)
-
-
5802
log { "resolver: answer #{FAMILY_TYPES[RECORD_TYPES[family]]} #{connection.origin.host}: #{addresses.inspect}" }
-
5761
if @pool && # if triggered by early resolve, pool may not be here yet
-
!connection.io &&
-
connection.options.ip_families.size > 1 &&
-
family == Socket::AF_INET &&
-
addresses.first.to_s != connection.origin.host.to_s
-
log { "resolver: A response, applying resolution delay..." }
-
@pool.after(0.05) do
-
unless connection.state == :closed ||
-
# double emission check
-
(connection.addresses && addresses.intersect?(connection.addresses))
-
emit_resolved_connection(connection, addresses, early_resolve)
-
end
-
end
-
else
-
5761
emit_resolved_connection(connection, addresses, early_resolve)
-
end
-
end
-
-
24
private
-
-
24
def emit_resolved_connection(connection, addresses, early_resolve)
-
begin
-
5761
connection.addresses = addresses
-
-
5721
emit(:resolve, connection)
-
24
rescue StandardError => e
-
40
if early_resolve
-
34
connection.force_reset
-
34
throw(:resolve_error, e)
-
else
-
6
emit(:error, connection, e)
-
end
-
end
-
end
-
-
24
def early_resolve(connection, hostname: connection.origin.host)
-
16
addresses = @resolver_options[:cache] && (connection.addresses || HTTPX::Resolver.nolookup_resolve(hostname))
-
-
16
return unless addresses
-
-
5
addresses = addresses.select { |addr| addr.family == @family }
-
-
1
return if addresses.empty?
-
-
1
emit_addresses(connection, @family, addresses, true)
-
end
-
-
24
def emit_resolve_error(connection, hostname = connection.origin.host, ex = nil)
-
154
emit(:error, connection, resolve_error(hostname, ex))
-
end
-
-
24
def resolve_error(hostname, ex = nil)
-
154
return ex if ex.is_a?(ResolveError) || ex.is_a?(ResolveTimeoutError)
-
-
50
message = ex ? ex.message : "Can't resolve #{hostname}"
-
50
error = ResolveError.new(message)
-
50
error.set_backtrace(ex ? ex.backtrace : caller)
-
50
error
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "forwardable"
-
24
require "resolv"
-
-
24
module HTTPX
-
24
class Resolver::System < Resolver::Resolver
-
24
using URIExtensions
-
24
extend Forwardable
-
-
24
RESOLV_ERRORS = [Resolv::ResolvError,
-
Resolv::DNS::Requester::RequestError,
-
Resolv::DNS::EncodeError,
-
Resolv::DNS::DecodeError].freeze
-
-
24
DONE = 1
-
24
ERROR = 2
-
-
24
class << self
-
24
def multi?
-
21
false
-
end
-
end
-
-
24
attr_reader :state
-
-
24
def_delegator :@connections, :empty?
-
-
24
def initialize(options)
-
21
super(nil, options)
-
21
@resolver_options = @options.resolver_options
-
21
resolv_options = @resolver_options.dup
-
21
timeouts = resolv_options.delete(:timeouts) || Resolver::RESOLVE_TIMEOUT
-
21
@_timeouts = Array(timeouts)
-
42
@timeouts = Hash.new { |tims, host| tims[host] = @_timeouts.dup }
-
21
resolv_options.delete(:cache)
-
21
@connections = []
-
21
@queries = []
-
21
@ips = []
-
21
@pipe_mutex = Thread::Mutex.new
-
21
@state = :idle
-
end
-
-
24
def resolvers
-
42
return enum_for(__method__) unless block_given?
-
-
21
yield self
-
end
-
-
24
def connections
-
EMPTY
-
end
-
-
24
def close
-
21
transition(:closed)
-
end
-
-
24
def closed?
-
62
@state == :closed
-
end
-
-
24
def to_io
-
20
@pipe_read.to_io
-
end
-
-
24
def call
-
20
case @state
-
when :open
-
20
consume
-
end
-
nil
-
end
-
-
24
def interests
-
20
return if @queries.empty?
-
-
20
:r
-
end
-
-
24
def timeout
-
20
return unless @queries.empty?
-
-
_, connection = @queries.first
-
-
return unless connection
-
-
@timeouts[connection.origin.host].first
-
end
-
-
24
def <<(connection)
-
21
@connections << connection
-
21
resolve
-
end
-
-
24
def handle_socket_timeout(interval)
-
error = HTTPX::ResolveTimeoutError.new(interval, "timed out while waiting on select")
-
error.set_backtrace(caller)
-
on_error(error)
-
end
-
-
24
private
-
-
24
def transition(nextstate)
-
42
case nextstate
-
when :idle
-
@timeouts.clear
-
when :open
-
21
return unless @state == :idle
-
-
21
@pipe_read, @pipe_write = ::IO.pipe
-
when :closed
-
21
return unless @state == :open
-
-
21
@pipe_write.close
-
21
@pipe_read.close
-
end
-
42
@state = nextstate
-
end
-
-
24
def consume
-
41
return if @connections.empty?
-
-
62
while @pipe_read.ready? && (event = @pipe_read.getbyte)
-
21
case event
-
when DONE
-
20
*pair, addrs = @pipe_mutex.synchronize { @ips.pop }
-
10
@queries.delete(pair)
-
-
10
family, connection = pair
-
20
catch(:coalesced) { emit_addresses(connection, family, addrs) }
-
when ERROR
-
22
*pair, error = @pipe_mutex.synchronize { @ips.pop }
-
11
@queries.delete(pair)
-
-
11
family, connection = pair
-
11
emit_resolve_error(connection, connection.origin.host, error)
-
end
-
-
21
@connections.delete(connection) if @queries.empty?
-
end
-
-
41
return emit(:close, self) if @connections.empty?
-
-
20
resolve
-
end
-
-
24
def resolve(connection = @connections.first)
-
41
raise Error, "no URI to resolve" unless connection
-
41
return unless @queries.empty?
-
-
21
hostname = connection.origin.host
-
21
scheme = connection.origin.scheme
-
21
log { "resolver: resolve IDN #{connection.origin.non_ascii_hostname} as #{hostname}" } if connection.origin.non_ascii_hostname
-
-
21
transition(:open)
-
-
21
connection.options.ip_families.each do |family|
-
21
@queries << [family, connection]
-
end
-
21
async_resolve(connection, hostname, scheme)
-
21
consume
-
end
-
-
24
def async_resolve(connection, hostname, scheme)
-
21
families = connection.options.ip_families
-
21
log { "resolver: query for #{hostname}" }
-
21
timeouts = @timeouts[connection.origin.host]
-
21
resolve_timeout = timeouts.first
-
-
21
Thread.start do
-
21
Thread.current.report_on_exception = false
-
begin
-
21
addrs = if resolve_timeout
-
-
21
Timeout.timeout(resolve_timeout) do
-
21
__addrinfo_resolve(hostname, scheme)
-
end
-
else
-
__addrinfo_resolve(hostname, scheme)
-
end
-
10
addrs = addrs.sort_by(&:afamily).group_by(&:afamily)
-
10
families.each do |family|
-
10
addresses = addrs[family]
-
10
next unless addresses
-
-
10
addresses.map!(&:ip_address)
-
10
addresses.uniq!
-
10
@pipe_mutex.synchronize do
-
10
@ips.unshift([family, connection, addresses])
-
10
@pipe_write.putc(DONE) unless @pipe_write.closed?
-
end
-
end
-
rescue StandardError => e
-
11
if e.is_a?(Timeout::Error)
-
1
timeouts.shift
-
1
retry unless timeouts.empty?
-
1
e = ResolveTimeoutError.new(resolve_timeout, e.message)
-
1
e.set_backtrace(e.backtrace)
-
end
-
11
@pipe_mutex.synchronize do
-
11
families.each do |family|
-
11
@ips.unshift([family, connection, e])
-
11
@pipe_write.putc(ERROR) unless @pipe_write.closed?
-
end
-
end
-
end
-
end
-
end
-
-
24
def __addrinfo_resolve(host, scheme)
-
21
Addrinfo.getaddrinfo(host, scheme, Socket::AF_UNSPEC, Socket::SOCK_STREAM)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "objspace"
-
24
require "stringio"
-
24
require "tempfile"
-
24
require "fileutils"
-
24
require "forwardable"
-
-
24
module HTTPX
-
# Defines a HTTP response is handled internally, with a few properties exposed as attributes.
-
#
-
# It delegates the following methods to the corresponding HTTPX::Request:
-
#
-
# * HTTPX::Request#uri
-
# * HTTPX::Request#peer_address
-
#
-
# It implements (indirectly, via the +body+) the IO write protocol to internally buffer payloads.
-
#
-
# It implements the IO reader protocol in order for users to buffer/stream it, acts as an enumerable
-
# (of payload chunks).
-
#
-
24
class Response
-
24
extend Forwardable
-
24
include Callbacks
-
-
# the HTTP response status code
-
24
attr_reader :status
-
-
# an HTTPX::Headers object containing the response HTTP headers.
-
24
attr_reader :headers
-
-
# a HTTPX::Response::Body object wrapping the response body. The following methods are delegated to it:
-
#
-
# * HTTPX::Response::Body#to_s
-
# * HTTPX::Response::Body#to_str
-
# * HTTPX::Response::Body#read
-
# * HTTPX::Response::Body#copy_to
-
# * HTTPX::Response::Body#close
-
24
attr_reader :body
-
-
# The HTTP protocol version used to fetch the response.
-
24
attr_reader :version
-
-
# returns the response body buffered in a string.
-
24
def_delegator :@body, :to_s
-
-
24
def_delegator :@body, :to_str
-
-
# implements the IO reader +#read+ interface.
-
24
def_delegator :@body, :read
-
-
# copies the response body to a different location.
-
24
def_delegator :@body, :copy_to
-
-
# closes the body.
-
24
def_delegator :@body, :close
-
-
# the corresponding request uri.
-
24
def_delegator :@request, :uri
-
-
# the IP address of the peer server.
-
24
def_delegator :@request, :peer_address
-
-
# inits the instance with the corresponding +request+ to this response, an the
-
# response HTTP +status+, +version+ and HTTPX::Headers instance of +headers+.
-
24
def initialize(request, status, version, headers)
-
7321
@request = request
-
7321
@options = request.options
-
7321
@version = version
-
7321
@status = Integer(status)
-
7321
@headers = @options.headers_class.new(headers)
-
7321
@body = @options.response_body_class.new(self, @options)
-
7321
@finished = complete?
-
7321
@content_type = nil
-
end
-
-
# merges headers defined in +h+ into the response headers.
-
24
def merge_headers(h)
-
162
@headers = @headers.merge(h)
-
end
-
-
# writes +data+ chunk into the response body.
-
24
def <<(data)
-
9852
@body.write(data)
-
end
-
-
# returns the HTTPX::ContentType for the response, as per what's declared in the content-type header.
-
#
-
# response.content_type #=> #<HTTPX::ContentType:xxx @header_value="text/plain">
-
# response.content_type.mime_type #=> "text/plain"
-
24
def content_type
-
7582
@content_type ||= ContentType.new(@headers["content-type"])
-
end
-
-
# returns whether the response has been fully fetched.
-
24
def finished?
-
3843
@finished
-
end
-
-
# marks the response as finished, freezes the headers.
-
24
def finish!
-
3749
@finished = true
-
3749
@headers.freeze
-
end
-
-
# returns whether the response contains body payload.
-
24
def bodyless?
-
7321
@request.verb == "HEAD" ||
-
@status < 200 || # informational response
-
@status == 204 ||
-
@status == 205 ||
-
@status == 304 || begin
-
6933
content_length = @headers["content-length"]
-
6933
return false if content_length.nil?
-
-
5994
content_length == "0"
-
end
-
end
-
-
24
def complete?
-
7321
bodyless? || (@request.verb == "CONNECT" && @status == 200)
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<Response:#{object_id} " \
-
skipped
"HTTP/#{version} " \
-
skipped
"@status=#{@status} " \
-
skipped
"@headers=#{@headers} " \
-
skipped
"@body=#{@body.bytesize}>"
-
skipped
end
-
skipped
# :nocov:
-
-
# returns an instance of HTTPX::HTTPError if the response has a 4xx or 5xx
-
# status code, or nothing.
-
#
-
# ok_response.error #=> nil
-
# not_found_response.error #=> HTTPX::HTTPError instance, status 404
-
24
def error
-
451
return if @status < 400
-
-
47
HTTPError.new(self)
-
end
-
-
# it raises the exception returned by +error+, or itself otherwise.
-
#
-
# ok_response.raise_for_status #=> ok_response
-
# not_found_response.raise_for_status #=> raises HTTPX::HTTPError exception
-
24
def raise_for_status
-
416
return self unless (err = error)
-
-
33
raise err
-
end
-
-
# decodes the response payload into a ruby object **if** the payload is valid json.
-
#
-
# response.json #≈> { "foo" => "bar" } for "{\"foo\":\"bar\"}" payload
-
# response.json(symbolize_names: true) #≈> { foo: "bar" } for "{\"foo\":\"bar\"}" payload
-
24
def json(*args)
-
65
decode(Transcoder::JSON, *args)
-
end
-
-
# decodes the response payload into a ruby object **if** the payload is valid
-
# "application/x-www-urlencoded" or "multipart/form-data".
-
24
def form
-
56
decode(Transcoder::Form)
-
end
-
-
# decodes the response payload into a Nokogiri::XML::Node object **if** the payload is valid
-
# "application/xml" (requires the "nokogiri" gem).
-
24
def xml
-
7
decode(Transcoder::Xml)
-
end
-
-
24
private
-
-
# decodes the response payload using the given +transcoder+, which implements the decoding logic.
-
#
-
# +transcoder+ must implement the internal transcoder API, i.e. respond to <tt>decode(HTTPX::Response response)</tt>,
-
# which returns a decoder which responds to <tt>call(HTTPX::Response response, **kwargs)</tt>
-
24
def decode(transcoder, *args)
-
# TODO: check if content-type is a valid format, i.e. "application/json" for json parsing
-
-
128
decoder = transcoder.decode(self)
-
-
114
raise Error, "no decoder available for \"#{transcoder}\"" unless decoder
-
-
114
@body.rewind
-
-
114
decoder.call(self, *args)
-
end
-
end
-
-
# Helper class which decodes the HTTP "content-type" header.
-
24
class ContentType
-
24
MIME_TYPE_RE = %r{^([^/]+/[^;]+)(?:$|;)}.freeze
-
24
CHARSET_RE = /;\s*charset=([^;]+)/i.freeze
-
-
24
def initialize(header_value)
-
7548
@header_value = header_value
-
end
-
-
# returns the mime type declared in the header.
-
#
-
# ContentType.new("application/json; charset=utf-8").mime_type #=> "application/json"
-
24
def mime_type
-
128
return @mime_type if defined?(@mime_type)
-
-
94
m = @header_value.to_s[MIME_TYPE_RE, 1]
-
94
m && @mime_type = m.strip.downcase
-
end
-
-
# returns the charset declared in the header.
-
#
-
# ContentType.new("application/json; charset=utf-8").charset #=> "utf-8"
-
# ContentType.new("text/plain").charset #=> nil
-
24
def charset
-
7454
return @charset if defined?(@charset)
-
-
7454
m = @header_value.to_s[CHARSET_RE, 1]
-
7454
m && @charset = m.strip.delete('"')
-
end
-
end
-
-
# Wraps an error which has happened while processing an HTTP Request. It has partial
-
# public API parity with HTTPX::Response, so users should rely on it to infer whether
-
# the returned response is one or the other.
-
#
-
# response = HTTPX.get("https://some-domain/path") #=> response is HTTPX::Response or HTTPX::ErrorResponse
-
# response.raise_for_status #=> raises if it wraps an error
-
24
class ErrorResponse
-
24
include Loggable
-
24
extend Forwardable
-
-
# the corresponding HTTPX::Request instance.
-
24
attr_reader :request
-
-
# the HTTPX::Response instance, when there is one (i.e. error happens fetching the response).
-
24
attr_reader :response
-
-
# the wrapped exception.
-
24
attr_reader :error
-
-
# the request uri
-
24
def_delegator :@request, :uri
-
-
# the IP address of the peer server.
-
24
def_delegator :@request, :peer_address
-
-
24
def initialize(request, error)
-
936
@request = request
-
936
@response = request.response if request.response.is_a?(Response)
-
936
@error = error
-
936
@options = request.options
-
936
log_exception(@error)
-
end
-
-
# returns the exception full message.
-
24
def to_s
-
8
@error.full_message(highlight: false)
-
end
-
-
# closes the error resources.
-
24
def close
-
7
@response.close if @response && @response.respond_to?(:close)
-
end
-
-
# always true for error responses.
-
24
def finished?
-
7
true
-
end
-
-
# raises the wrapped exception.
-
24
def raise_for_status
-
66
raise @error
-
end
-
-
# buffers lost chunks to error response
-
24
def <<(data)
-
7
@response << data
-
end
-
end
-
end
-
-
24
require_relative "response/body"
-
24
require_relative "response/buffer"
-
24
require_relative "pmatch_extensions" if RUBY_VERSION >= "2.7.0"
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
# Implementation of the HTTP Response body as a buffer which implements the IO writer protocol
-
# (for buffering the response payload), the IO reader protocol (for consuming the response payload),
-
# and can be iterated over (via #each, which yields the payload in chunks).
-
24
class Response::Body
-
# the payload encoding (i.e. "utf-8", "ASCII-8BIT")
-
24
attr_reader :encoding
-
-
# Array of encodings contained in the response "content-encoding" header.
-
24
attr_reader :encodings
-
-
# initialized with the corresponding HTTPX::Response +response+ and HTTPX::Options +options+.
-
24
def initialize(response, options)
-
7454
@response = response
-
7454
@headers = response.headers
-
7454
@options = options
-
7454
@window_size = options.window_size
-
7454
@encodings = []
-
7454
@length = 0
-
7454
@buffer = nil
-
7454
@reader = nil
-
7454
@state = :idle
-
-
# initialize response encoding
-
7454
@encoding = if (enc = response.content_type.charset)
-
161
begin
-
1267
Encoding.find(enc)
-
rescue ArgumentError
-
28
Encoding::BINARY
-
end
-
else
-
6187
Encoding::BINARY
-
end
-
-
7454
initialize_inflaters
-
end
-
-
24
def initialize_dup(other)
-
28
super
-
-
28
@buffer = other.instance_variable_get(:@buffer).dup
-
end
-
-
24
def closed?
-
259
@state == :closed
-
end
-
-
# write the response payload +chunk+ into the buffer. Inflates the chunk when required
-
# and supported.
-
24
def write(chunk)
-
9716
return if @state == :closed
-
-
9716
return 0 if chunk.empty?
-
-
9362
chunk = decode_chunk(chunk)
-
-
9362
size = chunk.bytesize
-
8179
@length += size
-
9362
transition(:open)
-
9362
@buffer.write(chunk)
-
-
9362
@response.emit(:chunk_received, chunk)
-
9348
size
-
end
-
-
# reads a chunk from the payload (implementation of the IO reader protocol).
-
24
def read(*args)
-
147
return unless @buffer
-
-
147
unless @reader
-
94
rewind
-
94
@reader = @buffer
-
end
-
-
147
@reader.read(*args)
-
end
-
-
# size of the decoded response payload. May differ from "content-length" header if
-
# response was encoded over-the-wire.
-
24
def bytesize
-
151
@length
-
end
-
-
# yields the payload in chunks.
-
24
def each
-
56
return enum_for(__method__) unless block_given?
-
-
5
begin
-
42
if @buffer
-
42
rewind
-
108
while (chunk = @buffer.read(@window_size))
-
42
yield(chunk.force_encoding(@encoding))
-
end
-
end
-
ensure
-
42
close
-
end
-
end
-
-
# returns the declared filename in the "contennt-disposition" header, when present.
-
24
def filename
-
42
return unless @headers.key?("content-disposition")
-
-
35
Utils.get_filename(@headers["content-disposition"])
-
end
-
-
# returns the full response payload as a string.
-
24
def to_s
-
3765
return "".b unless @buffer
-
-
3497
@buffer.to_s
-
end
-
-
24
alias_method :to_str, :to_s
-
-
# whether the payload is empty.
-
24
def empty?
-
28
@length.zero?
-
end
-
-
# copies the payload to +dest+.
-
#
-
# body.copy_to("path/to/file")
-
# body.copy_to(Pathname.new("path/to/file"))
-
# body.copy_to(File.new("path/to/file"))
-
24
def copy_to(dest)
-
42
return unless @buffer
-
-
42
rewind
-
-
42
if dest.respond_to?(:path) && @buffer.respond_to?(:path)
-
7
FileUtils.mv(@buffer.path, dest.path)
-
else
-
35
::IO.copy_stream(@buffer, dest)
-
end
-
end
-
-
# closes/cleans the buffer, resets everything
-
24
def close
-
491
if @buffer
-
351
@buffer.close
-
351
@buffer = nil
-
end
-
491
@length = 0
-
491
transition(:closed)
-
end
-
-
24
def ==(other)
-
103
object_id == other.object_id || begin
-
103
if other.respond_to?(:read)
-
70
_with_same_buffer_pos { FileUtils.compare_stream(@buffer, other) }
-
else
-
68
to_s == other.to_s
-
end
-
end
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<HTTPX::Response::Body:#{object_id} " \
-
skipped
"@state=#{@state} " \
-
skipped
"@length=#{@length}>"
-
skipped
end
-
skipped
# :nocov:
-
-
# rewinds the response payload buffer.
-
24
def rewind
-
327
return unless @buffer
-
-
# in case there's some reading going on
-
327
@reader = nil
-
-
327
@buffer.rewind
-
end
-
-
24
private
-
-
# prepares inflaters for the advertised encodings in "content-encoding" header.
-
24
def initialize_inflaters
-
7454
@inflaters = nil
-
-
7454
return unless @headers.key?("content-encoding")
-
-
149
return unless @options.decompress_response_body
-
-
135
@inflaters = @headers.get("content-encoding").filter_map do |encoding|
-
135
next if encoding == "identity"
-
-
135
inflater = self.class.initialize_inflater_by_encoding(encoding, @response)
-
-
# do not uncompress if there is no decoder available. In fact, we can't reliably
-
# continue decompressing beyond that, so ignore.
-
135
break unless inflater
-
-
135
@encodings << encoding
-
135
inflater
-
end
-
end
-
-
# passes the +chunk+ through all inflaters to decode it.
-
24
def decode_chunk(chunk)
-
35
@inflaters.reverse_each do |inflater|
-
371
chunk = inflater.call(chunk)
-
9489
end if @inflaters
-
-
9490
chunk
-
end
-
-
# tries transitioning the body STM to the +nextstate+.
-
24
def transition(nextstate)
-
8611
case nextstate
-
when :open
-
9362
return unless @state == :idle
-
-
5713
@buffer = Response::Buffer.new(
-
threshold_size: @options.body_threshold_size,
-
bytesize: @length,
-
encoding: @encoding
-
)
-
when :closed
-
491
return if @state == :closed
-
end
-
-
6204
@state = nextstate
-
end
-
-
24
def _with_same_buffer_pos # :nodoc:
-
35
return yield unless @buffer && @buffer.respond_to?(:pos)
-
-
# @type ivar @buffer: StringIO | Tempfile
-
35
current_pos = @buffer.pos
-
35
@buffer.rewind
-
4
begin
-
35
yield
-
ensure
-
35
@buffer.pos = current_pos
-
end
-
end
-
-
24
class << self
-
24
def initialize_inflater_by_encoding(encoding, response, **kwargs) # :nodoc:
-
120
case encoding
-
when "gzip"
-
121
Transcoder::GZIP.decode(response, **kwargs)
-
when "deflate"
-
14
Transcoder::Deflate.decode(response, **kwargs)
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "delegate"
-
24
require "stringio"
-
24
require "tempfile"
-
-
24
module HTTPX
-
# wraps and delegates to an internal buffer, which can be a StringIO or a Tempfile.
-
24
class Response::Buffer < SimpleDelegator
-
# initializes buffer with the +threshold_size+ over which the payload gets buffer to a tempfile,
-
# the initial +bytesize+, and the +encoding+.
-
24
def initialize(threshold_size:, bytesize: 0, encoding: Encoding::BINARY)
-
5771
@threshold_size = threshold_size
-
5771
@bytesize = bytesize
-
5771
@encoding = encoding
-
5771
@buffer = StringIO.new("".b)
-
5771
super(@buffer)
-
end
-
-
24
def initialize_dup(other)
-
28
super
-
-
28
@buffer = other.instance_variable_get(:@buffer).dup
-
end
-
-
# size in bytes of the buffered content.
-
24
def size
-
222
@bytesize
-
end
-
-
# writes the +chunk+ into the buffer.
-
24
def write(chunk)
-
8275
@bytesize += chunk.bytesize
-
9466
try_upgrade_buffer
-
9466
@buffer.write(chunk)
-
end
-
-
# returns the buffered content as a string.
-
24
def to_s
-
3027
case @buffer
-
when StringIO
-
451
begin
-
3427
@buffer.string.force_encoding(@encoding)
-
rescue ArgumentError
-
@buffer.string
-
end
-
when Tempfile
-
70
rewind
-
140
content = _with_same_buffer_pos { @buffer.read }
-
9
begin
-
70
content.force_encoding(@encoding)
-
rescue ArgumentError # ex: unknown encoding name - utf
-
content
-
end
-
end
-
end
-
-
# closes the buffer.
-
24
def close
-
351
@buffer.close
-
351
@buffer.unlink if @buffer.respond_to?(:unlink)
-
end
-
-
24
private
-
-
# initializes the buffer into a StringIO, or turns it into a Tempfile when the threshold
-
# has been reached.
-
24
def try_upgrade_buffer
-
9466
return unless @bytesize > @threshold_size
-
-
353
return if @buffer.is_a?(Tempfile)
-
-
115
aux = @buffer
-
-
115
@buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
-
115
if aux
-
115
aux.rewind
-
115
::IO.copy_stream(aux, @buffer)
-
115
aux.close
-
end
-
-
115
__setobj__(@buffer)
-
end
-
-
24
def _with_same_buffer_pos # :nodoc:
-
70
current_pos = @buffer.pos
-
70
@buffer.rewind
-
9
begin
-
70
yield
-
ensure
-
70
@buffer.pos = current_pos
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "io/wait"
-
-
24
class HTTPX::Selector
-
24
READABLE = %i[rw r].freeze
-
24
WRITABLE = %i[rw w].freeze
-
-
24
private_constant :READABLE
-
24
private_constant :WRITABLE
-
-
24
def initialize
-
548
@selectables = []
-
end
-
-
# deregisters +io+ from selectables.
-
24
def deregister(io)
-
12683
@selectables.delete(io)
-
end
-
-
# register +io+.
-
24
def register(io)
-
7131
return if @selectables.include?(io)
-
-
6907
@selectables << io
-
end
-
-
24
private
-
-
24
def select_many(interval, &block)
-
2026
selectables, r, w = nil
-
-
# first, we group IOs based on interest type. On call to #interests however,
-
# things might already happen, and new IOs might be registered, so we might
-
# have to start all over again. We do this until we group all selectables
-
231
begin
-
2026
loop do
-
231
begin
-
2026
r = nil
-
2026
w = nil
-
-
2026
selectables = @selectables
-
2026
@selectables = []
-
-
2026
selectables.delete_if do |io|
-
7612
interests = io.interests
-
-
7612
(r ||= []) << io if READABLE.include?(interests)
-
7612
(w ||= []) << io if WRITABLE.include?(interests)
-
-
7612
io.state == :closed
-
end
-
-
2026
if @selectables.empty?
-
2026
@selectables = selectables
-
-
# do not run event loop if there's nothing to wait on.
-
# this might happen if connect failed and connection was unregistered.
-
2026
return if (!r || r.empty?) && (!w || w.empty?) && !selectables.empty?
-
-
2003
break
-
else
-
@selectables.concat(selectables)
-
end
-
rescue StandardError
-
@selectables = selectables if selectables
-
raise
-
end
-
end
-
-
# TODO: what to do if there are no selectables?
-
-
2003
readers, writers = IO.select(r, w, nil, interval)
-
-
2003
if readers.nil? && writers.nil? && interval
-
188
[*r, *w].each { |io| io.handle_socket_timeout(interval) }
-
145
return
-
end
-
rescue IOError, SystemCallError
-
@selectables.reject!(&:closed?)
-
retry
-
end
-
-
1858
if writers
-
162
readers.each do |io|
-
992
yield io
-
-
# so that we don't yield 2 times
-
991
writers.delete(io)
-
1857
end if readers
-
-
1857
writers.each(&block)
-
else
-
readers.each(&block) if readers
-
end
-
end
-
-
24
def select_one(interval)
-
2227227
io = @selectables.first
-
-
2227227
return unless io
-
-
2227227
interests = io.interests
-
-
2227227
result = case interests
-
9394
when :r then io.to_io.wait_readable(interval)
-
7109
when :w then io.to_io.wait_writable(interval)
-
when :rw then io.to_io.wait(interval, :read_write)
-
2210724
when nil then return
-
end
-
-
16503
unless result || interval.nil?
-
427
io.handle_socket_timeout(interval)
-
422
return
-
end
-
# raise HTTPX::TimeoutError.new(interval, "timed out while waiting on select")
-
-
16076
yield io
-
rescue IOError, SystemCallError
-
@selectables.reject!(&:closed?)
-
raise unless @selectables.empty?
-
end
-
-
24
def select(interval, &block)
-
# do not cause an infinite loop here.
-
#
-
# this may happen if timeout calculation actually triggered an error which causes
-
# the connections to be reaped (such as the total timeout error) before #select
-
# gets called.
-
2229253
return if interval.nil? && @selectables.empty?
-
-
2229253
return select_one(interval, &block) if @selectables.size == 1
-
-
2026
select_many(interval, &block)
-
end
-
-
24
public :select
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
EMPTY_HASH = {}.freeze
-
-
# Class implementing the APIs being used publicly.
-
#
-
# HTTPX.get(..) #=> delegating to an internal HTTPX::Session object.
-
# HTTPX.plugin(..).get(..) #=> creating an intermediate HTTPX::Session with plugin, then sending the GET request
-
24
class Session
-
24
include Loggable
-
24
include Chainable
-
-
# initializes the session with a set of +options+, which will be shared by all
-
# requests sent from it.
-
#
-
# When pass a block, it'll yield itself to it, then closes after the block is evaluated.
-
24
def initialize(options = EMPTY_HASH, &blk)
-
8618
@options = self.class.default_options.merge(options)
-
8618
@responses = {}
-
8618
@persistent = @options.persistent
-
8618
wrap(&blk) if blk
-
end
-
-
# Yields itself the block, then closes it after the block is evaluated.
-
#
-
# session.wrap do |http|
-
# http.get("https://wikipedia.com")
-
# end # wikipedia connection closes here
-
24
def wrap
-
425
prev_persistent = @persistent
-
425
@persistent = true
-
425
pool.wrap do
-
46
begin
-
425
yield self
-
ensure
-
425
@persistent = prev_persistent
-
425
close unless @persistent
-
end
-
end
-
end
-
-
# closes all the active connections from the session
-
24
def close(*args)
-
5598
pool.close(*args)
-
end
-
-
# performs one, or multple requests; it accepts:
-
#
-
# 1. one or multiple HTTPX::Request objects;
-
# 2. an HTTP verb, then a sequence of URIs or URI/options tuples;
-
# 3. one or multiple HTTP verb / uri / (optional) options tuples;
-
#
-
# when present, the set of +options+ kwargs is applied to all of the
-
# sent requests.
-
#
-
# respectively returns a single HTTPX::Response response, or all of them in an Array, in the same order.
-
#
-
# resp1 = session.request(req1)
-
# resp1, resp2 = session.request(req1, req2)
-
# resp1 = session.request("GET", "https://server.org/a")
-
# resp1, resp2 = session.request("GET", ["https://server.org/a", "https://server.org/b"])
-
# resp1, resp2 = session.request(["GET", "https://server.org/a"], ["GET", "https://server.org/b"])
-
# resp1 = session.request("POST", "https://server.org/a", form: { "foo" => "bar" })
-
# resp1, resp2 = session.request(["POST", "https://server.org/a", form: { "foo" => "bar" }], ["GET", "https://server.org/b"])
-
# resp1, resp2 = session.request("GET", ["https://server.org/a", "https://server.org/b"], headers: { "x-api-token" => "TOKEN" })
-
#
-
24
def request(*args, **params)
-
5837
raise ArgumentError, "must perform at least one request" if args.empty?
-
-
5837
requests = args.first.is_a?(Request) ? args : build_requests(*args, params)
-
5816
responses = send_requests(*requests)
-
5692
return responses.first if responses.size == 1
-
-
167
responses
-
end
-
-
# returns a HTTP::Request instance built from the HTTP +verb+, the request +uri+, and
-
# the optional set of request-specific +options+. This request **must** be sent through
-
# the same session it was built from.
-
#
-
# req = session.build_request("GET", "https://server.com")
-
# resp = session.request(req)
-
24
def build_request(verb, uri, params = EMPTY_HASH, options = @options)
-
7052
rklass = options.request_class
-
7052
request = rklass.new(verb, uri, options, params)
-
7031
request.persistent = @persistent
-
7031
set_request_callbacks(request)
-
7031
request
-
end
-
-
24
private
-
-
# returns the HTTPX::Pool object which manages the networking required to
-
# perform requests.
-
24
def pool
-
2240687
Thread.current[:httpx_connection_pool] ||= Pool.new
-
end
-
-
# callback executed when a response for a given request has been received.
-
24
def on_response(request, response)
-
6449
@responses[request] = response
-
end
-
-
# callback executed when an HTTP/2 promise frame has been received.
-
24
def on_promise(_, stream)
-
7
log(level: 2) { "#{stream.id}: refusing stream!" }
-
7
stream.refuse
-
end
-
-
# returns the corresponding HTTP::Response to the given +request+ if it has been received.
-
24
def fetch_response(request, _, _)
-
2235453
@responses.delete(request)
-
end
-
-
# returns the HTTPX::Connection through which the +request+ should be sent through.
-
24
def find_connection(request, connections, options)
-
7046
uri = request.uri
-
-
7046
connection = pool.find_connection(uri, options) || init_connection(uri, options)
-
6988
unless connections.nil? || connections.include?(connection)
-
5618
connections << connection
-
5618
set_connection_callbacks(connection, connections, options)
-
end
-
6988
connection
-
end
-
-
# sends the +request+ to the corresponding HTTPX::Connection
-
24
def send_request(request, connections, options = request.options)
-
7367
error = catch(:resolve_error) do
-
7367
connection = find_connection(request, connections, options)
-
7288
connection.send(request)
-
end
-
7341
return unless error.is_a?(Error)
-
-
58
request.emit(:response, ErrorResponse.new(request, error))
-
end
-
-
# sets the callbacks on the +connection+ required to process certain specific
-
# connection lifecycle events which deal with request rerouting.
-
24
def set_connection_callbacks(connection, connections, options, cloned: false)
-
5952
connection.only(:misdirected) do |misdirected_request|
-
7
other_connection = connection.create_idle(ssl: { alpn_protocols: %w[http/1.1] })
-
7
other_connection.merge(connection)
-
7
catch(:coalesced) do
-
7
pool.init_connection(other_connection, options)
-
end
-
7
set_connection_callbacks(other_connection, connections, options)
-
7
connections << other_connection
-
7
misdirected_request.transition(:idle)
-
7
other_connection.send(misdirected_request)
-
end
-
5952
connection.only(:altsvc) do |alt_origin, origin, alt_params|
-
7
other_connection = build_altsvc_connection(connection, connections, alt_origin, origin, alt_params, options)
-
7
connections << other_connection if other_connection
-
end
-
5200
connection.only(:cloned) do |cloned_conn|
-
set_connection_callbacks(cloned_conn, connections, options, cloned: true)
-
connections << cloned_conn
-
5951
end unless cloned
-
end
-
-
# returns an HTTPX::Connection for the negotiated Alternative Service (or none).
-
24
def build_altsvc_connection(existing_connection, connections, alt_origin, origin, alt_params, options)
-
# do not allow security downgrades on altsvc negotiation
-
7
return if existing_connection.origin.scheme == "https" && alt_origin.scheme != "https"
-
-
7
altsvc = AltSvc.cached_altsvc_set(origin, alt_params.merge("origin" => alt_origin))
-
-
# altsvc already exists, somehow it wasn't advertised, probably noop
-
7
return unless altsvc
-
-
7
alt_options = options.merge(ssl: options.ssl.merge(hostname: URI(origin).host))
-
-
7
connection = pool.find_connection(alt_origin, alt_options) || init_connection(alt_origin, alt_options)
-
-
# advertised altsvc is the same origin being used, ignore
-
7
return if connection == existing_connection
-
-
7
connection.extend(AltSvc::ConnectionMixin) unless connection.is_a?(AltSvc::ConnectionMixin)
-
-
7
set_connection_callbacks(connection, connections, alt_options)
-
-
7
log(level: 1) { "#{origin} alt-svc: #{alt_origin}" }
-
-
7
connection.merge(existing_connection)
-
7
existing_connection.terminate
-
7
connection
-
rescue UnsupportedSchemeError
-
altsvc["noop"] = true
-
nil
-
end
-
-
# returns a set of HTTPX::Request objects built from the given +args+ and +options+.
-
24
def build_requests(*args, params)
-
5404
requests = if args.size == 1
-
68
reqs = args.first
-
# TODO: find a way to make requests share same options object
-
68
reqs.map do |verb, uri, ps = EMPTY_HASH|
-
136
request_params = params
-
136
request_params = request_params.merge(ps) unless ps.empty?
-
136
build_request(verb, uri, request_params)
-
end
-
else
-
5336
verb, uris = args
-
5336
if uris.respond_to?(:each)
-
# TODO: find a way to make requests share same options object
-
5126
uris.enum_for(:each).map do |uri, ps = EMPTY_HASH|
-
5850
request_params = params
-
5850
request_params = request_params.merge(ps) unless ps.empty?
-
5850
build_request(verb, uri, request_params)
-
end
-
else
-
210
[build_request(verb, uris, params)]
-
end
-
end
-
5383
raise ArgumentError, "wrong number of URIs (given 0, expect 1..+1)" if requests.empty?
-
-
5383
requests
-
end
-
-
24
def set_request_callbacks(request)
-
7031
request.on(:response, &method(:on_response).curry(2)[request])
-
7031
request.on(:promise, &method(:on_promise))
-
end
-
-
24
def init_connection(uri, options)
-
5894
connection = options.connection_class.new(uri, options)
-
5880
catch(:coalesced) do
-
5880
pool.init_connection(connection, options)
-
5831
connection
-
end
-
end
-
-
24
def deactivate_connection(request, connections, options)
-
109
conn = connections.find do |c|
-
109
c.match?(request.uri, options)
-
end
-
-
109
pool.deactivate(conn) if conn
-
end
-
-
# sends an array of HTTPX::Request +requests+, returns the respective array of HTTPX::Response objects.
-
24
def send_requests(*requests)
-
5902
connections = _send_requests(requests)
-
5876
receive_requests(requests, connections)
-
end
-
-
# sends an array of HTTPX::Request objects
-
24
def _send_requests(requests)
-
5902
connections = []
-
-
5902
requests.each do |request|
-
6681
send_request(request, connections)
-
end
-
-
5876
connections
-
end
-
-
# returns the array of HTTPX::Response objects corresponding to the array of HTTPX::Request +requests+.
-
24
def receive_requests(requests, connections)
-
# @type var responses: Array[response]
-
5876
responses = []
-
-
741
begin
-
# guarantee ordered responses
-
5876
loop do
-
6662
request = requests.first
-
-
6662
return responses unless request
-
-
3363603
catch(:coalesced) { pool.next_tick } until (response = fetch_response(request, connections, request.options))
-
6564
request.emit(:complete, response)
-
-
6564
responses << response
-
6564
requests.shift
-
-
6564
break if requests.empty?
-
-
786
next unless pool.empty?
-
-
# in some cases, the pool of connections might have been drained because there was some
-
# handshake error, and the error responses have already been emitted, but there was no
-
# opportunity to traverse the requests, hence we're returning only a fraction of the errors
-
# we were supposed to. This effectively fetches the existing responses and return them.
-
while (request = requests.shift)
-
response = fetch_response(request, connections, request.options)
-
request.emit(:complete, response) if response
-
responses << response
-
end
-
break
-
end
-
5778
responses
-
ensure
-
5876
if @persistent
-
869
pool.deactivate(*connections)
-
else
-
5007
close(connections)
-
end
-
end
-
end
-
-
24
@default_options = Options.new
-
24
@default_options.freeze
-
24
@plugins = []
-
-
24
class << self
-
24
attr_reader :default_options
-
-
24
def inherited(klass)
-
4243
super
-
4243
klass.instance_variable_set(:@default_options, @default_options)
-
4243
klass.instance_variable_set(:@plugins, @plugins.dup)
-
4243
klass.instance_variable_set(:@callbacks, @callbacks.dup)
-
end
-
-
# returns a new HTTPX::Session instance, with the plugin pointed by +pl+ loaded.
-
#
-
# session_with_retries = session.plugin(:retries)
-
# session_with_custom = session.plugin(CustomPlugin)
-
#
-
24
def plugin(pl, options = nil, &block)
-
# raise Error, "Cannot add a plugin to a frozen config" if frozen?
-
5781
pl = Plugins.load_plugin(pl) if pl.is_a?(Symbol)
-
5781
if !@plugins.include?(pl)
-
5588
@plugins << pl
-
5588
pl.load_dependencies(self, &block) if pl.respond_to?(:load_dependencies)
-
-
5588
@default_options = @default_options.dup
-
-
5588
include(pl::InstanceMethods) if defined?(pl::InstanceMethods)
-
5588
extend(pl::ClassMethods) if defined?(pl::ClassMethods)
-
-
5588
opts = @default_options
-
5588
opts.extend_with_plugin_classes(pl)
-
5588
if defined?(pl::OptionsMethods)
-
-
2204
(pl::OptionsMethods.instance_methods - Object.instance_methods).each do |meth|
-
6414
opts.options_class.method_added(meth)
-
end
-
2204
@default_options = opts.options_class.new(opts)
-
end
-
-
5588
@default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
-
5588
@default_options = @default_options.merge(options) if options
-
-
5588
pl.configure(self, &block) if pl.respond_to?(:configure)
-
-
5588
@default_options.freeze
-
192
elsif options
-
# this can happen when two plugins are loaded, an one of them calls the other under the hood,
-
# albeit changing some default.
-
14
@default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
-
14
@default_options = @default_options.merge(options) if options
-
-
14
@default_options.freeze
-
end
-
5781
self
-
end
-
end
-
end
-
-
# session may be overridden by certain adapters.
-
24
S = Session
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
unless ENV.keys.grep(/\Ahttps?_proxy\z/i).empty?
-
1
proxy_session = plugin(:proxy)
-
1
remove_const(:Session)
-
1
const_set(:Session, proxy_session.class)
-
-
# redefine the default options static var, which needs to
-
# refresh options_class
-
1
options = proxy_session.class.default_options.to_hash
-
1
original_verbosity = $VERBOSE
-
1
$VERBOSE = nil
-
1
const_set(:Options, proxy_session.class.default_options.options_class)
-
1
options[:options_class] = Class.new(options[:options_class])
-
1
options.freeze
-
1
Options.send(:const_set, :DEFAULT_OPTIONS, options)
-
1
Session.instance_variable_set(:@default_options, Options.new(options))
-
1
$VERBOSE = original_verbosity
-
end
-
-
skipped
# :nocov:
-
skipped
if Session.default_options.debug_level > 2
-
skipped
proxy_session = plugin(:internal_telemetry)
-
skipped
remove_const(:Session)
-
skipped
const_set(:Session, proxy_session.class)
-
skipped
end
-
skipped
# :nocov:
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
class Timers
-
24
def initialize
-
548
@intervals = []
-
end
-
-
24
def after(interval_in_secs, cb = nil, &blk)
-
34587
return unless interval_in_secs
-
-
34587
callback = cb || blk
-
-
# I'm assuming here that most requests will have the same
-
# request timeout, as in most cases they share common set of
-
# options. A user setting different request timeouts for 100s of
-
# requests will already have a hard time dealing with that.
-
63196
unless (interval = @intervals.find { |t| t.interval == interval_in_secs })
-
7120
interval = Interval.new(interval_in_secs)
-
13949
interval.on_empty { @intervals.delete(interval) }
-
7120
@intervals << interval
-
7120
@intervals.sort!
-
end
-
-
34587
interval << callback
-
-
34587
@next_interval_at = nil
-
-
34587
interval
-
end
-
-
24
def wait_interval
-
2229253
return if @intervals.empty?
-
-
2215117
@next_interval_at = Utils.now
-
-
2215117
@intervals.first.interval
-
end
-
-
24
def fire(error = nil)
-
2229143
raise error if error && error.timeout != @intervals.first
-
2229138
return if @intervals.empty? || !@next_interval_at
-
-
2210032
elapsed_time = Utils.elapsed_time(@next_interval_at)
-
-
4420076
@intervals = @intervals.drop_while { |interval| interval.elapse(elapsed_time) <= 0 }
-
-
2210032
@next_interval_at = nil if @intervals.empty?
-
end
-
-
24
class Interval
-
24
include Comparable
-
-
24
attr_reader :interval
-
-
24
def initialize(interval)
-
7120
@interval = interval
-
7120
@callbacks = []
-
7120
@on_empty = nil
-
end
-
-
24
def on_empty(&blk)
-
7120
@on_empty = blk
-
end
-
-
24
def <=>(other)
-
653
@interval <=> other.interval
-
end
-
-
24
def ==(other)
-
2141
return @interval == other if other.is_a?(Numeric)
-
-
2141
@interval == other.to_f # rubocop:disable Lint/FloatComparison
-
end
-
-
24
def to_f
-
2141
Float(@interval)
-
end
-
-
24
def <<(callback)
-
34587
@callbacks << callback
-
end
-
-
24
def delete(callback)
-
51064
@callbacks.delete(callback)
-
51064
@on_empty.call if @callbacks.empty?
-
end
-
-
24
def no_callbacks?
-
51064
@callbacks.empty?
-
end
-
-
24
def elapsed?
-
1087
@interval <= 0
-
end
-
-
24
def elapse(elapsed)
-
1083138
@interval -= elapsed
-
-
2210044
if @interval <= 0
-
481
cb = @callbacks.dup
-
481
cb.each(&:call)
-
end
-
-
2210044
@interval
-
end
-
end
-
24
private_constant :Interval
-
end
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
module Transcoder
-
24
module_function
-
-
24
def normalize_keys(key, value, cond = nil, &block)
-
2957
if cond && cond.call(value)
-
931
block.call(key.to_s, value)
-
2025
elsif value.respond_to?(:to_ary)
-
397
if value.empty?
-
112
block.call("#{key}[]")
-
else
-
285
value.to_ary.each do |element|
-
458
normalize_keys("#{key}[]", element, cond, &block)
-
end
-
end
-
1628
elsif value.respond_to?(:to_hash)
-
448
value.to_hash.each do |child_key, child_value|
-
448
normalize_keys("#{key}[#{child_key}]", child_value, cond, &block)
-
end
-
else
-
1181
block.call(key.to_s, value)
-
end
-
end
-
-
# based on https://github.com/rack/rack/blob/d15dd728440710cfc35ed155d66a98dc2c07ae42/lib/rack/query_parser.rb#L82
-
24
def normalize_query(params, name, v, depth)
-
161
raise Error, "params depth surpasses what's supported" if depth <= 0
-
-
161
name =~ /\A[\[\]]*([^\[\]]+)\]*/
-
161
k = Regexp.last_match(1) || ""
-
161
after = Regexp.last_match ? Regexp.last_match.post_match : ""
-
-
161
if k.empty?
-
14
return Array(v) if !v.empty? && name == "[]"
-
-
6
return
-
end
-
-
126
case after
-
when ""
-
42
params[k] = v
-
when "["
-
6
params[name] = v
-
when "[]"
-
14
params[k] ||= []
-
14
raise Error, "expected Array (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Array)
-
-
14
params[k] << v
-
when /^\[\]\[([^\[\]]+)\]$/, /^\[\](.+)$/
-
28
child_key = Regexp.last_match(1)
-
28
params[k] ||= []
-
28
raise Error, "expected Array (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Array)
-
-
28
if params[k].last.is_a?(Hash) && !params_hash_has_key?(params[k].last, child_key)
-
7
normalize_query(params[k].last, child_key, v, depth - 1)
-
else
-
21
params[k] << normalize_query({}, child_key, v, depth - 1)
-
end
-
else
-
49
params[k] ||= {}
-
49
raise Error, "expected Hash (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Hash)
-
-
42
params[k] = normalize_query(params[k], after, v, depth - 1)
-
end
-
-
147
params
-
end
-
-
24
def params_hash_has_key?(hash, key)
-
14
return false if key.include?("[]")
-
-
14
key.split(/[\[\]]+/).inject(hash) do |h, part|
-
14
next h if part == ""
-
14
return false unless h.is_a?(Hash) && h.key?(part)
-
-
7
h[part]
-
end
-
-
7
true
-
end
-
end
-
end
-
-
24
require "httpx/transcoder/body"
-
24
require "httpx/transcoder/form"
-
24
require "httpx/transcoder/json"
-
24
require "httpx/transcoder/xml"
-
24
require "httpx/transcoder/chunker"
-
24
require "httpx/transcoder/deflate"
-
24
require "httpx/transcoder/gzip"
-
# frozen_string_literal: true
-
-
24
require "forwardable"
-
-
24
module HTTPX::Transcoder
-
24
module Body
-
24
class Error < HTTPX::Error; end
-
-
24
module_function
-
-
24
class Encoder
-
24
extend Forwardable
-
-
24
def_delegator :@raw, :to_s
-
-
24
def_delegator :@raw, :==
-
-
24
def initialize(body)
-
1043
@raw = body
-
end
-
-
24
def bytesize
-
4017
if @raw.respond_to?(:bytesize)
-
2152
@raw.bytesize
-
1864
elsif @raw.respond_to?(:to_ary)
-
778
@raw.sum(&:bytesize)
-
1086
elsif @raw.respond_to?(:size)
-
604
@raw.size || Float::INFINITY
-
482
elsif @raw.respond_to?(:length)
-
224
@raw.length || Float::INFINITY
-
258
elsif @raw.respond_to?(:each)
-
252
Float::INFINITY
-
else
-
7
raise Error, "cannot determine size of body: #{@raw.inspect}"
-
end
-
end
-
-
24
def content_type
-
1001
"application/octet-stream"
-
end
-
-
24
private
-
-
24
def respond_to_missing?(meth, *args)
-
4497
@raw.respond_to?(meth, *args) || super
-
end
-
-
24
def method_missing(meth, *args, &block)
-
893
return super unless @raw.respond_to?(meth)
-
-
893
@raw.__send__(meth, *args, &block)
-
end
-
end
-
-
24
def encode(body)
-
1043
Encoder.new(body)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "forwardable"
-
-
24
module HTTPX::Transcoder
-
24
module Chunker
-
24
class Error < HTTPX::Error; end
-
-
24
CRLF = "\r\n".b
-
-
24
class Encoder
-
24
extend Forwardable
-
-
24
def initialize(body)
-
84
@raw = body
-
end
-
-
24
def each
-
84
return enum_for(__method__) unless block_given?
-
-
84
@raw.each do |chunk|
-
392
yield "#{chunk.bytesize.to_s(16)}#{CRLF}#{chunk}#{CRLF}"
-
end
-
84
yield "0#{CRLF}"
-
end
-
-
24
def respond_to_missing?(meth, *args)
-
132
@raw.respond_to?(meth, *args) || super
-
end
-
end
-
-
24
class Decoder
-
24
extend Forwardable
-
-
24
def_delegator :@buffer, :empty?
-
-
24
def_delegator :@buffer, :<<
-
-
24
def_delegator :@buffer, :clear
-
-
24
def initialize(buffer, trailers = false)
-
100
@buffer = buffer
-
100
@chunk_buffer = "".b
-
100
@finished = false
-
100
@state = :length
-
100
@trailers = trailers
-
end
-
-
24
def to_s
-
93
@buffer
-
end
-
-
24
def each
-
170
loop do
-
894
case @state
-
when :length
-
298
index = @buffer.index(CRLF)
-
298
return unless index && index.positive?
-
-
# Read hex-length
-
298
hexlen = @buffer.byteslice(0, index)
-
298
@buffer = @buffer.byteslice(index..-1) || "".b
-
298
hexlen[/\h/] || raise(Error, "wrong chunk size line: #{hexlen}")
-
298
@chunk_length = hexlen.hex
-
# check if is last chunk
-
298
@finished = @chunk_length.zero?
-
298
nextstate(:crlf)
-
when :crlf
-
496
crlf_size = @finished && !@trailers ? 4 : 2
-
# consume CRLF
-
496
return if @buffer.bytesize < crlf_size
-
496
raise Error, "wrong chunked encoding format" unless @buffer.start_with?(CRLF * (crlf_size / 2))
-
-
496
@buffer = @buffer.byteslice(crlf_size..-1)
-
496
if @chunk_length.nil?
-
198
nextstate(:length)
-
else
-
298
return if @finished
-
-
205
nextstate(:data)
-
end
-
when :data
-
247
chunk = @buffer.byteslice(0, @chunk_length)
-
247
@buffer = @buffer.byteslice(@chunk_length..-1) || "".b
-
247
@chunk_buffer << chunk
-
212
@chunk_length -= chunk.bytesize
-
247
if @chunk_length.zero?
-
205
yield @chunk_buffer unless @chunk_buffer.empty?
-
198
@chunk_buffer.clear
-
198
@chunk_length = nil
-
198
nextstate(:crlf)
-
end
-
end
-
941
break if @buffer.empty?
-
end
-
end
-
-
24
def finished?
-
163
@finished
-
end
-
-
24
private
-
-
24
def nextstate(state)
-
899
@state = state
-
end
-
end
-
-
24
module_function
-
-
24
def encode(chunks)
-
84
Encoder.new(chunks)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "zlib"
-
24
require_relative "utils/deflater"
-
-
24
module HTTPX
-
24
module Transcoder
-
24
module Deflate
-
24
class Deflater < Transcoder::Deflater
-
24
def deflate(chunk)
-
42
@deflater ||= Zlib::Deflate.new
-
-
42
if chunk.nil?
-
28
unless @deflater.closed?
-
14
last = @deflater.finish
-
14
@deflater.close
-
14
last.empty? ? nil : last
-
end
-
else
-
14
@deflater.deflate(chunk)
-
end
-
end
-
end
-
-
24
module_function
-
-
24
def encode(body)
-
14
Deflater.new(body)
-
end
-
-
24
def decode(response, bytesize: nil)
-
14
bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
-
14
GZIP::Inflater.new(bytesize)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "forwardable"
-
24
require "uri"
-
24
require_relative "multipart"
-
-
24
module HTTPX
-
24
module Transcoder
-
24
module Form
-
24
module_function
-
-
24
PARAM_DEPTH_LIMIT = 32
-
-
24
class Encoder
-
24
extend Forwardable
-
-
24
def_delegator :@raw, :to_s
-
-
24
def_delegator :@raw, :to_str
-
-
24
def_delegator :@raw, :bytesize
-
-
24
def_delegator :@raw, :==
-
-
24
def initialize(form)
-
602
@raw = form.each_with_object("".b) do |(key, val), buf|
-
1008
HTTPX::Transcoder.normalize_keys(key, val) do |k, v|
-
1181
buf << "&" unless buf.empty?
-
1181
buf << URI.encode_www_form_component(k)
-
1181
buf << "=#{URI.encode_www_form_component(v.to_s)}" unless v.nil?
-
end
-
end
-
end
-
-
24
def content_type
-
470
"application/x-www-form-urlencoded"
-
end
-
end
-
-
24
module Decoder
-
24
module_function
-
-
24
def call(response, *)
-
35
URI.decode_www_form(response.to_s).each_with_object({}) do |(field, value), params|
-
84
HTTPX::Transcoder.normalize_query(params, field, value, PARAM_DEPTH_LIMIT)
-
end
-
end
-
end
-
-
24
def encode(form)
-
1434
if multipart?(form)
-
832
Multipart::Encoder.new(form)
-
else
-
602
Encoder.new(form)
-
end
-
end
-
-
24
def decode(response)
-
56
content_type = response.content_type.mime_type
-
-
48
case content_type
-
when "application/x-www-form-urlencoded"
-
35
Decoder
-
when "multipart/form-data"
-
14
Multipart::Decoder.new(response)
-
else
-
7
raise Error, "invalid form mime type (#{content_type})"
-
end
-
end
-
-
24
def multipart?(data)
-
1434
data.any? do |_, v|
-
1896
Multipart::MULTIPART_VALUE_COND.call(v) ||
-
1456
(v.respond_to?(:to_ary) && v.to_ary.any?(&Multipart::MULTIPART_VALUE_COND)) ||
-
1792
(v.respond_to?(:to_hash) && v.to_hash.any? { |_, e| Multipart::MULTIPART_VALUE_COND.call(e) })
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "forwardable"
-
24
require "uri"
-
24
require "stringio"
-
24
require "zlib"
-
-
24
module HTTPX
-
24
module Transcoder
-
24
module GZIP
-
24
class Deflater < Transcoder::Deflater
-
24
def initialize(body)
-
34
@compressed_chunk = "".b
-
34
super
-
end
-
-
24
def deflate(chunk)
-
68
@deflater ||= Zlib::GzipWriter.new(self)
-
-
68
if chunk.nil?
-
34
unless @deflater.closed?
-
34
@deflater.flush
-
34
@deflater.close
-
34
compressed_chunk
-
end
-
else
-
34
@deflater.write(chunk)
-
34
compressed_chunk
-
end
-
end
-
-
24
private
-
-
24
def write(chunk)
-
102
@compressed_chunk << chunk
-
end
-
-
24
def compressed_chunk
-
68
@compressed_chunk.dup
-
ensure
-
68
@compressed_chunk.clear
-
end
-
end
-
-
24
class Inflater
-
24
def initialize(bytesize)
-
135
@inflater = Zlib::Inflate.new(Zlib::MAX_WBITS + 32)
-
135
@bytesize = bytesize
-
end
-
-
24
def call(chunk)
-
371
buffer = @inflater.inflate(chunk)
-
336
@bytesize -= chunk.bytesize
-
371
if @bytesize <= 0
-
80
buffer << @inflater.finish
-
80
@inflater.close
-
end
-
371
buffer
-
end
-
end
-
-
24
module_function
-
-
24
def encode(body)
-
34
Deflater.new(body)
-
end
-
-
24
def decode(response, bytesize: nil)
-
121
bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
-
121
Inflater.new(bytesize)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "forwardable"
-
-
24
module HTTPX::Transcoder
-
24
module JSON
-
24
module_function
-
-
24
JSON_REGEX = %r{\bapplication/(?:vnd\.api\+|hal\+)?json\b}i.freeze
-
-
24
class Encoder
-
24
extend Forwardable
-
-
24
def_delegator :@raw, :to_s
-
-
24
def_delegator :@raw, :bytesize
-
-
24
def_delegator :@raw, :==
-
-
24
def initialize(json)
-
63
@raw = JSON.json_dump(json)
-
63
@charset = @raw.encoding.name.downcase
-
end
-
-
24
def content_type
-
63
"application/json; charset=#{@charset}"
-
end
-
end
-
-
24
def encode(json)
-
63
Encoder.new(json)
-
end
-
-
24
def decode(response)
-
65
content_type = response.content_type.mime_type
-
-
65
raise HTTPX::Error, "invalid json mime type (#{content_type})" unless JSON_REGEX.match?(content_type)
-
-
58
method(:json_load)
-
end
-
-
# rubocop:disable Style/SingleLineMethods
-
24
if defined?(MultiJson)
-
4
def json_load(*args); MultiJson.load(*args); end
-
1
def json_dump(*args); MultiJson.dump(*args); end
-
22
elsif defined?(Oj)
-
4
def json_load(response, *args); Oj.load(response.to_s, *args); end
-
1
def json_dump(*args); Oj.dump(*args); end
-
21
elsif defined?(Yajl)
-
4
def json_load(response, *args); Yajl::Parser.new(*args).parse(response.to_s); end
-
1
def json_dump(*args); Yajl::Encoder.encode(*args); end
-
else
-
21
require "json"
-
63
def json_load(*args); ::JSON.parse(*args); end
-
75
def json_dump(*args); ::JSON.dump(*args); end
-
end
-
# rubocop:enable Style/SingleLineMethods
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require_relative "multipart/encoder"
-
24
require_relative "multipart/decoder"
-
24
require_relative "multipart/part"
-
24
require_relative "multipart/mime_type_detector"
-
-
24
module HTTPX::Transcoder
-
24
module Multipart
-
24
MULTIPART_VALUE_COND = lambda do |value|
-
4237
value.respond_to?(:read) ||
-
3038
(value.respond_to?(:to_hash) &&
-
value.key?(:body) &&
-
564
(value.key?(:filename) || value.key?(:content_type)))
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "tempfile"
-
24
require "delegate"
-
-
24
module HTTPX
-
24
module Transcoder
-
24
module Multipart
-
24
class FilePart < SimpleDelegator
-
24
attr_reader :original_filename, :content_type
-
-
24
def initialize(filename, content_type)
-
28
@original_filename = filename
-
28
@content_type = content_type
-
28
@file = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
28
super(@file)
-
end
-
end
-
-
24
class Decoder
-
24
include HTTPX::Utils
-
-
24
CRLF = "\r\n"
-
24
BOUNDARY_RE = /;\s*boundary=([^;]+)/i.freeze
-
24
MULTIPART_CONTENT_TYPE = /Content-Type: (.*)#{CRLF}/ni.freeze
-
24
MULTIPART_CONTENT_DISPOSITION = /Content-Disposition:.*;\s*name=(#{VALUE})/ni.freeze
-
24
MULTIPART_CONTENT_ID = /Content-ID:\s*([^#{CRLF}]*)/ni.freeze
-
24
WINDOW_SIZE = 2 << 14
-
-
24
def initialize(response)
-
2
@boundary = begin
-
14
m = response.headers["content-type"].to_s[BOUNDARY_RE, 1]
-
14
raise Error, "no boundary declared in content-type header" unless m
-
-
14
m.strip
-
end
-
14
@buffer = "".b
-
14
@parts = {}
-
14
@intermediate_boundary = "--#{@boundary}"
-
14
@state = :idle
-
end
-
-
24
def call(response, *)
-
14
response.body.each do |chunk|
-
14
@buffer << chunk
-
-
14
parse
-
end
-
-
14
raise Error, "invalid or unsupported multipart format" unless @buffer.empty?
-
-
14
@parts
-
end
-
-
24
private
-
-
24
def parse
-
12
case @state
-
when :idle
-
14
raise Error, "payload does not start with boundary" unless @buffer.start_with?("#{@intermediate_boundary}#{CRLF}")
-
-
14
@buffer = @buffer.byteslice(@intermediate_boundary.bytesize + 2..-1)
-
-
14
@state = :part_header
-
when :part_header
-
42
idx = @buffer.index("#{CRLF}#{CRLF}")
-
-
# raise Error, "couldn't parse part headers" unless idx
-
42
return unless idx
-
-
42
head = @buffer.byteslice(0..idx + 4 - 1)
-
-
42
@buffer = @buffer.byteslice(head.bytesize..-1)
-
-
42
content_type = head[MULTIPART_CONTENT_TYPE, 1]
-
72
if (name = head[MULTIPART_CONTENT_DISPOSITION, 1])
-
42
name = /\A"(.*)"\Z/ =~ name ? Regexp.last_match(1) : name.dup
-
42
name.gsub!(/\\(.)/, "\\1")
-
12
name
-
else
-
name = head[MULTIPART_CONTENT_ID, 1]
-
end
-
-
42
filename = HTTPX::Utils.get_filename(head)
-
-
42
name = filename || +"#{content_type || "text/plain"}[]" if name.nil? || name.empty?
-
-
42
@current = name
-
-
36
@parts[name] = if filename
-
28
FilePart.new(filename, content_type)
-
else
-
14
"".b
-
end
-
-
42
@state = :part_body
-
when :part_body
-
42
part = @parts[@current]
-
-
42
body_separator = if part.is_a?(FilePart)
-
24
"#{CRLF}#{CRLF}"
-
else
-
14
CRLF
-
end
-
42
idx = @buffer.index(body_separator)
-
-
42
if idx
-
42
payload = @buffer.byteslice(0..idx - 1)
-
42
@buffer = @buffer.byteslice(idx + body_separator.bytesize..-1)
-
42
part << payload
-
42
part.rewind if part.respond_to?(:rewind)
-
42
@state = :parse_boundary
-
else
-
part << @buffer
-
@buffer.clear
-
end
-
when :parse_boundary
-
42
raise Error, "payload does not start with boundary" unless @buffer.start_with?(@intermediate_boundary)
-
-
42
@buffer = @buffer.byteslice(@intermediate_boundary.bytesize..-1)
-
-
42
if @buffer == "--"
-
14
@buffer.clear
-
14
@state = :done
-
14
return
-
27
elsif @buffer.start_with?(CRLF)
-
28
@buffer = @buffer.byteslice(2..-1)
-
28
@state = :part_header
-
else
-
return
-
end
-
when :done
-
raise Error, "parsing should have been over by now"
-
20
end until @buffer.empty?
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
module Transcoder::Multipart
-
24
class Encoder
-
24
attr_reader :bytesize
-
-
24
def initialize(form)
-
832
@boundary = ("-" * 21) << SecureRandom.hex(21)
-
832
@part_index = 0
-
832
@buffer = "".b
-
-
832
@form = form
-
832
@parts = to_parts(form)
-
end
-
-
24
def content_type
-
832
"multipart/form-data; boundary=#{@boundary}"
-
end
-
-
24
def to_s
-
15
read
-
ensure
-
15
rewind
-
end
-
-
24
def read(length = nil, outbuf = nil)
-
3355
data = String(outbuf).clear.force_encoding(Encoding::BINARY) if outbuf
-
3355
data ||= "".b
-
-
3355
read_chunks(data, length)
-
-
3355
data unless length && data.empty?
-
end
-
-
24
def rewind
-
43
form = @form.each_with_object([]) do |(key, val), aux|
-
43
if val.respond_to?(:path) && val.respond_to?(:reopen) && val.respond_to?(:closed?) && val.closed?
-
43
val = val.reopen(val.path, File::RDONLY)
-
end
-
43
val.rewind if val.respond_to?(:rewind)
-
43
aux << [key, val]
-
end
-
43
@form = form
-
43
@parts = to_parts(form)
-
43
@part_index = 0
-
end
-
-
24
private
-
-
24
def to_parts(form)
-
875
@bytesize = 0
-
875
params = form.each_with_object([]) do |(key, val), aux|
-
1043
Transcoder.normalize_keys(key, val, MULTIPART_VALUE_COND) do |k, v|
-
1043
next if v.nil?
-
-
1043
value, content_type, filename = Part.call(v)
-
-
1043
header = header_part(k, content_type, filename)
-
899
@bytesize += header.size
-
1043
aux << header
-
-
899
@bytesize += value.size
-
1043
aux << value
-
-
1043
delimiter = StringIO.new("\r\n")
-
899
@bytesize += delimiter.size
-
1043
aux << delimiter
-
end
-
end
-
875
final_delimiter = StringIO.new("--#{@boundary}--\r\n")
-
755
@bytesize += final_delimiter.size
-
875
params << final_delimiter
-
-
875
params
-
end
-
-
24
def header_part(key, content_type, filename)
-
1043
header = "--#{@boundary}\r\n".b
-
1043
header << "Content-Disposition: form-data; name=#{key.inspect}".b
-
1043
header << "; filename=#{filename.inspect}" if filename
-
1043
header << "\r\nContent-Type: #{content_type}\r\n\r\n"
-
1043
StringIO.new(header)
-
end
-
-
24
def read_chunks(buffer, length = nil)
-
4455
while @part_index < @parts.size
-
9535
chunk = read_from_part(length)
-
-
9535
next unless chunk
-
-
5571
buffer << chunk.force_encoding(Encoding::BINARY)
-
-
5571
next unless length
-
-
4776
length -= chunk.bytesize
-
-
5516
break if length.zero?
-
end
-
end
-
-
# if there's a current part to read from, tries to read a chunk.
-
24
def read_from_part(max_length = nil)
-
9535
part = @parts[@part_index]
-
-
9535
chunk = part.read(max_length, @buffer)
-
-
9535
return chunk if chunk && !chunk.empty?
-
-
3964
part.close if part.respond_to?(:close)
-
-
3412
@part_index += 1
-
-
1104
nil
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
module Transcoder::Multipart
-
24
module MimeTypeDetector
-
24
module_function
-
-
24
DEFAULT_MIMETYPE = "application/octet-stream"
-
-
# inspired by https://github.com/shrinerb/shrine/blob/master/lib/shrine/plugins/determine_mime_type.rb
-
24
if defined?(FileMagic)
-
1
MAGIC_NUMBER = 256 * 1024
-
-
1
def call(file, _)
-
1
return nil if file.eof? # FileMagic returns "application/x-empty" for empty files
-
-
1
mime = FileMagic.open(FileMagic::MAGIC_MIME_TYPE) do |filemagic|
-
1
filemagic.buffer(file.read(MAGIC_NUMBER))
-
end
-
-
1
file.rewind
-
-
1
mime
-
end
-
22
elsif defined?(Marcel)
-
1
def call(file, filename)
-
1
return nil if file.eof? # marcel returns "application/octet-stream" for empty files
-
-
1
Marcel::MimeType.for(file, name: filename)
-
end
-
-
21
elsif defined?(MimeMagic)
-
-
1
def call(file, _)
-
1
mime = MimeMagic.by_magic(file)
-
1
mime.type if mime
-
end
-
-
20
elsif system("which file", out: File::NULL)
-
21
require "open3"
-
-
21
def call(file, _)
-
591
return if file.eof? # file command returns "application/x-empty" for empty files
-
-
553
Open3.popen3(*%w[file --mime-type --brief -]) do |stdin, stdout, stderr, thread|
-
75
begin
-
553
::IO.copy_stream(file, stdin.binmode)
-
rescue Errno::EPIPE
-
end
-
553
file.rewind
-
553
stdin.close
-
-
553
status = thread.value
-
-
# call to file command failed
-
553
if status.nil? || !status.success?
-
$stderr.print(stderr.read)
-
else
-
-
553
output = stdout.read.strip
-
-
553
if output.include?("cannot open")
-
$stderr.print(output)
-
else
-
553
output
-
end
-
end
-
end
-
end
-
-
else
-
-
def call(_, _); end
-
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
module Transcoder::Multipart
-
24
module Part
-
24
module_function
-
-
24
def call(value)
-
# take out specialized objects of the way
-
1043
if value.respond_to?(:filename) && value.respond_to?(:content_type) && value.respond_to?(:read)
-
96
return value, value.content_type, value.filename
-
end
-
-
931
content_type = filename = nil
-
-
931
if value.is_a?(Hash)
-
282
content_type = value[:content_type]
-
282
filename = value[:filename]
-
282
value = value[:body]
-
end
-
-
931
value = value.open(File::RDONLY) if Object.const_defined?(:Pathname) && value.is_a?(Pathname)
-
-
931
if value.respond_to?(:path) && value.respond_to?(:read)
-
# either a File, a Tempfile, or something else which has to quack like a file
-
595
filename ||= File.basename(value.path)
-
595
content_type ||= MimeTypeDetector.call(value, filename) || "application/octet-stream"
-
595
[value, content_type, filename]
-
else
-
336
[StringIO.new(value.to_s), content_type || "text/plain", filename]
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "stringio"
-
-
24
module HTTPX
-
24
module Transcoder
-
24
class BodyReader
-
24
def initialize(body)
-
163
@body = if body.respond_to?(:read)
-
10
body.rewind if body.respond_to?(:rewind)
-
10
body
-
152
elsif body.respond_to?(:each)
-
30
body.enum_for(:each)
-
else
-
123
StringIO.new(body.to_s)
-
end
-
end
-
-
24
def bytesize
-
335
return @body.bytesize if @body.respond_to?(:bytesize)
-
-
305
Float::INFINITY
-
end
-
-
24
def read(length = nil, outbuf = nil)
-
350
return @body.read(length, outbuf) if @body.respond_to?(:read)
-
-
begin
-
70
chunk = @body.next
-
40
if outbuf
-
40
outbuf.clear.force_encoding(Encoding::BINARY)
-
40
outbuf << chunk
-
else
-
outbuf = chunk
-
end
-
40
outbuf unless length && outbuf.empty?
-
24
rescue StopIteration
-
end
-
end
-
-
24
def close
-
34
@body.close if @body.respond_to?(:close)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "forwardable"
-
24
require_relative "body_reader"
-
-
24
module HTTPX
-
24
module Transcoder
-
24
class Deflater
-
24
extend Forwardable
-
-
24
attr_reader :content_type
-
-
24
def initialize(body)
-
58
@content_type = body.content_type
-
58
@body = BodyReader.new(body)
-
58
@closed = false
-
end
-
-
24
def bytesize
-
222
buffer_deflate!
-
-
222
@buffer.size
-
end
-
-
24
def read(length = nil, outbuf = nil)
-
280
return @buffer.read(length, outbuf) if @buffer
-
-
164
return if @closed
-
-
130
chunk = @body.read(length)
-
-
130
compressed_chunk = deflate(chunk)
-
-
130
return unless compressed_chunk
-
-
106
if outbuf
-
98
outbuf.clear.force_encoding(Encoding::BINARY)
-
98
outbuf << compressed_chunk
-
else
-
8
compressed_chunk
-
end
-
end
-
-
24
def close
-
34
return if @closed
-
-
34
@buffer.close if @buffer
-
-
34
@body.close
-
-
34
@closed = true
-
end
-
-
24
private
-
-
# rubocop:disable Naming/MemoizedInstanceVariableName
-
24
def buffer_deflate!
-
222
return @buffer if defined?(@buffer)
-
-
58
buffer = Response::Buffer.new(
-
threshold_size: Options::MAX_BODY_THRESHOLD_SIZE
-
)
-
58
::IO.copy_stream(self, buffer)
-
-
58
buffer.rewind
-
-
58
@buffer = buffer
-
end
-
# rubocop:enable Naming/MemoizedInstanceVariableName
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
require "delegate"
-
24
require "forwardable"
-
24
require "uri"
-
-
24
module HTTPX::Transcoder
-
24
module Xml
-
24
module_function
-
-
24
MIME_TYPES = %r{\b(application|text)/(.+\+)?xml\b}.freeze
-
-
24
class Encoder
-
24
def initialize(xml)
-
119
@raw = xml
-
end
-
-
24
def content_type
-
119
charset = @raw.respond_to?(:encoding) ? @raw.encoding.to_s.downcase : "utf-8"
-
119
"application/xml; charset=#{charset}"
-
end
-
-
24
def bytesize
-
357
@raw.to_s.bytesize
-
end
-
-
24
def to_s
-
112
@raw.to_s
-
end
-
end
-
-
24
def encode(xml)
-
119
Encoder.new(xml)
-
end
-
-
begin
-
24
require "nokogiri"
-
-
24
def decode(response)
-
7
content_type = response.content_type.mime_type
-
-
7
raise HTTPX::Error, "invalid form mime type (#{content_type})" unless MIME_TYPES.match?(content_type)
-
-
7
Nokogiri::XML.method(:parse)
-
end
-
rescue LoadError
-
def decode(_response)
-
raise HTTPX::Error, "\"nokogiri\" is required in order to decode XML"
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
24
module HTTPX
-
24
module Utils
-
24
using URIExtensions
-
-
24
TOKEN = %r{[^\s()<>,;:\\"/\[\]?=]+}.freeze
-
24
VALUE = /"(?:\\"|[^"])*"|#{TOKEN}/.freeze
-
24
FILENAME_REGEX = /\s*filename=(#{VALUE})/.freeze
-
24
FILENAME_EXTENSION_REGEX = /\s*filename\*=(#{VALUE})/.freeze
-
-
24
module_function
-
-
24
def now
-
2236729
Process.clock_gettime(Process::CLOCK_MONOTONIC)
-
end
-
-
24
def elapsed_time(monotonic_timestamp)
-
2211018
Process.clock_gettime(Process::CLOCK_MONOTONIC) - monotonic_timestamp
-
end
-
-
# The value of this field can be either an HTTP-date or a number of
-
# seconds to delay after the response is received.
-
24
def parse_retry_after(retry_after)
-
# first: bet on it being an integer
-
53
Integer(retry_after)
-
rescue ArgumentError
-
# Then it's a datetime
-
14
time = Time.httpdate(retry_after)
-
14
time - Time.now
-
end
-
-
24
def get_filename(header, _prefix_regex = nil)
-
77
filename = nil
-
66
case header
-
when FILENAME_REGEX
-
49
filename = Regexp.last_match(1)
-
49
filename = Regexp.last_match(1) if filename =~ /^"(.*)"$/
-
when FILENAME_EXTENSION_REGEX
-
14
filename = Regexp.last_match(1)
-
14
encoding, _, filename = filename.split("'", 3)
-
end
-
-
77
return unless filename
-
-
119
filename = URI::DEFAULT_PARSER.unescape(filename) if filename.scan(/%.?.?/).all? { |s| /%[0-9a-fA-F]{2}/.match?(s) }
-
-
63
filename.scrub!
-
-
63
filename = filename.gsub(/\\(.)/, '\1') unless /\\[^\\"]/.match?(filename)
-
-
63
filename.force_encoding ::Encoding.find(encoding) if encoding
-
-
63
filename
-
end
-
-
24
URIParser = URI::RFC2396_Parser.new
-
-
24
def to_uri(uri)
-
20119
return URI(uri) unless uri.is_a?(String) && !uri.ascii_only?
-
-
29
uri = URI(URIParser.escape(uri))
-
-
29
non_ascii_hostname = URIParser.unescape(uri.host)
-
-
29
non_ascii_hostname.force_encoding(Encoding::UTF_8)
-
-
29
idna_hostname = Punycode.encode_hostname(non_ascii_hostname)
-
-
29
uri.host = idna_hostname
-
28
uri.non_ascii_hostname = non_ascii_hostname
-
28
uri
-
end
-
end
-
end