-
# frozen_string_literal: true
-
-
23
require "httpx/version"
-
-
# Top-Level Namespace
-
#
-
23
module HTTPX
-
23
EMPTY = [].freeze
-
23
EMPTY_HASH = {}.freeze
-
-
# All plugins should be stored under this module/namespace. Can register and load
-
# plugins.
-
#
-
23
module Plugins
-
23
@plugins = {}
-
23
@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.
-
#
-
23
def self.load_plugin(name)
-
4042
h = @plugins
-
4042
m = @plugins_mutex
-
8084
unless (plugin = m.synchronize { h[name] })
-
86
require "httpx/plugins/#{name}"
-
172
raise "Plugin #{name} hasn't been registered" unless (plugin = m.synchronize { h[name] })
-
end
-
4042
plugin
-
end
-
-
# Registers a plugin (+mod+) in the central store indexed by +name+.
-
#
-
23
def self.register_plugin(name, mod)
-
237
h = @plugins
-
237
m = @plugins_mutex
-
474
m.synchronize { h[name] = mod }
-
end
-
end
-
end
-
-
23
require "httpx/extensions"
-
-
23
require "httpx/errors"
-
23
require "httpx/utils"
-
23
require "httpx/punycode"
-
23
require "httpx/domain_name"
-
23
require "httpx/altsvc"
-
23
require "httpx/callbacks"
-
23
require "httpx/loggable"
-
23
require "httpx/transcoder"
-
23
require "httpx/timers"
-
23
require "httpx/pool"
-
23
require "httpx/headers"
-
23
require "httpx/request"
-
23
require "httpx/response"
-
23
require "httpx/options"
-
23
require "httpx/chainable"
-
-
23
require "httpx/session"
-
23
require "httpx/session_extensions"
-
-
# load integrations when possible
-
-
23
require "httpx/adapters/datadog" if defined?(DDTrace) || defined?(Datadog)
-
23
require "httpx/adapters/sentry" if defined?(Sentry)
-
23
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)
-
223
@request = request
-
223
@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.
-
246
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.
-
343
request.on(:headers) { call }
-
end
-
-
# sets up the span start time, while preparing the on response callback.
-
5
def call(*args)
-
129
return if @start_time
-
-
124
start(*args)
-
-
124
@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)
-
129
@start_time = start_time
-
end
-
-
# resets the start time for already finished request transactions.
-
5
def reset
-
23
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)
-
124
return unless @start_time
-
-
124
span = initialize_span
-
-
124
return unless span
-
-
124
if response.is_a?(::HTTPX::ErrorResponse)
-
9
span.set_error(response.error)
-
else
-
115
span.set_tag(TAG_STATUS_CODE, response.status.to_s)
-
-
115
span.set_error(::HTTPX::HTTPError.new(response)) if response.status >= 400 && response.status <= 599
-
end
-
-
124
span.finish
-
ensure
-
124
@start_time = nil
-
end
-
-
# return a span initialized with the +@request+ state.
-
5
def initialize_span
-
124
verb = @request.verb
-
124
uri = @request.uri
-
-
124
span = create_span(@request)
-
-
124
span.resource = verb
-
-
# Add additional request specific tags to the span.
-
-
124
span.set_tag(TAG_URL, @request.path)
-
124
span.set_tag(TAG_METHOD, verb)
-
-
124
span.set_tag(TAG_TARGET_HOST, uri.host)
-
124
span.set_tag(TAG_TARGET_PORT, uri.port.to_s)
-
-
# Tag as an external peer service
-
124
span.set_tag(TAG_PEER_SERVICE, span.service)
-
-
124
if configuration[:distributed_tracing]
-
119
propagate_trace_http(
-
Datadog::Tracing.active_trace.to_digest,
-
@request.headers
-
)
-
end
-
-
# Set analytics sample rate
-
124
if Contrib::Analytics.enabled?(configuration[:analytics_enabled])
-
10
Contrib::Analytics.set_sample_rate(span, configuration[:analytics_sample_rate])
-
end
-
-
124
span
-
rescue StandardError => e
-
Datadog.logger.error("error preparing span for http request: #{e}")
-
Datadog.logger.error(e.backtrace)
-
end
-
-
5
def now
-
120
::Datadog::Core::Utils::Time.now.utc
-
end
-
-
5
def configuration
-
382
@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)
-
52
Datadog::Tracing::Contrib::HTTP.inject(digest, headers)
-
end
-
-
2
def create_span(request)
-
54
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)
-
67
Datadog::Tracing::Propagation::HTTP.inject!(digest, headers)
-
end
-
-
3
def create_span(request)
-
70
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(*)
-
214
super
-
-
214
return unless Datadog::Tracing.enabled?
-
-
214
RequestTracer.new(self)
-
end
-
end
-
-
5
module ConnectionMethods
-
5
attr_reader :init_time
-
-
5
def initialize(*)
-
201
super
-
-
201
@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
-
60
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
-
70
Configuration::Settings.new
-
end
-
-
5
def patcher
-
130
Patcher
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
7
require "delegate"
-
7
require "httpx"
-
7
require "faraday"
-
-
7
module Faraday
-
7
class Adapter
-
7
class HTTPX < Faraday::Adapter
-
7
module RequestMixin
-
7
def build_connection(env)
-
163
return @connection if defined?(@connection)
-
-
163
@connection = ::HTTPX.plugin(:persistent).plugin(ReasonPlugin)
-
163
@connection = @connection.with(@connection_options) unless @connection_options.empty?
-
163
connection_opts = options_from_env(env)
-
-
163
if (bind = env.request.bind)
-
6
@bind = TCPSocket.new(bind[:host], bind[:port])
-
6
connection_opts[:io] = @bind
-
end
-
163
@connection = @connection.with(connection_opts)
-
-
163
if (proxy = env.request.proxy)
-
6
proxy_options = { uri: proxy.uri }
-
6
proxy_options[:username] = proxy.user if proxy.user
-
6
proxy_options[:password] = proxy.password if proxy.password
-
-
6
@connection = @connection.plugin(:proxy).with(proxy: proxy_options)
-
end
-
163
@connection = @connection.plugin(OnDataPlugin) if env.request.stream_response?
-
-
163
@connection = @config_block.call(@connection) || @connection if @config_block
-
163
@connection
-
end
-
-
7
def close
-
168
@connection.close if @connection
-
168
@bind.close if @bind
-
end
-
-
7
private
-
-
7
def connect(env, &blk)
-
163
connection(env, &blk)
-
rescue ::HTTPX::TLSError => e
-
6
raise Faraday::SSLError, e
-
rescue Errno::ECONNABORTED,
-
Errno::ECONNREFUSED,
-
Errno::ECONNRESET,
-
Errno::EHOSTUNREACH,
-
Errno::EINVAL,
-
Errno::ENETUNREACH,
-
Errno::EPIPE,
-
::HTTPX::ConnectionError => e
-
6
raise Faraday::ConnectionFailed, e
-
end
-
-
7
def build_request(env)
-
169
meth = env[:method]
-
-
request_options = {
-
168
headers: env.request_headers,
-
body: env.body,
-
**options_from_env(env),
-
}
-
169
[meth.to_s.upcase, env.url, request_options]
-
end
-
-
7
def options_from_env(env)
-
332
timeout_options = {}
-
332
req_opts = env.request
-
332
if (sec = request_timeout(:read, req_opts))
-
12
timeout_options[:read_timeout] = sec
-
end
-
-
332
if (sec = request_timeout(:write, req_opts))
-
12
timeout_options[:write_timeout] = sec
-
end
-
-
332
if (sec = request_timeout(:open, req_opts))
-
12
timeout_options[:connect_timeout] = sec
-
end
-
-
{
-
331
ssl: ssl_options_from_env(env),
-
timeout: timeout_options,
-
}
-
end
-
-
7
if defined?(::OpenSSL)
-
7
def ssl_options_from_env(env)
-
332
ssl_options = {}
-
-
332
unless env.ssl.verify.nil?
-
24
ssl_options[:verify_mode] = env.ssl.verify ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
-
end
-
-
332
ssl_options[:ca_file] = env.ssl.ca_file if env.ssl.ca_file
-
332
ssl_options[:ca_path] = env.ssl.ca_path if env.ssl.ca_path
-
332
ssl_options[:cert_store] = env.ssl.cert_store if env.ssl.cert_store
-
332
ssl_options[:cert] = env.ssl.client_cert if env.ssl.client_cert
-
332
ssl_options[:key] = env.ssl.client_key if env.ssl.client_key
-
332
ssl_options[:ssl_version] = env.ssl.version if env.ssl.version
-
332
ssl_options[:verify_depth] = env.ssl.verify_depth if env.ssl.verify_depth
-
332
ssl_options[:min_version] = env.ssl.min_version if env.ssl.min_version
-
332
ssl_options[:max_version] = env.ssl.max_version if env.ssl.max_version
-
332
ssl_options
-
end
-
else
-
skipped
# :nocov:
-
skipped
def ssl_options_from_env(*)
-
skipped
{}
-
skipped
end
-
skipped
# :nocov:
-
end
-
end
-
-
7
include RequestMixin
-
-
7
module OnDataPlugin
-
7
module RequestMethods
-
7
attr_writer :response_on_data
-
-
7
def response=(response)
-
12
super
-
-
12
return if response.is_a?(::HTTPX::ErrorResponse)
-
-
12
response.body.on_data = @response_on_data
-
end
-
end
-
-
7
module ResponseBodyMethods
-
7
attr_writer :on_data
-
-
7
def write(chunk)
-
35
return super unless @on_data
-
-
35
@on_data.call(chunk, chunk.bytesize)
-
end
-
end
-
end
-
-
7
module ReasonPlugin
-
7
def self.load_dependencies(*)
-
163
require "net/http/status"
-
end
-
-
7
module ResponseMethods
-
7
def reason
-
133
Net::HTTP::STATUS_CODES.fetch(@status)
-
end
-
end
-
end
-
-
7
class ParallelManager
-
7
class ResponseHandler < SimpleDelegator
-
7
attr_reader :env
-
-
7
def initialize(env)
-
24
@env = env
-
24
super
-
end
-
-
7
def on_response(&blk)
-
48
if blk
-
24
@on_response = ->(response) do
-
24
blk.call(response)
-
end
-
24
self
-
else
-
24
@on_response
-
end
-
end
-
-
7
def on_complete(&blk)
-
72
if blk
-
24
@on_complete = blk
-
24
self
-
else
-
48
@on_complete
-
end
-
end
-
end
-
-
7
include RequestMixin
-
-
7
def initialize(options)
-
24
@handlers = []
-
24
@connection_options = options
-
end
-
-
7
def enqueue(request)
-
24
handler = ResponseHandler.new(request)
-
24
@handlers << handler
-
24
handler
-
end
-
-
7
def run
-
24
return unless @handlers.last
-
-
18
env = @handlers.last.env
-
-
18
connect(env) do |session|
-
42
requests = @handlers.map { |handler| session.build_request(*build_request(handler.env)) }
-
-
18
if env.request.stream_response?
-
6
requests.each do |request|
-
6
request.response_on_data = env.request.on_data
-
end
-
end
-
-
18
responses = session.request(*requests)
-
18
Array(responses).each_with_index do |response, index|
-
24
handler = @handlers[index]
-
24
handler.on_response.call(response)
-
24
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
-
7
def connection(env)
-
18
conn = build_connection(env)
-
18
return conn unless block_given?
-
-
18
yield conn
-
end
-
-
7
private
-
-
# from Faraday::Adapter#request_timeout
-
7
def request_timeout(type, options)
-
126
key = Faraday::Adapter::TIMEOUT_KEYS[type]
-
126
options[key] || options[:timeout]
-
end
-
end
-
-
7
self.supports_parallel = true
-
-
7
class << self
-
7
def setup_parallel_manager(options = {})
-
24
ParallelManager.new(options)
-
end
-
end
-
-
7
def call(env)
-
169
super
-
169
if parallel?(env)
-
24
handler = env[:parallel_manager].enqueue(env)
-
24
handler.on_response do |response|
-
24
if response.is_a?(::HTTPX::Response)
-
18
save_response(env, response.status, response.body.to_s, response.headers, response.reason) do |response_headers|
-
18
response_headers.merge!(response.headers)
-
end
-
else
-
6
env[:error] = response.error
-
6
save_response(env, 0, "", {}, nil)
-
end
-
end
-
24
return handler
-
end
-
-
145
response = connect_and_request(env)
-
115
save_response(env, response.status, response.body.to_s, response.headers, response.reason) do |response_headers|
-
115
response_headers.merge!(response.headers)
-
end
-
115
@app.call(env)
-
end
-
-
7
private
-
-
7
def connect_and_request(env)
-
145
connect(env) do |session|
-
145
request = session.build_request(*build_request(env))
-
-
145
request.response_on_data = env.request.on_data if env.request.stream_response?
-
-
145
response = session.request(request)
-
# do not call #raise_for_status for HTTP 4xx or 5xx, as faraday has a middleware for that.
-
145
response.raise_for_status unless response.is_a?(::HTTPX::Response)
-
115
response
-
end
-
rescue ::HTTPX::TimeoutError => e
-
18
raise Faraday::TimeoutError, e
-
end
-
-
7
def parallel?(env)
-
169
env[:parallel_manager]
-
end
-
end
-
-
7
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)
-
64
sentry_span = start_sentry_span
-
-
64
return unless sentry_span
-
-
64
set_sentry_trace_header(request, sentry_span)
-
-
64
request.on(:response, &method(:finish_sentry_span).curry(3)[sentry_span, request])
-
end
-
-
5
def start_sentry_span
-
64
return unless ::Sentry.initialized? && (span = ::Sentry.get_current_scope.get_span)
-
64
return if span.sampled == false
-
-
64
span.start_child(op: "httpx.client", start_timestamp: ::Sentry.utc_now.to_f)
-
end
-
-
5
def set_sentry_trace_header(request, sentry_span)
-
64
return unless sentry_span
-
-
64
config = ::Sentry.configuration
-
64
url = request.uri.to_s
-
-
128
return unless config.propagate_traces && config.trace_propagation_targets.any? { |target| url.match?(target) }
-
-
64
trace = ::Sentry.get_current_client.generate_sentry_trace(sentry_span)
-
64
request.headers[::Sentry::SENTRY_TRACE_HEADER_NAME] = trace if trace
-
end
-
-
5
def finish_sentry_span(span, request, response)
-
66
return unless ::Sentry.initialized?
-
-
66
record_sentry_breadcrumb(request, response)
-
66
record_sentry_span(request, response, span)
-
end
-
-
5
def record_sentry_breadcrumb(req, res)
-
66
return unless ::Sentry.configuration.breadcrumbs_logger.include?(:http_logger)
-
-
66
request_info = extract_request_info(req)
-
-
66
data = if res.is_a?(HTTPX::ErrorResponse)
-
6
{ error: res.error.message, **request_info }
-
else
-
60
{ status: res.status, **request_info }
-
end
-
-
66
crumb = ::Sentry::Breadcrumb.new(
-
level: :info,
-
category: "httpx",
-
type: :info,
-
data: data
-
)
-
66
::Sentry.add_breadcrumb(crumb)
-
end
-
-
5
def record_sentry_span(req, res, sentry_span)
-
66
return unless sentry_span
-
-
66
request_info = extract_request_info(req)
-
66
sentry_span.set_description("#{request_info[:method]} #{request_info[:url]}")
-
66
if res.is_a?(HTTPX::ErrorResponse)
-
6
sentry_span.set_data(:error, res.error.message)
-
else
-
60
sentry_span.set_data(:status, res.status)
-
end
-
66
sentry_span.set_timestamp(::Sentry.utc_now.to_f)
-
end
-
-
5
def extract_request_info(req)
-
132
uri = req.uri
-
-
result = {
-
132
method: req.verb,
-
}
-
-
132
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
-
-
132
result[:url] = uri.to_s
-
-
132
result
-
end
-
end
-
-
5
module RequestMethods
-
5
def __sentry_enable_trace!
-
66
return if @__sentry_enable_trace
-
-
64
Tracer.call(self)
-
64
@__sentry_enable_trace = true
-
end
-
end
-
-
5
module ConnectionMethods
-
5
def send(request)
-
66
request.__sentry_enable_trace!
-
-
66
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
private
-
-
7
def do_init_connection(connection, selector)
-
142
super
-
-
142
connection.once(:unmock_connection) do
-
20
unless connection.addresses
-
20
connection.__send__(:callbacks)[:connect_error].clear
-
20
deselect_connection(connection, selector)
-
end
-
20
resolve_connection(connection, selector)
-
end
-
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(*)
-
142
super
-
142
@mocked = true
-
end
-
-
7
def open?
-
162
return true if @mocked
-
-
20
super
-
end
-
-
7
def interests
-
230
return if @mocked
-
-
205
super
-
end
-
-
7
def terminate
-
121
force_reset
-
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
-
-
23
require "strscan"
-
-
23
module HTTPX
-
23
module AltSvc
-
# makes connections able to accept requests destined to primary service.
-
23
module ConnectionMixin
-
23
using URIExtensions
-
-
23
def send(request)
-
6
request.headers["alt-used"] = @origin.authority if @parser && !@write_buffer.full? && match_altsvcs?(request.uri)
-
-
6
super
-
end
-
-
23
def match?(uri, options)
-
6
return false if !used? && (@state == :closing || @state == :closed)
-
-
6
match_altsvcs?(uri) && match_altsvc_options?(uri, options)
-
end
-
-
23
private
-
-
# checks if this is connection is an alternative service of
-
# +uri+
-
23
def match_altsvcs?(uri)
-
18
@origins.any? { |origin| altsvc_match?(uri, origin) } ||
-
AltSvc.cached_altsvc(@origin).any? do |altsvc|
-
origin = altsvc["origin"]
-
altsvc_match?(origin, uri.origin)
-
end
-
end
-
-
23
def match_altsvc_options?(uri, options)
-
6
return @options == options unless @options.ssl.all? do |k, v|
-
6
v == (k == :hostname ? uri.host : options.ssl[k])
-
end
-
-
6
@options.options_equals?(options, Options::REQUEST_BODY_IVARS + %i[@ssl])
-
end
-
-
23
def altsvc_match?(uri, other_uri)
-
12
other_uri = URI(other_uri)
-
-
12
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
-
6
false
-
end
-
end
-
end
-
end
-
-
23
@altsvc_mutex = Thread::Mutex.new
-
41
@altsvcs = Hash.new { |h, k| h[k] = [] }
-
-
23
module_function
-
-
23
def cached_altsvc(origin)
-
30
now = Utils.now
-
30
@altsvc_mutex.synchronize do
-
30
lookup(origin, now)
-
end
-
end
-
-
23
def cached_altsvc_set(origin, entry)
-
18
now = Utils.now
-
18
@altsvc_mutex.synchronize do
-
18
return if @altsvcs[origin].any? { |altsvc| altsvc["origin"] == entry["origin"] }
-
-
18
entry["TTL"] = Integer(entry["ma"]) + now if entry.key?("ma")
-
18
@altsvcs[origin] << entry
-
18
entry
-
end
-
end
-
-
23
def lookup(origin, ttl)
-
30
return [] unless @altsvcs.key?(origin)
-
-
24
@altsvcs[origin] = @altsvcs[origin].select do |entry|
-
18
!entry.key?("TTL") || entry["TTL"] > ttl
-
end
-
36
@altsvcs[origin].reject { |entry| entry["noop"] }
-
end
-
-
23
def emit(request, response)
-
5839
return unless response.respond_to?(:headers)
-
# Alt-Svc
-
5818
return unless response.headers.key?("alt-svc")
-
-
63
origin = request.origin
-
63
host = request.uri.host
-
-
63
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).
-
63
if altsvc == "clear"
-
6
@altsvc_mutex.synchronize do
-
6
@altsvcs[origin].clear
-
end
-
-
6
return
-
end
-
-
57
parse(altsvc) do |alt_origin, alt_params|
-
6
alt_origin.host ||= host
-
6
yield(alt_origin, origin, alt_params)
-
end
-
end
-
-
23
def parse(altsvc)
-
141
return enum_for(__method__, altsvc) unless block_given?
-
-
99
scanner = StringScanner.new(altsvc)
-
99
until scanner.eos?
-
99
alt_service = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
-
-
99
alt_params = []
-
99
loop do
-
117
alt_param = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
-
117
alt_params << alt_param.strip if alt_param
-
117
scanner.skip(/;/)
-
117
break if scanner.eos? || scanner.scan(/ *, */)
-
end
-
198
alt_params = Hash[alt_params.map { |field| field.split("=", 2) }]
-
-
99
alt_proto, alt_authority = alt_service.split("=", 2)
-
99
alt_origin = parse_altsvc_origin(alt_proto, alt_authority)
-
99
return unless alt_origin
-
-
36
yield(alt_origin, alt_params.merge("proto" => alt_proto))
-
end
-
end
-
-
23
def parse_altsvc_scheme(alt_proto)
-
117
case alt_proto
-
when "h2c"
-
6
"http"
-
when "h2"
-
42
"https"
-
end
-
end
-
-
23
def parse_altsvc_origin(alt_proto, alt_origin)
-
99
alt_scheme = parse_altsvc_scheme(alt_proto)
-
-
99
return unless alt_scheme
-
-
36
alt_origin = alt_origin[1..-2] if alt_origin.start_with?("\"") && alt_origin.end_with?("\"")
-
-
36
URI.parse("#{alt_scheme}://#{alt_origin}")
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
-
23
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
-
#
-
23
class Buffer
-
23
extend Forwardable
-
-
23
def_delegator :@buffer, :<<
-
-
23
def_delegator :@buffer, :to_s
-
-
23
def_delegator :@buffer, :to_str
-
-
23
def_delegator :@buffer, :empty?
-
-
23
def_delegator :@buffer, :bytesize
-
-
23
def_delegator :@buffer, :clear
-
-
23
def_delegator :@buffer, :replace
-
-
23
attr_reader :limit
-
-
23
def initialize(limit)
-
15532
@buffer = "".b
-
15532
@limit = limit
-
end
-
-
23
def full?
-
3413790
@buffer.bytesize >= @limit
-
end
-
-
23
def capacity
-
10
@limit - @buffer.bytesize
-
end
-
-
23
def shift!(fin)
-
15602
@buffer = @buffer.byteslice(fin..-1) || "".b
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Callbacks
-
23
def on(type, &action)
-
210662
callbacks(type) << action
-
210662
self
-
end
-
-
23
def once(type, &block)
-
84090
on(type) do |*args, &callback|
-
83153
block.call(*args, &callback)
-
83105
:delete
-
end
-
84090
self
-
end
-
-
23
def emit(type, *args)
-
219953
callbacks(type).delete_if { |pr| :delete == pr.call(*args) } # rubocop:disable Style/YodaCondition
-
end
-
-
23
def callbacks_for?(type)
-
2322
@callbacks.key?(type) && @callbacks[type].any?
-
end
-
-
23
protected
-
-
23
def callbacks(type = nil)
-
310578
return @callbacks unless type
-
-
488303
@callbacks ||= Hash.new { |h, k| h[k] = [] }
-
310492
@callbacks[type]
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
# Session mixin, implements most of the APIs that the users call.
-
# delegates to a default session when extended.
-
23
module Chainable
-
23
%w[head get post put delete trace options connect patch].each do |meth|
-
198
class_eval(<<-MOD, __FILE__, __LINE__ + 1)
-
def #{meth}(*uri, **options) # def get(*uri, **options)
-
9
request("#{meth.upcase}", uri, **options) # request("GET", uri, **options)
-
end # end
-
MOD
-
end
-
-
# delegates to the default session (see HTTPX::Session#request).
-
23
def request(*args, **options)
-
1876
branch(default_options).request(*args, **options)
-
end
-
-
23
def accept(type)
-
12
with(headers: { "accept" => String(type) })
-
end
-
-
# delegates to the default session (see HTTPX::Session#wrap).
-
23
def wrap(&blk)
-
67
branch(default_options).wrap(&blk)
-
end
-
-
# returns a new instance loaded with the +pl+ plugin and +options+.
-
23
def plugin(pl, options = nil, &blk)
-
3755
klass = is_a?(S) ? self.class : Session
-
3755
klass = Class.new(klass)
-
3755
klass.instance_variable_set(:@default_options, klass.default_options.merge(default_options))
-
3755
klass.plugin(pl, options, &blk).new
-
end
-
-
# returns a new instance loaded with +options+.
-
23
def with(options, &blk)
-
1952
branch(default_options.merge(options), &blk)
-
end
-
-
23
private
-
-
# returns default instance of HTTPX::Options.
-
23
def default_options
-
7692
@options || Session.default_options
-
end
-
-
# returns a default instance of HTTPX::Session.
-
23
def branch(options, &blk)
-
3883
return self.class.new(options, &blk) if is_a?(S)
-
-
2245
Session.new(options, &blk)
-
end
-
-
23
def method_missing(meth, *args, **options, &blk)
-
558
case meth
-
when /\Awith_(.+)/
-
-
551
option = Regexp.last_match(1)
-
-
551
return super unless option
-
-
551
with(option.to_sym => args.first || options)
-
when /\Aon_(.+)/
-
7
callback = Regexp.last_match(1)
-
-
6
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)
-
-
7
warn "DEPRECATION WARNING: calling `.#{meth}` on plain HTTPX sessions is deprecated. " \
-
"Use `HTTPX.plugin(:callbacks).#{meth}` instead."
-
-
7
plugin(:callbacks).__send__(meth, *args, **options, &blk)
-
else
-
super
-
end
-
end
-
-
23
def respond_to_missing?(meth, *)
-
42
case meth
-
when /\Awith_(.+)/
-
30
option = Regexp.last_match(1)
-
-
30
default_options.respond_to?(option) || super
-
when /\Aon_(.+)/
-
12
callback = Regexp.last_match(1)
-
-
10
%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
-
-
23
extend Chainable
-
end
-
# frozen_string_literal: true
-
-
23
require "resolv"
-
23
require "forwardable"
-
23
require "httpx/io"
-
23
require "httpx/buffer"
-
-
23
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.
-
#
-
23
class Connection
-
23
extend Forwardable
-
23
include Loggable
-
23
include Callbacks
-
-
23
using URIExtensions
-
-
23
require "httpx/connection/http2"
-
23
require "httpx/connection/http1"
-
-
23
def_delegator :@io, :closed?
-
-
23
def_delegator :@write_buffer, :empty?
-
-
23
attr_reader :type, :io, :origin, :origins, :state, :pending, :options, :ssl_session
-
-
23
attr_writer :current_selector, :coalesced_connection
-
-
23
attr_accessor :current_session, :family
-
-
23
def initialize(uri, options)
-
5281
@current_session = @current_selector = @coalesced_connection = nil
-
5281
@exhausted = @cloned = false
-
-
5281
@options = Options.new(options)
-
5281
@type = initialize_type(uri, @options)
-
5281
@origins = [uri.origin]
-
5281
@origin = Utils.to_uri(uri.origin)
-
5281
@window_size = @options.window_size
-
5281
@read_buffer = Buffer.new(@options.buffer_size)
-
5281
@write_buffer = Buffer.new(@options.buffer_size)
-
5281
@pending = []
-
-
5281
on(:error, &method(:on_error))
-
5281
if @options.io
-
# if there's an already open IO, get its
-
# peer address, and force-initiate the parser
-
50
transition(:already_open)
-
50
@io = build_socket
-
50
parser
-
else
-
5231
transition(:idle)
-
end
-
5281
on(:activate) do
-
119
@current_session.select_connection(self, @current_selector)
-
end
-
5281
on(:close) do
-
5540
next if @exhausted # it'll reset
-
-
# may be called after ":close" above, so after the connection has been checked back in.
-
# next unless @current_session
-
-
5534
next unless @current_session
-
-
5534
@current_session.deselect_connection(self, @current_selector, @cloned)
-
end
-
5281
on(:terminate) do
-
1939
next if @exhausted # it'll reset
-
-
# may be called after ":close" above, so after the connection has been checked back in.
-
1933
next unless @current_session
-
-
12
@current_session.deselect_connection(self, @current_selector)
-
end
-
-
5281
on(:altsvc) do |alt_origin, origin, alt_params|
-
6
build_altsvc_connection(alt_origin, origin, alt_params)
-
end
-
-
5281
@inflight = 0
-
5281
@keep_alive_timeout = @options.timeout[:keep_alive_timeout]
-
-
5281
@intervals = []
-
-
5281
self.addresses = @options.addresses if @options.addresses
-
end
-
-
23
def peer
-
11287
@origin
-
end
-
-
# this is a semi-private method, to be used by the resolver
-
# to initiate the io object.
-
23
def addresses=(addrs)
-
5084
if @io
-
166
@io.add_addresses(addrs)
-
else
-
4918
@io = build_socket(addrs)
-
end
-
end
-
-
23
def addresses
-
10545
@io && @io.addresses
-
end
-
-
23
def match?(uri, options)
-
1675
return false if !used? && (@state == :closing || @state == :closed)
-
-
146
(
-
1427
@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
-
1506
(@origins.size == 1 || @origin == uri.origin || (@io.is_a?(SSL) && @io.verify_hostname(uri.host)))
-
) && @options == options
-
end
-
-
23
def expired?
-
return false unless @io
-
-
@io.expired?
-
end
-
-
23
def mergeable?(connection)
-
243
return false if @state == :closing || @state == :closed || !@io
-
-
53
return false unless connection.addresses
-
-
(
-
53
(open? && @origin == connection.origin) ||
-
53
!(@io.addresses & (connection.addresses || [])).empty?
-
) && @options == connection.options
-
end
-
-
# coalescable connections need to be mergeable!
-
# but internally, #mergeable? is called before #coalescable?
-
23
def coalescable?(connection)
-
23
if @io.protocol == "h2" &&
-
@origin.scheme == "https" &&
-
connection.origin.scheme == "https" &&
-
@io.can_verify_peer?
-
11
@io.verify_hostname(connection.origin.host)
-
else
-
12
@origin == connection.origin
-
end
-
end
-
-
23
def create_idle(options = {})
-
self.class.new(@origin, @options.merge(options))
-
end
-
-
23
def merge(connection)
-
23
@origins |= connection.instance_variable_get(:@origins)
-
23
if connection.ssl_session
-
5
@ssl_session = connection.ssl_session
-
@io.session_new_cb do |sess|
-
10
@ssl_session = sess
-
5
end if @io
-
end
-
23
connection.purge_pending do |req|
-
6
send(req)
-
end
-
end
-
-
23
def purge_pending(&block)
-
23
pendings = []
-
23
if @parser
-
12
@inflight -= @parser.pending.size
-
12
pendings << @parser.pending
-
end
-
23
pendings << @pending
-
23
pendings.each do |pending|
-
35
pending.reject!(&block)
-
end
-
end
-
-
23
def connecting?
-
3437236
@state == :idle
-
end
-
-
23
def inflight?
-
2051
@parser && (
-
# parser may be dealing with other requests (possibly started from a different fiber)
-
1632
!@parser.empty? ||
-
# connection may be doing connection termination handshake
-
!@write_buffer.empty?
-
)
-
end
-
-
23
def interests
-
# connecting
-
3428984
if connecting?
-
8021
connect
-
-
8021
return @io.interests if connecting?
-
end
-
-
# if the write buffer is full, we drain it
-
3421423
return :w unless @write_buffer.empty?
-
-
3391835
return @parser.interests if @parser
-
-
5
nil
-
rescue StandardError => e
-
emit(:error, e)
-
nil
-
end
-
-
23
def to_io
-
16237
@io.to_io
-
end
-
-
23
def call
-
15721
case @state
-
when :idle
-
7442
connect
-
7430
consume
-
when :closed
-
return
-
when :closing
-
consume
-
transition(:closed)
-
when :open
-
8121
consume
-
end
-
1995
nil
-
rescue StandardError => e
-
17
emit(:error, e)
-
17
raise e
-
end
-
-
23
def close
-
1917
transition(:active) if @state == :inactive
-
-
1917
@parser.close if @parser
-
end
-
-
23
def terminate
-
1917
@connected_at = nil if @state == :closed
-
-
1917
close
-
end
-
-
# bypasses the state machine to force closing of connections still connecting.
-
# **only** used for Happy Eyeballs v2.
-
23
def force_reset(cloned = false)
-
232
@state = :closing
-
232
@cloned = cloned
-
232
transition(:closed)
-
end
-
-
23
def reset
-
5459
return if @state == :closing || @state == :closed
-
-
5422
transition(:closing)
-
-
5422
transition(:closed)
-
end
-
-
23
def send(request)
-
6565
return @coalesced_connection.send(request) if @coalesced_connection
-
-
6560
if @parser && !@write_buffer.full?
-
311
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.
-
6
log(level: 3) { "keep alive timeout expired, pinging connection..." }
-
6
@pending << request
-
6
transition(:active) if @state == :inactive
-
6
parser.ping
-
6
return
-
end
-
-
305
send_request_to_parser(request)
-
else
-
6249
@pending << request
-
end
-
end
-
-
23
def timeout
-
3339581
return if @state == :closed || @state == :inactive
-
-
3339581
return @timeout if @timeout
-
-
3330689
return @options.timeout[:connect_timeout] if @state == :idle
-
-
3330689
@options.timeout[:operation_timeout]
-
end
-
-
23
def idling
-
614
purge_after_closed
-
614
@write_buffer.clear
-
614
transition(:idle)
-
614
@parser = nil if @parser
-
end
-
-
23
def used?
-
1821
@connected_at
-
end
-
-
23
def deactivate
-
255
transition(:inactive)
-
end
-
-
23
def open?
-
5158
@state == :open || @state == :inactive
-
end
-
-
23
def handle_socket_timeout(interval)
-
334
@intervals.delete_if(&:elapsed?)
-
-
334
unless @intervals.empty?
-
# remove the intervals which will elapse
-
-
310
return
-
end
-
-
24
error = HTTPX::TimeoutError.new(interval, "timed out while waiting on select")
-
24
error.set_backtrace(caller)
-
24
on_error(error)
-
end
-
-
23
private
-
-
23
def connect
-
14696
transition(:open)
-
end
-
-
23
def disconnect
-
5540
emit(:close)
-
5528
@current_session = nil
-
5528
@current_selector = nil
-
end
-
-
23
def consume
-
17746
return unless @io
-
-
17746
catch(:called) do
-
17746
epiped = false
-
17746
loop do
-
# connection may have
-
32205
return if @state == :idle
-
-
29971
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)
-
29959
if @pending.empty? && @inflight.zero? && @write_buffer.empty?
-
1992
log(level: 3) { "NO MORE REQUESTS..." }
-
1980
return
-
end
-
-
27979
@timeout = @current_timeout
-
-
27979
read_drained = false
-
27979
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.
-
#
-
loop do
-
36184
siz = @io.read(@window_size, @read_buffer)
-
36272
log(level: 3, color: :cyan) { "IO READ: #{siz} bytes... (wsize: #{@window_size}, rbuffer: #{@read_buffer.bytesize})" }
-
36184
unless siz
-
14
ex = EOFError.new("descriptor closed")
-
14
ex.set_backtrace(caller)
-
14
on_error(ex)
-
14
return
-
end
-
-
# socket has been drained. mark and exit the read loop.
-
36170
if siz.zero?
-
7490
read_drained = @read_buffer.empty?
-
7490
epiped = false
-
7490
break
-
end
-
-
28680
parser << @read_buffer.to_s
-
-
# continue reading if possible.
-
25482
break if interests == :w && !epiped
-
-
# exit the read loop if connection is preparing to be closed
-
20133
break if @state == :closing || @state == :closed
-
-
# exit #consume altogether if all outstanding requests have been dealt with
-
20128
return if @pending.empty? && @inflight.zero?
-
27979
end unless ((ints = interests).nil? || ints == :w || @state == :closing) && !epiped
-
-
#
-
# tight write loop.
-
#
-
# flush as many bytes as the sockets allow.
-
#
-
loop do
-
# buffer has been drainned, mark and exit the write loop.
-
17257
if @write_buffer.empty?
-
# we only mark as drained on the first loop
-
2167
write_drained = write_drained.nil? && @inflight.positive?
-
-
2167
break
-
end
-
-
1936
begin
-
15090
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.
-
21
log(level: 2) { "pipe broken, could not flush buffer..." }
-
21
epiped = true
-
21
read_drained = false
-
21
break
-
end
-
15127
log(level: 3, color: :cyan) { "IO WRITE: #{siz} bytes..." }
-
15062
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.
-
15062
if siz.zero?
-
18
write_drained = !@write_buffer.empty?
-
18
break
-
end
-
-
# exit write loop if marked to consume from peer, or is closing.
-
15044
break if interests == :r || @state == :closing || @state == :closed
-
-
2136
write_drained = false
-
22604
end unless (ints = interests) == :r
-
-
22597
send_pending if @state == :open
-
-
# return if socket is drained
-
22597
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;
-
8166
log(level: 3) { "(#{ints}): WAITING FOR EVENTS..." }
-
8138
return
-
end
-
end
-
end
-
-
23
def send_pending
-
63304
while !@write_buffer.full? && (request = @pending.shift)
-
16481
send_request_to_parser(request)
-
end
-
end
-
-
23
def parser
-
81635
@parser ||= build_parser
-
end
-
-
23
def send_request_to_parser(request)
-
16786
@inflight += 1
-
16786
request.peer_address = @io.ip
-
16786
parser.send(request)
-
-
16786
set_request_timeouts(request)
-
-
16786
return unless @state == :inactive
-
-
5
transition(:active)
-
end
-
-
23
def build_parser(protocol = @io.protocol)
-
5325
parser = self.class.parser_type(protocol).new(@write_buffer, @options)
-
5325
set_parser_callbacks(parser)
-
5325
parser
-
end
-
-
23
def set_parser_callbacks(parser)
-
5409
parser.on(:response) do |request, response|
-
5833
AltSvc.emit(request, response) do |alt_origin, origin, alt_params|
-
6
emit(:altsvc, alt_origin, origin, alt_params)
-
end
-
5833
@response_received_at = Utils.now
-
5833
@inflight -= 1
-
5833
request.emit(:response, response)
-
end
-
5409
parser.on(:altsvc) do |alt_origin, origin, alt_params|
-
emit(:altsvc, alt_origin, origin, alt_params)
-
end
-
-
5409
parser.on(:pong, &method(:send_pending))
-
-
5409
parser.on(:promise) do |request, stream|
-
18
request.emit(:promise, parser, stream)
-
end
-
5409
parser.on(:exhausted) do
-
6
@exhausted = true
-
6
current_session = @current_session
-
6
current_selector = @current_selector
-
6
parser.close
-
6
@pending.concat(parser.pending)
-
6
case @state
-
when :closed
-
6
idling
-
6
@exhausted = false
-
6
@current_session = current_session
-
6
@current_selector = current_selector
-
when :closing
-
once(:close) do
-
idling
-
@exhausted = false
-
@current_session = current_session
-
@current_selector = current_selector
-
end
-
end
-
end
-
5409
parser.on(:origin) do |origin|
-
@origins |= [origin]
-
end
-
5409
parser.on(:close) do |force|
-
1939
if force
-
1939
reset
-
1933
emit(:terminate)
-
end
-
end
-
5409
parser.on(:close_handshake) do
-
6
consume
-
end
-
5409
parser.on(:reset) do
-
2915
@pending.concat(parser.pending) unless parser.empty?
-
2915
current_session = @current_session
-
2915
current_selector = @current_selector
-
2915
reset
-
2909
unless @pending.empty?
-
154
idling
-
154
@current_session = current_session
-
154
@current_selector = current_selector
-
end
-
end
-
5409
parser.on(:current_timeout) do
-
2241
@current_timeout = @timeout = parser.timeout
-
end
-
5409
parser.on(:timeout) do |tout|
-
1904
@timeout = tout
-
end
-
5409
parser.on(:error) do |request, ex|
-
42
case ex
-
when MisdirectedRequestError
-
6
current_session = @current_session
-
6
current_selector = @current_selector
-
6
parser.close
-
-
6
other_connection = current_session.find_connection(@origin, current_selector,
-
@options.merge(ssl: { alpn_protocols: %w[http/1.1] }))
-
6
other_connection.merge(self)
-
6
request.transition(:idle)
-
6
other_connection.send(request)
-
else
-
36
response = ErrorResponse.new(request, ex)
-
36
request.response = response
-
36
request.emit(:response, response)
-
end
-
end
-
end
-
-
23
def transition(nextstate)
-
33116
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
-
59
error = ConnectionError.new(e.message)
-
59
error.set_backtrace(e.backtrace)
-
59
connecting? && callbacks_for?(:connect_error) ? emit(:connect_error, error) : handle_error(error)
-
59
@state = :closed
-
59
disconnect
-
rescue TLSError, ::HTTP2::Error::ProtocolError, ::HTTP2::Error::HandshakeError => e
-
# connect errors, exit gracefully
-
19
handle_error(e)
-
19
connecting? && callbacks_for?(:connect_error) ? emit(:connect_error, e) : handle_error(e)
-
19
@state = :closed
-
19
disconnect
-
end
-
-
23
def handle_transition(nextstate)
-
32736
case nextstate
-
when :idle
-
5857
@timeout = @current_timeout = @options.timeout[:connect_timeout]
-
-
5857
@connected_at = nil
-
when :open
-
14925
return if @state == :closed
-
-
14925
@io.connect
-
14848
emit(:tcp_open, self) if @io.state == :connected
-
-
14848
return unless @io.connected?
-
-
5330
@connected_at = Utils.now
-
-
5330
send_pending
-
-
5330
@timeout = @current_timeout = parser.timeout
-
5330
emit(:open)
-
when :inactive
-
255
return unless @state == :open
-
-
# do not deactivate connection in use
-
254
return if @inflight.positive?
-
when :closing
-
5428
return unless @state == :idle || @state == :open
-
-
5428
unless @write_buffer.empty?
-
# preset state before handshake, as error callbacks
-
# may take it back here.
-
1929
@state = nextstate
-
# handshakes, try sending
-
1929
consume
-
1928
@write_buffer.clear
-
1928
return
-
end
-
when :closed
-
5660
return unless @state == :closing
-
5659
return unless @write_buffer.empty?
-
-
5640
purge_after_closed
-
5640
disconnect if @pending.empty?
-
when :already_open
-
50
nextstate = :open
-
# the first check for given io readiness must still use a timeout.
-
# connect is the reasonable choice in such a case.
-
50
@timeout = @options.timeout[:connect_timeout]
-
50
send_pending
-
when :active
-
119
return unless @state == :inactive
-
-
119
nextstate = :open
-
119
emit(:activate)
-
end
-
21162
@state = nextstate
-
end
-
-
23
def purge_after_closed
-
6260
@io.close if @io
-
6260
@read_buffer.clear
-
6260
@timeout = nil
-
end
-
-
23
def initialize_type(uri, options)
-
5004
options.transport || begin
-
4984
case uri.scheme
-
when "http"
-
2871
"tcp"
-
when "https"
-
2113
"ssl"
-
else
-
raise UnsupportedSchemeError, "#{uri}: #{uri.scheme}: unsupported URI scheme"
-
end
-
end
-
end
-
-
# returns an HTTPX::Connection for the negotiated Alternative Service (or none).
-
23
def build_altsvc_connection(alt_origin, origin, alt_params)
-
# do not allow security downgrades on altsvc negotiation
-
6
return if @origin.scheme == "https" && alt_origin.scheme != "https"
-
-
6
altsvc = AltSvc.cached_altsvc_set(origin, alt_params.merge("origin" => alt_origin))
-
-
# altsvc already exists, somehow it wasn't advertised, probably noop
-
6
return unless altsvc
-
-
6
alt_options = @options.merge(ssl: @options.ssl.merge(hostname: URI(origin).host))
-
-
6
connection = @current_session.find_connection(alt_origin, @current_selector, alt_options)
-
-
# advertised altsvc is the same origin being used, ignore
-
6
return if connection == self
-
-
6
connection.extend(AltSvc::ConnectionMixin) unless connection.is_a?(AltSvc::ConnectionMixin)
-
-
6
log(level: 1) { "#{origin} alt-svc: #{alt_origin}" }
-
-
6
connection.merge(self)
-
6
terminate
-
rescue UnsupportedSchemeError
-
altsvc["noop"] = true
-
nil
-
end
-
-
23
def build_socket(addrs = nil)
-
4968
case @type
-
when "tcp"
-
2916
TCP.new(peer, addrs, @options)
-
when "ssl"
-
2032
SSL.new(peer, addrs, @options) do |sock|
-
2015
sock.ssl_session = @ssl_session
-
2015
sock.session_new_cb do |sess|
-
3382
@ssl_session = sess
-
-
3382
sock.ssl_session = sess
-
end
-
end
-
when "unix"
-
20
path = Array(addrs).first
-
-
20
path = String(path) if path
-
-
20
UNIX.new(peer, path, @options)
-
else
-
raise Error, "unsupported transport (#{@type})"
-
end
-
end
-
-
23
def on_error(error, request = nil)
-
587
if error.instance_of?(TimeoutError)
-
-
# inactive connections do not contribute to the select loop, therefore
-
# they should not fail due to such errors.
-
24
return if @state == :inactive
-
-
24
if @timeout
-
24
@timeout -= error.timeout
-
24
return unless @timeout <= 0
-
end
-
-
24
error = error.to_connection_error if connecting?
-
end
-
587
handle_error(error, request)
-
587
reset
-
end
-
-
23
def handle_error(error, request = nil)
-
684
parser.handle_error(error, request) if @parser && parser.respond_to?(:handle_error)
-
1559
while (req = @pending.shift)
-
320
next if request && req == request
-
-
320
response = ErrorResponse.new(req, error)
-
320
req.response = response
-
320
req.emit(:response, response)
-
end
-
-
684
return unless request
-
-
307
response = ErrorResponse.new(request, error)
-
307
request.response = response
-
307
request.emit(:response, response)
-
end
-
-
23
def set_request_timeouts(request)
-
16786
set_request_write_timeout(request)
-
16786
set_request_read_timeout(request)
-
16786
set_request_request_timeout(request)
-
end
-
-
23
def set_request_read_timeout(request)
-
16786
read_timeout = request.read_timeout
-
-
16786
return if read_timeout.nil? || read_timeout.infinite?
-
-
16561
set_request_timeout(request, read_timeout, :done, :response) do
-
18
read_timeout_callback(request, read_timeout)
-
end
-
end
-
-
23
def set_request_write_timeout(request)
-
16786
write_timeout = request.write_timeout
-
-
16786
return if write_timeout.nil? || write_timeout.infinite?
-
-
16786
set_request_timeout(request, write_timeout, :headers, %i[done response]) do
-
18
write_timeout_callback(request, write_timeout)
-
end
-
end
-
-
23
def set_request_request_timeout(request)
-
16572
request_timeout = request.request_timeout
-
-
16572
return if request_timeout.nil? || request_timeout.infinite?
-
-
384
set_request_timeout(request, request_timeout, :headers, :complete) do
-
271
read_timeout_callback(request, request_timeout, RequestTimeoutError)
-
end
-
end
-
-
23
def write_timeout_callback(request, write_timeout)
-
18
return if request.state == :done
-
-
18
@write_buffer.clear
-
18
error = WriteTimeoutError.new(request, nil, write_timeout)
-
-
18
on_error(error, request)
-
end
-
-
23
def read_timeout_callback(request, read_timeout, error_type = ReadTimeoutError)
-
289
response = request.response
-
-
289
return if response && response.finished?
-
-
289
@write_buffer.clear
-
289
error = error_type.new(request, request.response, read_timeout)
-
-
289
on_error(error, request)
-
end
-
-
23
def set_request_timeout(request, timeout, start_event, finish_events, &callback)
-
33791
request.once(start_event) do
-
33237
interval = @current_selector.after(timeout, callback)
-
-
33237
Array(finish_events).each do |event|
-
# clean up request timeouts if the connection errors out
-
49821
request.once(event) do
-
49707
if @intervals.include?(interval)
-
49288
interval.delete(callback)
-
49288
@intervals.delete(interval) if interval.no_callbacks?
-
end
-
end
-
end
-
-
33237
@intervals << interval
-
end
-
end
-
-
23
class << self
-
23
def parser_type(protocol)
-
5435
case protocol
-
2246
when "h2" then HTTP2
-
3189
when "http/1.1" then HTTP1
-
else
-
raise Error, "unsupported protocol (##{protocol})"
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "httpx/parser/http1"
-
-
23
module HTTPX
-
23
class Connection::HTTP1
-
23
include Callbacks
-
23
include Loggable
-
-
23
MAX_REQUESTS = 200
-
23
CRLF = "\r\n"
-
-
23
attr_reader :pending, :requests
-
-
23
attr_accessor :max_concurrent_requests
-
-
23
def initialize(buffer, options)
-
3189
@options = options
-
3189
@max_concurrent_requests = @options.max_concurrent_requests || MAX_REQUESTS
-
3189
@max_requests = @options.max_requests
-
3189
@parser = Parser::HTTP1.new(self)
-
3189
@buffer = buffer
-
3189
@version = [1, 1]
-
3189
@pending = []
-
3189
@requests = []
-
3189
@handshake_completed = false
-
end
-
-
23
def timeout
-
3100
@options.timeout[:operation_timeout]
-
end
-
-
23
def interests
-
# this means we're processing incoming response already
-
23823
return :r if @request
-
-
19741
return if @requests.empty?
-
-
19723
request = @requests.first
-
-
19723
return unless request
-
-
19723
return :w if request.interests == :w || !@buffer.empty?
-
-
17173
:r
-
end
-
-
23
def reset
-
3014
@max_requests = @options.max_requests || MAX_REQUESTS
-
3014
@parser.reset!
-
3014
@handshake_completed = false
-
3014
@pending.concat(@requests) unless @requests.empty?
-
end
-
-
23
def close
-
63
reset
-
63
emit(:close, true)
-
end
-
-
23
def exhausted?
-
515
!@max_requests.positive?
-
end
-
-
23
def empty?
-
# this means that for every request there's an available
-
# partial response, so there are no in-flight requests waiting.
-
2952
@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.
-
157
!@requests.first.response.nil? &&
-
(@requests.size == 1 || !@requests.last.response.nil?)
-
)
-
end
-
-
23
def <<(data)
-
5380
@parser << data
-
end
-
-
23
def send(request)
-
14249
unless @max_requests.positive?
-
@pending << request
-
return
-
end
-
-
14249
return if @requests.include?(request)
-
-
14249
@requests << request
-
14249
@pipelining = true if @requests.size > 1
-
end
-
-
23
def consume
-
12262
requests_limit = [@max_requests, @requests.size].min
-
12262
concurrent_requests_limit = [@max_concurrent_requests, requests_limit].min
-
12262
@requests.each_with_index do |request, idx|
-
14740
break if idx >= concurrent_requests_limit
-
12212
next if request.state == :done
-
-
4577
handle(request)
-
end
-
end
-
-
# HTTP Parser callbacks
-
#
-
# must be public methods, or else they won't be reachable
-
-
23
def on_start
-
3594
log(level: 2) { "parsing begins" }
-
end
-
-
23
def on_headers(h)
-
3576
@request = @requests.first
-
-
3576
return if @request.response
-
-
3594
log(level: 2) { "headers received" }
-
3576
headers = @request.options.headers_class.new(h)
-
3576
response = @request.options.response_class.new(@request,
-
@parser.status_code,
-
@parser.http_version.join("."),
-
headers)
-
3594
log(color: :yellow) { "-> HEADLINE: #{response.status} HTTP/#{@parser.http_version.join(".")}" }
-
3738
log(color: :yellow) { response.headers.each.map { |f, v| "-> HEADER: #{f}: #{v}" }.join("\n") }
-
-
3576
@request.response = response
-
3570
on_complete if response.finished?
-
end
-
-
23
def on_trailers(h)
-
6
return unless @request
-
-
6
response = @request.response
-
6
log(level: 2) { "trailer headers received" }
-
-
6
log(color: :yellow) { h.each.map { |f, v| "-> HEADER: #{f}: #{v.join(", ")}" }.join("\n") }
-
6
response.merge_headers(h)
-
end
-
-
23
def on_data(chunk)
-
4106
request = @request
-
-
4106
return unless request
-
-
4124
log(color: :green) { "-> DATA: #{chunk.bytesize} bytes..." }
-
4124
log(level: 2, color: :green) { "-> #{chunk.inspect}" }
-
4106
response = request.response
-
-
4106
response << chunk
-
rescue StandardError => e
-
11
error_response = ErrorResponse.new(request, e)
-
11
request.response = error_response
-
11
dispatch
-
end
-
-
23
def on_complete
-
3553
request = @request
-
-
3553
return unless request
-
-
3571
log(level: 2) { "parsing complete" }
-
3553
dispatch
-
end
-
-
23
def dispatch
-
3564
request = @request
-
-
3564
if request.expects?
-
54
@parser.reset!
-
54
return handle(request)
-
end
-
-
3510
@request = nil
-
3510
@requests.shift
-
3510
response = request.response
-
3510
response.finish! unless response.is_a?(ErrorResponse)
-
3510
emit(:response, request, response)
-
-
3466
if @parser.upgrade?
-
24
response << @parser.upgrade_data
-
24
throw(:called)
-
end
-
-
3442
@parser.reset!
-
3442
@max_requests -= 1
-
3442
if response.is_a?(ErrorResponse)
-
11
disable
-
else
-
3431
manage_connection(request, response)
-
end
-
-
515
if exhausted?
-
@pending.concat(@requests)
-
@requests.clear
-
-
emit(:exhausted)
-
else
-
515
send(@pending.shift) unless @pending.empty?
-
end
-
end
-
-
23
def handle_error(ex, request = nil)
-
165
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
-
12
catch(:called) { on_complete }
-
6
return
-
end
-
-
159
if @pipelining
-
catch(:called) { disable }
-
else
-
159
@requests.each do |req|
-
145
next if request && request == req
-
-
emit(:error, req, ex)
-
end
-
159
@pending.each do |req|
-
next if request && request == req
-
-
emit(:error, req, ex)
-
end
-
end
-
end
-
-
23
def ping
-
reset
-
emit(:reset)
-
emit(:exhausted)
-
end
-
-
23
private
-
-
23
def manage_connection(request, response)
-
3431
connection = response.headers["connection"]
-
3431
case connection
-
when /keep-alive/i
-
515
if @handshake_completed
-
if @max_requests.zero?
-
@pending.concat(@requests)
-
@requests.clear
-
emit(:exhausted)
-
end
-
return
-
end
-
-
515
keep_alive = response.headers["keep-alive"]
-
515
return unless keep_alive
-
-
106
parameters = Hash[keep_alive.split(/ *, */).map do |pair|
-
106
pair.split(/ *= */, 2)
-
end]
-
106
@max_requests = parameters["max"].to_i - 1 if parameters.key?("max")
-
-
106
if parameters.key?("timeout")
-
keep_alive_timeout = parameters["timeout"].to_i
-
emit(:timeout, keep_alive_timeout)
-
end
-
106
@handshake_completed = true
-
when /close/i
-
2916
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
-
-
23
def disable
-
2927
disable_pipelining
-
2927
reset
-
2927
emit(:reset)
-
2921
throw(:called)
-
end
-
-
23
def disable_pipelining
-
2927
return if @requests.empty?
-
# do not disable pipelining if already set to 1 request at a time
-
160
return if @max_concurrent_requests == 1
-
-
16
@requests.each do |r|
-
16
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.
-
16
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.
-
16
@max_concurrent_requests = 1
-
16
@pipelining = false
-
end
-
-
23
def set_protocol_headers(request)
-
3689
if !request.headers.key?("content-length") &&
-
request.body.bytesize == Float::INFINITY
-
24
request.body.chunk!
-
end
-
-
3689
extra_headers = {}
-
-
3689
unless request.headers.key?("connection")
-
3671
connection_value = if request.persistent?
-
# when in a persistent connection, the request can't be at
-
# the edge of a renegotiation
-
43
if @requests.index(request) + 1 < @max_requests
-
43
"keep-alive"
-
else
-
"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)
-
3628
requests_limit = [@max_requests, @requests.size].min
-
3628
if request == @requests[requests_limit - 1]
-
3086
"close"
-
else
-
542
"keep-alive"
-
end
-
end
-
-
3671
extra_headers["connection"] = connection_value
-
end
-
3689
extra_headers["host"] = request.authority unless request.headers.key?("host")
-
3689
extra_headers
-
end
-
-
23
def handle(request)
-
4631
catch(:buffer_full) do
-
4631
request.transition(:headers)
-
4625
join_headers(request) if request.state == :headers
-
4625
request.transition(:body)
-
4625
join_body(request) if request.state == :body
-
3823
request.transition(:trailers)
-
# HTTP/1.1 trailers should only work for chunked encoding
-
3823
join_trailers(request) if request.body.chunked? && request.state == :trailers
-
3823
request.transition(:done)
-
end
-
end
-
-
23
def join_headline(request)
-
3629
"#{request.verb} #{request.path} HTTP/#{@version.join(".")}"
-
end
-
-
23
def join_headers(request)
-
3689
headline = join_headline(request)
-
3689
@buffer << headline << CRLF
-
3707
log(color: :yellow) { "<- HEADLINE: #{headline.chomp.inspect}" }
-
3689
extra_headers = set_protocol_headers(request)
-
3689
join_headers2(request.headers.each(extra_headers))
-
3707
log { "<- " }
-
3689
@buffer << CRLF
-
end
-
-
23
def join_body(request)
-
4473
return if request.body.empty?
-
-
4918
while (chunk = request.drain_body)
-
2589
log(color: :green) { "<- DATA: #{chunk.bytesize} bytes..." }
-
2589
log(level: 2, color: :green) { "<- #{chunk.inspect}" }
-
2589
@buffer << chunk
-
2589
throw(:buffer_full, request) if @buffer.full?
-
end
-
-
1141
return unless (error = request.drain_error)
-
-
raise error
-
end
-
-
23
def join_trailers(request)
-
72
return unless request.trailers? && request.callbacks_for?(:trailers)
-
-
24
join_headers2(request.trailers)
-
24
log { "<- " }
-
24
@buffer << CRLF
-
end
-
-
23
def join_headers2(headers)
-
3713
headers.each do |field, value|
-
22116
buffer = "#{capitalized(field)}: #{value}#{CRLF}"
-
22206
log(color: :yellow) { "<- HEADER: #{buffer.chomp}" }
-
22116
@buffer << buffer
-
end
-
end
-
-
23
UPCASED = {
-
"www-authenticate" => "WWW-Authenticate",
-
"http2-settings" => "HTTP2-Settings",
-
"content-md5" => "Content-MD5",
-
}.freeze
-
-
23
def capitalized(field)
-
22116
UPCASED[field] || field.split("-").map(&:capitalize).join("-")
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "securerandom"
-
23
require "http/2"
-
-
23
module HTTPX
-
23
class Connection::HTTP2
-
23
include Callbacks
-
23
include Loggable
-
-
23
MAX_CONCURRENT_REQUESTS = ::HTTP2::DEFAULT_MAX_CONCURRENT_STREAMS
-
-
23
class Error < Error
-
23
def initialize(id, code)
-
26
super("stream #{id} closed with error: #{code}")
-
end
-
end
-
-
23
class GoawayError < Error
-
23
def initialize
-
11
super(0, :no_error)
-
end
-
end
-
-
23
attr_reader :streams, :pending
-
-
23
def initialize(buffer, options)
-
2264
@options = options
-
2264
@settings = @options.http2_settings
-
2264
@pending = []
-
2264
@streams = {}
-
2264
@drains = {}
-
2264
@pings = []
-
2264
@buffer = buffer
-
2264
@handshake_completed = false
-
2264
@wait_for_handshake = @settings.key?(:wait_for_handshake) ? @settings.delete(:wait_for_handshake) : true
-
2264
@max_concurrent_requests = @options.max_concurrent_requests || MAX_CONCURRENT_REQUESTS
-
2264
@max_requests = @options.max_requests
-
2264
init_connection
-
end
-
-
23
def timeout
-
4471
return @options.timeout[:operation_timeout] if @handshake_completed
-
-
2230
@options.timeout[:settings_timeout]
-
end
-
-
23
def interests
-
# waiting for WINDOW_UPDATE frames
-
3367952
return :r if @buffer.full?
-
-
3367952
if @connection.state == :closed
-
2047
return unless @handshake_completed
-
-
2019
return :w
-
end
-
-
3365905
unless @connection.state == :connected && @handshake_completed
-
9527
return @buffer.empty? ? :r : :rw
-
end
-
-
3356378
return :w if !@pending.empty? && can_buffer_more_requests?
-
-
3356378
return :w unless @drains.empty?
-
-
3355730
if @buffer.empty?
-
3355730
return if @streams.empty? && @pings.empty?
-
-
30042
return :r
-
end
-
-
:rw
-
end
-
-
23
def close
-
1904
unless @connection.state == :closed
-
1904
@connection.goaway
-
1904
emit(:timeout, @options.timeout[:close_handshake_timeout])
-
end
-
1904
emit(:close, true)
-
end
-
-
23
def empty?
-
1905
@connection.state == :closed || @streams.empty?
-
end
-
-
23
def exhausted?
-
2266
!@max_requests.positive?
-
end
-
-
23
def <<(data)
-
23072
@connection << data
-
end
-
-
23
def can_buffer_more_requests?
-
5306
(@handshake_completed || !@wait_for_handshake) &&
-
@streams.size < @max_concurrent_requests &&
-
@streams.size < @max_requests
-
end
-
-
23
def send(request, head = false)
-
4966
unless can_buffer_more_requests?
-
2409
head ? @pending.unshift(request) : @pending << request
-
2409
return false
-
end
-
2557
unless (stream = @streams[request])
-
2557
stream = @connection.new_stream
-
2557
handle_stream(stream, request)
-
2557
@streams[request] = stream
-
2557
@max_requests -= 1
-
end
-
2557
handle(request, stream)
-
2545
true
-
rescue ::HTTP2::Error::StreamLimitExceeded
-
@pending.unshift(request)
-
false
-
end
-
-
23
def consume
-
17119
@streams.each do |request, stream|
-
6549
next if request.state == :done
-
-
738
handle(request, stream)
-
end
-
end
-
-
23
def handle_error(ex, request = nil)
-
197
if ex.instance_of?(TimeoutError) && !@handshake_completed && @connection.state != :closed
-
6
@connection.goaway(:settings_timeout, "closing due to settings timeout")
-
6
emit(:close_handshake)
-
6
settings_ex = SettingsTimeoutError.new(ex.timeout, ex.message)
-
6
settings_ex.set_backtrace(ex.backtrace)
-
6
ex = settings_ex
-
end
-
197
@streams.each_key do |req|
-
161
next if request && request == req
-
-
11
emit(:error, req, ex)
-
end
-
197
@pending.each do |req|
-
25
next if request && request == req
-
-
25
emit(:error, req, ex)
-
end
-
end
-
-
23
def ping
-
6
ping = SecureRandom.gen_random(8)
-
6
@connection.ping(ping)
-
ensure
-
6
@pings << ping
-
end
-
-
23
private
-
-
23
def send_pending
-
6074
while (request = @pending.shift)
-
2318
break unless send(request, true)
-
end
-
end
-
-
23
def handle(request, stream)
-
3343
catch(:buffer_full) do
-
3343
request.transition(:headers)
-
3337
join_headers(stream, request) if request.state == :headers
-
3337
request.transition(:body)
-
3337
join_body(stream, request) if request.state == :body
-
2683
request.transition(:trailers)
-
2683
join_trailers(stream, request) if request.state == :trailers && !request.body.empty?
-
2683
request.transition(:done)
-
end
-
end
-
-
23
def init_connection
-
2264
@connection = ::HTTP2::Client.new(@settings)
-
2264
@connection.on(:frame, &method(:on_frame))
-
2264
@connection.on(:frame_sent, &method(:on_frame_sent))
-
2264
@connection.on(:frame_received, &method(:on_frame_received))
-
2264
@connection.on(:origin, &method(:on_origin))
-
2264
@connection.on(:promise, &method(:on_promise))
-
2264
@connection.on(:altsvc) { |frame| on_altsvc(frame[:origin], frame) }
-
2264
@connection.on(:settings_ack, &method(:on_settings))
-
2264
@connection.on(:ack, &method(:on_pong))
-
2264
@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.
-
#
-
2264
@connection.send_connection_preface
-
end
-
-
23
alias_method :reset, :init_connection
-
23
public :reset
-
-
23
def handle_stream(stream, request)
-
2569
request.on(:refuse, &method(:on_stream_refuse).curry(3)[stream, request])
-
2569
stream.on(:close, &method(:on_stream_close).curry(3)[stream, request])
-
2569
stream.on(:half_close) do
-
2553
log(level: 2) { "#{stream.id}: waiting for response..." }
-
end
-
2569
stream.on(:altsvc, &method(:on_altsvc).curry(2)[request.origin])
-
2569
stream.on(:headers, &method(:on_stream_headers).curry(3)[stream, request])
-
2569
stream.on(:data, &method(:on_stream_data).curry(3)[stream, request])
-
end
-
-
23
def set_protocol_headers(request)
-
{
-
2550
":scheme" => request.scheme,
-
":method" => request.verb,
-
":path" => request.path,
-
":authority" => request.authority,
-
}
-
end
-
-
23
def join_headers(stream, request)
-
2551
extra_headers = set_protocol_headers(request)
-
-
2551
if request.headers.key?("host")
-
6
log { "forbidden \"host\" header found (#{request.headers["host"]}), will use it as authority..." }
-
6
extra_headers[":authority"] = request.headers["host"]
-
end
-
-
2551
log(level: 1, color: :yellow) do
-
108
request.headers.merge(extra_headers).each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{v}" }.join("\n")
-
end
-
2551
stream.headers(request.headers.each(extra_headers), end_stream: request.body.empty?)
-
end
-
-
23
def join_trailers(stream, request)
-
1054
unless request.trailers?
-
1048
stream.data("", end_stream: true) if request.callbacks_for?(:trailers)
-
1048
return
-
end
-
-
6
log(level: 1, color: :yellow) do
-
12
request.trailers.each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{v}" }.join("\n")
-
end
-
6
stream.headers(request.trailers.each, end_stream: true)
-
end
-
-
23
def join_body(stream, request)
-
3205
return if request.body.empty?
-
-
1708
chunk = @drains.delete(request) || request.drain_body
-
1708
while chunk
-
2016
next_chunk = request.drain_body
-
2034
log(level: 1, color: :green) { "#{stream.id}: -> DATA: #{chunk.bytesize} bytes..." }
-
2034
log(level: 2, color: :green) { "#{stream.id}: -> #{chunk.inspect}" }
-
2016
stream.data(chunk, end_stream: !(next_chunk || request.trailers? || request.callbacks_for?(:trailers)))
-
2016
if next_chunk && (@buffer.full? || request.body.unbounded_body?)
-
654
@drains[request] = next_chunk
-
654
throw(:buffer_full)
-
end
-
1362
chunk = next_chunk
-
end
-
-
1054
return unless (error = request.drain_error)
-
-
10
on_stream_refuse(stream, request, error)
-
end
-
-
######
-
# HTTP/2 Callbacks
-
######
-
-
23
def on_stream_headers(stream, request, h)
-
2546
response = request.response
-
-
2546
if response.is_a?(Response) && response.version == "2.0"
-
95
on_stream_trailers(stream, response, h)
-
95
return
-
end
-
-
2451
log(color: :yellow) do
-
108
h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{v}" }.join("\n")
-
end
-
2451
_, status = h.shift
-
2451
headers = request.options.headers_class.new(h)
-
2451
response = request.options.response_class.new(request, status, "2.0", headers)
-
2451
request.response = response
-
2445
@streams[request] = stream
-
-
2445
handle(request, stream) if request.expects?
-
end
-
-
23
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
-
-
23
def on_stream_data(stream, request, data)
-
4505
log(level: 1, color: :green) { "#{stream.id}: <- DATA: #{data.bytesize} bytes..." }
-
4505
log(level: 2, color: :green) { "#{stream.id}: <- #{data.inspect}" }
-
4488
request.response << data
-
end
-
-
23
def on_stream_refuse(stream, request, error)
-
10
on_stream_close(stream, request, error)
-
10
stream.close
-
end
-
-
23
def on_stream_close(stream, request, error)
-
2389
return if error == :stream_closed && !@streams.key?(request)
-
-
2391
log(level: 2) { "#{stream.id}: closing stream" }
-
2379
@drains.delete(request)
-
2379
@streams.delete(request)
-
-
2379
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
-
2369
response = request.response
-
2369
if response && response.is_a?(Response) && response.status == 421
-
6
ex = MisdirectedRequestError.new(response)
-
6
ex.set_backtrace(caller)
-
6
emit(:error, request, ex)
-
else
-
2363
emit(:response, request, response)
-
end
-
end
-
2373
send(@pending.shift) unless @pending.empty?
-
-
2373
return unless @streams.empty? && exhausted?
-
-
6
if @pending.empty?
-
close
-
else
-
6
emit(:exhausted)
-
end
-
end
-
-
23
def on_frame(bytes)
-
14148
@buffer << bytes
-
end
-
-
23
def on_settings(*)
-
2241
@handshake_completed = true
-
2241
emit(:current_timeout)
-
2241
@max_concurrent_requests = [@max_concurrent_requests, @connection.remote_settings[:settings_max_concurrent_streams]].min
-
2241
send_pending
-
end
-
-
23
def on_close(_last_frame, error, _payload)
-
16
is_connection_closed = @connection.state == :closed
-
16
if error
-
16
@buffer.clear if is_connection_closed
-
16
if error == :no_error
-
11
ex = GoawayError.new
-
11
@pending.unshift(*@streams.keys)
-
11
@drains.clear
-
11
@streams.clear
-
else
-
5
ex = Error.new(0, error)
-
end
-
16
ex.set_backtrace(caller)
-
16
handle_error(ex)
-
end
-
16
return unless is_connection_closed && @streams.empty?
-
-
16
emit(:close, is_connection_closed)
-
end
-
-
23
def on_frame_sent(frame)
-
11948
log(level: 2) { "#{frame[:stream]}: frame was sent!" }
-
11876
log(level: 2, color: :blue) do
-
72
payload = frame
-
72
payload = payload.merge(payload: frame[:payload].bytesize) if frame[:type] == :data
-
72
"#{frame[:stream]}: #{payload}"
-
end
-
end
-
-
23
def on_frame_received(frame)
-
12590
log(level: 2) { "#{frame[:stream]}: frame was received!" }
-
12537
log(level: 2, color: :magenta) do
-
53
payload = frame
-
53
payload = payload.merge(payload: frame[:payload].bytesize) if frame[:type] == :data
-
53
"#{frame[:stream]}: #{payload}"
-
end
-
end
-
-
23
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
-
-
23
def on_promise(stream)
-
18
emit(:promise, @streams.key(stream.parent), stream)
-
end
-
-
23
def on_origin(origin)
-
emit(:origin, origin)
-
end
-
-
23
def on_pong(ping)
-
6
if @pings.delete(ping.to_s)
-
6
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.
-
-
23
require "ipaddr"
-
-
23
module HTTPX
-
# Represents a domain name ready for extracting its registered domain
-
# and TLD.
-
23
class DomainName
-
23
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.
-
23
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.
-
23
attr_reader :domain
-
-
23
class << self
-
23
def new(domain)
-
642
return domain if domain.is_a?(self)
-
-
594
super(domain)
-
end
-
-
# Normalizes a _domain_ using the Punycode algorithm as necessary.
-
# The result will be a downcased, ASCII-only string.
-
23
def normalize(domain)
-
570
unless domain.ascii_only?
-
domain = domain.chomp(".").unicode_normalize(:nfc)
-
domain = Punycode.encode_hostname(domain)
-
end
-
-
570
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.
-
23
def initialize(hostname)
-
594
hostname = String(hostname)
-
-
594
raise ArgumentError, "domain name must not start with a dot: #{hostname}" if hostname.start_with?(".")
-
-
98
begin
-
594
@ipaddr = IPAddr.new(hostname)
-
24
@hostname = @ipaddr.to_s
-
24
return
-
rescue IPAddr::Error
-
570
nil
-
end
-
-
570
@hostname = DomainName.normalize(hostname)
-
570
tld = if (last_dot = @hostname.rindex("."))
-
138
@hostname[(last_dot + 1)..-1]
-
else
-
432
@hostname
-
end
-
-
# unknown/local TLD
-
570
@domain = if last_dot
-
# fallback - accept cookies down to second level
-
# cf. http://www.dkim-reputation.org/regdom-libs/
-
138
if (penultimate_dot = @hostname.rindex(".", last_dot - 1))
-
36
@hostname[(penultimate_dot + 1)..-1]
-
else
-
102
@hostname
-
end
-
else
-
# no domain part - must be a local hostname
-
432
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.
-
23
def cookie_domain?(domain, host_only = false)
-
# RFC 6265 #5.3
-
# When the user agent "receives a cookie":
-
24
return self == @domain if host_only
-
-
24
domain = DomainName.new(domain)
-
-
# RFC 6265 #5.1.3
-
# Do not perform subdomain matching against IP addresses.
-
24
@hostname == domain.hostname if @ipaddr
-
-
# RFC 6265 #4.1.1
-
# Domain-value must be a subdomain.
-
24
@domain && self <= domain && domain <= @domain
-
end
-
-
23
def <=>(other)
-
36
other = DomainName.new(other)
-
36
othername = other.hostname
-
36
if othername == @hostname
-
12
0
-
23
elsif @hostname.end_with?(othername) && @hostname[-othername.size - 1, 1] == "."
-
# The other is higher
-
12
-1
-
else
-
# The other is lower
-
12
1
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
# the default exception class for exceptions raised by HTTPX.
-
23
class Error < StandardError; end
-
-
23
class UnsupportedSchemeError < Error; end
-
-
23
class ConnectionError < Error; end
-
-
# Error raised when there was a timeout. Its subclasses allow for finer-grained
-
# control of which timeout happened.
-
23
class TimeoutError < Error
-
# The timeout value which caused this error to be raised.
-
23
attr_reader :timeout
-
-
# initializes the timeout exception with the +timeout+ causing the error, and the
-
# error +message+ for it.
-
23
def initialize(timeout, message)
-
387
@timeout = timeout
-
387
super(message)
-
end
-
-
# clones this error into a HTTPX::ConnectionTimeoutError.
-
23
def to_connection_error
-
18
ex = ConnectTimeoutError.new(@timeout, message)
-
18
ex.set_backtrace(backtrace)
-
18
ex
-
end
-
end
-
-
# Raise when it can't acquire a connection for a given origin.
-
23
class PoolTimeoutError < TimeoutError
-
23
attr_reader :origin
-
-
# initializes the +origin+ it refers to, and the
-
# +timeout+ causing the error.
-
23
def initialize(origin, timeout)
-
6
@origin = origin
-
6
super(timeout, "Timed out after #{timeout} seconds while waiting for a connection to #{origin}")
-
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.
-
23
class ConnectTimeoutError < TimeoutError; end
-
-
# Error raised when there was a timeout while sending a request, or receiving a response
-
# from the server.
-
23
class RequestTimeoutError < TimeoutError
-
# The HTTPX::Request request object this exception refers to.
-
23
attr_reader :request
-
-
# initializes the exception with the +request+ and +response+ it refers to, and the
-
# +timeout+ causing the error, and the
-
23
def initialize(request, response, timeout)
-
307
@request = request
-
307
@response = response
-
307
super(timeout, "Timed out after #{timeout} seconds")
-
end
-
-
23
def marshal_dump
-
[message]
-
end
-
end
-
-
# Error raised when there was a timeout while receiving a response from the server.
-
23
class ReadTimeoutError < RequestTimeoutError; end
-
-
# Error raised when there was a timeout while sending a request from the server.
-
23
class WriteTimeoutError < RequestTimeoutError; end
-
-
# Error raised when there was a timeout while waiting for the HTTP/2 settings frame from the server.
-
23
class SettingsTimeoutError < TimeoutError; end
-
-
# Error raised when there was a timeout while resolving a domain to an IP.
-
23
class ResolveTimeoutError < TimeoutError; end
-
-
# Error raised when there was an error while resolving a domain to an IP.
-
23
class ResolveError < Error; end
-
-
# Error raised when there was an error while resolving a domain to an IP
-
# using a HTTPX::Resolver::Native resolver.
-
23
class NativeResolveError < ResolveError
-
23
attr_reader :connection, :host
-
-
# initializes the exception with the +connection+ it refers to, the +host+ domain
-
# which failed to resolve, and the error +message+.
-
23
def initialize(connection, host, message = "Can't resolve #{host}")
-
94
@connection = connection
-
94
@host = host
-
94
super(message)
-
end
-
end
-
-
# The exception class for HTTP responses with 4xx or 5xx status.
-
23
class HTTPError < Error
-
# The HTTPX::Response response object this exception refers to.
-
23
attr_reader :response
-
-
# Creates the instance and assigns the HTTPX::Response +response+.
-
23
def initialize(response)
-
76
@response = response
-
76
super("HTTP Error: #{@response.status} #{@response.headers}\n#{@response.body}")
-
end
-
-
# The HTTP response status.
-
#
-
# error.status #=> 404
-
23
def status
-
12
@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.
-
23
class MisdirectedRequestError < HTTPError; end
-
end
-
# frozen_string_literal: true
-
-
23
require "uri"
-
-
23
module HTTPX
-
23
module ArrayExtensions
-
23
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
-
22
end unless Array.method_defined?(:filter_map)
-
end
-
-
23
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
-
22
end unless Array.method_defined?(:intersect?)
-
end
-
end
-
-
23
module URIExtensions
-
# uri 0.11 backport, ships with ruby 3.1
-
23
refine URI::Generic do
-
-
23
def non_ascii_hostname
-
339
@non_ascii_hostname
-
end
-
-
23
def non_ascii_hostname=(hostname)
-
24
@non_ascii_hostname = hostname
-
end
-
-
def authority
-
5341
return host if port == default_port
-
-
558
"#{host}:#{port}"
-
22
end unless URI::HTTP.method_defined?(:authority)
-
-
def origin
-
4346
"#{scheme}://#{authority}"
-
22
end unless URI::HTTP.method_defined?(:origin)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
class Headers
-
23
class << self
-
23
def new(headers = nil)
-
18887
return headers if headers.is_a?(self)
-
-
8663
super
-
end
-
end
-
-
23
def initialize(headers = nil)
-
8663
@headers = {}
-
8663
return unless headers
-
-
8514
headers.each do |field, value|
-
44224
array_value(value).each do |v|
-
44266
add(downcased(field), v)
-
end
-
end
-
end
-
-
# cloned initialization
-
23
def initialize_clone(orig)
-
6
super
-
6
@headers = orig.instance_variable_get(:@headers).clone
-
end
-
-
# dupped initialization
-
23
def initialize_dup(orig)
-
10931
super
-
10931
@headers = orig.instance_variable_get(:@headers).dup
-
end
-
-
# freezes the headers hash
-
23
def freeze
-
12148
@headers.freeze
-
12148
super
-
end
-
-
23
def same_headers?(headers)
-
24
@headers.empty? || begin
-
24
headers.each do |k, v|
-
54
next unless key?(k)
-
-
54
return false unless v == self[k]
-
end
-
12
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
-
#
-
23
def merge(other)
-
3389
headers = dup
-
3389
other.each do |field, value|
-
2883
headers[downcased(field)] = value
-
end
-
3389
headers
-
end
-
-
# returns the comma-separated values of the header field
-
# identified by +field+, or nil otherwise.
-
#
-
23
def [](field)
-
66475
a = @headers[downcased(field)] || return
-
20157
a.join(", ")
-
end
-
-
# sets +value+ (if not nil) as single value for the +field+ header.
-
#
-
23
def []=(field, value)
-
29552
return unless value
-
-
29552
@headers[downcased(field)] = array_value(value)
-
end
-
-
# deletes all values associated with +field+ header.
-
#
-
23
def delete(field)
-
195
canonical = downcased(field)
-
195
@headers.delete(canonical) if @headers.key?(canonical)
-
end
-
-
# adds additional +value+ to the existing, for header +field+.
-
#
-
23
def add(field, value)
-
44620
(@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"
-
#
-
23
alias_method :add_header, :add
-
-
# returns the enumerable headers store in pairs of header field + the values in
-
# the comma-separated string format
-
#
-
23
def each(extra_headers = nil)
-
47483
return enum_for(__method__, extra_headers) { @headers.size } unless block_given?
-
-
25322
@headers.each do |field, value|
-
31972
yield(field, value.join(", ")) unless value.empty?
-
end
-
-
5388
extra_headers.each do |field, value|
-
17631
yield(field, value) unless value.empty?
-
25309
end if extra_headers
-
end
-
-
23
def ==(other)
-
14744
other == to_hash
-
end
-
-
# the headers store in Hash format
-
23
def to_hash
-
15748
Hash[to_a]
-
end
-
23
alias_method :to_h, :to_hash
-
-
# the headers store in array of pairs format
-
23
def to_a
-
15765
Array(each)
-
end
-
-
# headers as string
-
23
def to_s
-
1588
@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!
-
#
-
23
def key?(downcased_key)
-
46613
@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.
-
#
-
23
def get(field)
-
222
@headers[field] || EMPTY
-
end
-
-
23
private
-
-
23
def array_value(value)
-
73776
case value
-
when Array
-
71530
value.map { |val| String(val).strip }
-
else
-
41691
[String(value).strip]
-
end
-
end
-
-
23
def downcased(field)
-
187991
String(field).downcase
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "socket"
-
23
require "httpx/io/udp"
-
23
require "httpx/io/tcp"
-
23
require "httpx/io/unix"
-
-
begin
-
23
require "httpx/io/ssl"
-
rescue LoadError
-
end
-
# frozen_string_literal: true
-
-
23
require "openssl"
-
-
23
module HTTPX
-
23
TLSError = OpenSSL::SSL::SSLError
-
-
23
class SSL < TCP
-
# rubocop:disable Style/MutableConstant
-
23
TLS_OPTIONS = { alpn_protocols: %w[h2 http/1.1].freeze }
-
# https://github.com/jruby/jruby-openssl/issues/284
-
23
TLS_OPTIONS[:verify_hostname] = true if RUBY_ENGINE == "jruby"
-
# rubocop:enable Style/MutableConstant
-
23
TLS_OPTIONS.freeze
-
-
23
attr_writer :ssl_session
-
-
23
def initialize(_, _, options)
-
2100
super
-
-
2100
ctx_options = TLS_OPTIONS.merge(options.ssl)
-
2100
@sni_hostname = ctx_options.delete(:hostname) || @hostname
-
-
2100
if @keep_open && @io.is_a?(OpenSSL::SSL::SSLSocket)
-
# externally initiated ssl socket
-
17
@ctx = @io.context
-
17
@state = :negotiated
-
else
-
2083
@ctx = OpenSSL::SSL::SSLContext.new
-
2083
@ctx.set_params(ctx_options) unless ctx_options.empty?
-
2083
unless @ctx.session_cache_mode.nil? # a dummy method on JRuby
-
1776
@ctx.session_cache_mode =
-
OpenSSL::SSL::SSLContext::SESSION_CACHE_CLIENT | OpenSSL::SSL::SSLContext::SESSION_CACHE_NO_INTERNAL_STORE
-
end
-
-
2083
yield(self) if block_given?
-
end
-
-
2100
@verify_hostname = @ctx.verify_hostname
-
end
-
-
23
if OpenSSL::SSL::SSLContext.method_defined?(:session_new_cb=)
-
22
def session_new_cb(&pr)
-
5115
@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
-
-
23
def protocol
-
1943
@io.alpn_protocol || super
-
rescue StandardError
-
5
super
-
end
-
-
23
if RUBY_ENGINE == "jruby"
-
# in jruby, alpn_protocol may return ""
-
# https://github.com/jruby/jruby-openssl/issues/287
-
1
def protocol
-
336
proto = @io.alpn_protocol
-
-
335
return super if proto.nil? || proto.empty?
-
-
334
proto
-
rescue StandardError
-
1
super
-
end
-
end
-
-
23
def can_verify_peer?
-
11
@ctx.verify_mode == OpenSSL::SSL::VERIFY_PEER
-
end
-
-
23
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
-
-
23
def connected?
-
8658
@state == :negotiated
-
end
-
-
23
def expired?
-
super || ssl_session_expired?
-
end
-
-
23
def ssl_session_expired?
-
2246
@ssl_session.nil? || Process.clock_gettime(Process::CLOCK_REALTIME) >= (@ssl_session.time.to_f + @ssl_session.timeout)
-
end
-
-
23
def connect
-
8697
super
-
8676
return if @state == :negotiated ||
-
@state != :connected
-
-
6132
unless @io.is_a?(OpenSSL::SSL::SSLSocket)
-
2246
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
-
24
@sni_hostname = @ip.to_string
-
# IP addresses in SNI is not valid per RFC 6066, section 3.
-
24
@ctx.verify_hostname = false
-
end
-
-
2246
@io = OpenSSL::SSL::SSLSocket.new(@io, @ctx)
-
-
2246
@io.hostname = @sni_hostname unless hostname_is_ip
-
2246
@io.session = @ssl_session unless ssl_session_expired?
-
2246
@io.sync_close = true
-
end
-
6132
try_ssl_connect
-
end
-
-
23
def try_ssl_connect
-
6132
ret = @io.connect_nonblock(exception: false)
-
6145
log(level: 3, color: :cyan) { "TLS CONNECT: #{ret}..." }
-
6115
case ret
-
when :wait_readable
-
3904
@interests = :r
-
3904
return
-
when :wait_writable
-
@interests = :w
-
return
-
end
-
2211
@io.post_connection_check(@sni_hostname) if @ctx.verify_mode != OpenSSL::SSL::VERIFY_NONE && @verify_hostname
-
2210
transition(:negotiated)
-
2210
@interests = :w
-
end
-
-
23
private
-
-
23
def transition(nextstate)
-
8722
case nextstate
-
when :negotiated
-
2210
return unless @state == :connected
-
-
when :closed
-
2135
return unless @state == :negotiated ||
-
@state == :connected
-
end
-
8722
do_transition(nextstate)
-
end
-
-
23
def log_transition_state(nextstate)
-
53
return super unless nextstate == :negotiated
-
-
12
server_cert = @io.peer_cert
-
-
12
"#{super}\n\n" \
-
"SSL connection using #{@io.ssl_version} / #{Array(@io.cipher).first}\n" \
-
"ALPN, server accepted to use #{protocol}\n" \
-
"Server certificate:\n " \
-
"subject: #{server_cert.subject}\n " \
-
"start date: #{server_cert.not_before}\n " \
-
"expire date: #{server_cert.not_after}\n " \
-
"issuer: #{server_cert.issuer}\n " \
-
"SSL certificate verify ok."
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "resolv"
-
23
require "ipaddr"
-
-
23
module HTTPX
-
23
class TCP
-
23
include Loggable
-
-
23
using URIExtensions
-
-
23
attr_reader :ip, :port, :addresses, :state, :interests
-
-
23
alias_method :host, :ip
-
-
23
def initialize(origin, addresses, options)
-
5031
@state = :idle
-
5031
@addresses = []
-
5031
@hostname = origin.host
-
5031
@options = options
-
5031
@fallback_protocol = @options.fallback_protocol
-
5031
@port = origin.port
-
5031
@interests = :w
-
5031
if @options.io
-
40
@io = case @options.io
-
when Hash
-
12
@options.io[origin.authority]
-
else
-
28
@options.io
-
end
-
40
raise Error, "Given IO objects do not match the request authority" unless @io
-
-
40
_, _, _, @ip = @io.addr
-
40
@addresses << @ip
-
40
@keep_open = true
-
40
@state = :connected
-
else
-
4991
add_addresses(addresses)
-
end
-
5031
@ip_index = @addresses.size - 1
-
end
-
-
23
def socket
-
147
@io
-
end
-
-
23
def add_addresses(addrs)
-
5157
return if addrs.empty?
-
-
16762
addrs = addrs.map { |addr| addr.is_a?(IPAddr) ? addr : IPAddr.new(addr) }
-
-
5157
ip_index = @ip_index || (@addresses.size - 1)
-
5157
if addrs.first.ipv6?
-
# should be the next in line
-
176
@addresses = [*@addresses[0, ip_index], *addrs, *@addresses[ip_index..-1]]
-
else
-
4981
@addresses.unshift(*addrs)
-
4981
@ip_index += addrs.size if @ip_index
-
end
-
end
-
-
23
def to_io
-
16340
@io.to_io
-
end
-
-
23
def protocol
-
3213
@fallback_protocol
-
end
-
-
23
def connect
-
18713
return unless closed?
-
-
14663
if !@io || @io.closed?
-
5533
transition(:idle)
-
5533
@io = build_socket
-
end
-
14663
try_connect
-
rescue Errno::ECONNREFUSED,
-
Errno::EADDRNOTAVAIL,
-
Errno::EHOSTUNREACH,
-
SocketError,
-
IOError => e
-
413
raise e if @ip_index <= 0
-
-
369
log { "failed connecting to #{@ip} (#{e.message}), trying next..." }
-
359
@ip_index -= 1
-
359
@io = build_socket
-
359
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
-
-
23
def try_connect
-
14663
ret = @io.connect_nonblock(Socket.sockaddr_in(@port, @ip.to_s), exception: false)
-
11441
log(level: 3, color: :cyan) { "TCP CONNECT: #{ret}..." }
-
11361
case ret
-
when :wait_readable
-
@interests = :r
-
return
-
when :wait_writable
-
5882
@interests = :w
-
5882
return
-
end
-
5479
transition(:connected)
-
5479
@interests = :w
-
rescue Errno::EALREADY
-
2889
@interests = :w
-
end
-
23
private :try_connect
-
-
23
def read(size, buffer)
-
36209
ret = @io.read_nonblock(size, buffer, exception: false)
-
36209
if ret == :wait_readable
-
7490
buffer.clear
-
7490
return 0
-
end
-
28719
return if ret.nil?
-
-
28765
log { "READ: #{buffer.bytesize} bytes..." }
-
28705
buffer.bytesize
-
end
-
-
23
def write(buffer)
-
15103
siz = @io.write_nonblock(buffer, exception: false)
-
15077
return 0 if siz == :wait_writable
-
15059
return if siz.nil?
-
-
15124
log { "WRITE: #{siz} bytes..." }
-
-
15059
buffer.shift!(siz)
-
15059
siz
-
end
-
-
23
def close
-
5991
return if @keep_open || closed?
-
-
808
begin
-
5316
@io.close
-
ensure
-
5316
transition(:closed)
-
end
-
end
-
-
23
def connected?
-
9634
@state == :connected
-
end
-
-
23
def closed?
-
24693
@state == :idle || @state == :closed
-
end
-
-
23
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:
-
-
23
private
-
-
23
def build_socket
-
5892
@ip = @addresses[@ip_index]
-
5892
Socket.new(@ip.family, :STREAM, 0)
-
end
-
-
23
def transition(nextstate)
-
9831
case nextstate
-
# when :idle
-
when :connected
-
3311
return unless @state == :idle
-
when :closed
-
3181
return unless @state == :connected
-
end
-
9831
do_transition(nextstate)
-
end
-
-
23
def do_transition(nextstate)
-
18665
log(level: 1) { log_transition_state(nextstate) }
-
18553
@state = nextstate
-
end
-
-
23
def log_transition_state(nextstate)
-
112
case nextstate
-
when :connected
-
30
"Connected to #{host} (##{@io.fileno})"
-
else
-
82
"#{host} #{@state} -> #{nextstate}"
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "ipaddr"
-
-
23
module HTTPX
-
23
class UDP
-
23
include Loggable
-
-
23
def initialize(ip, port, options)
-
291
@host = ip
-
291
@port = port
-
291
@io = UDPSocket.new(IPAddr.new(ip).family)
-
291
@options = options
-
end
-
-
23
def to_io
-
935
@io.to_io
-
end
-
-
23
def connect; end
-
-
23
def connected?
-
291
true
-
end
-
-
23
def close
-
299
@io.close
-
end
-
-
23
if RUBY_ENGINE == "jruby"
-
# In JRuby, sendmsg_nonblock is not implemented
-
1
def write(buffer)
-
54
siz = @io.send(buffer.to_s, 0, @host, @port)
-
54
log { "WRITE: #{siz} bytes..." }
-
54
buffer.shift!(siz)
-
54
siz
-
end
-
else
-
22
def write(buffer)
-
489
siz = @io.sendmsg_nonblock(buffer.to_s, 0, Socket.sockaddr_in(@port, @host.to_s), exception: false)
-
489
return 0 if siz == :wait_writable
-
489
return if siz.nil?
-
-
489
log { "WRITE: #{siz} bytes..." }
-
-
489
buffer.shift!(siz)
-
489
siz
-
end
-
end
-
-
23
def read(size, buffer)
-
729
ret = @io.recvfrom_nonblock(size, 0, buffer, exception: false)
-
729
return 0 if ret == :wait_readable
-
495
return if ret.nil?
-
-
495
log { "READ: #{buffer.bytesize} bytes..." }
-
-
495
buffer.bytesize
-
rescue IOError
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
class UNIX < TCP
-
23
using URIExtensions
-
-
23
attr_reader :path
-
-
23
alias_method :host, :path
-
-
23
def initialize(origin, path, options)
-
20
@addresses = []
-
20
@hostname = origin.host
-
20
@state = :idle
-
20
@options = options
-
20
@fallback_protocol = @options.fallback_protocol
-
20
if @options.io
-
10
@io = case @options.io
-
when Hash
-
5
@options.io[origin.authority]
-
else
-
5
@options.io
-
end
-
10
raise Error, "Given IO objects do not match the request authority" unless @io
-
-
10
@path = @io.path
-
10
@keep_open = true
-
10
@state = :connected
-
10
elsif path
-
10
@path = path
-
else
-
raise Error, "No path given where to store the socket"
-
end
-
20
@io ||= build_socket
-
end
-
-
23
def connect
-
15
return unless closed?
-
-
begin
-
15
if @io.closed?
-
5
transition(:idle)
-
5
@io = build_socket
-
end
-
15
@io.connect_nonblock(Socket.sockaddr_un(@path))
-
rescue Errno::EISCONN
-
end
-
10
transition(:connected)
-
rescue Errno::EINPROGRESS,
-
Errno::EALREADY,
-
::IO::WaitReadable
-
end
-
-
23
def expired?
-
false
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}(path: #{@path}): (state: #{@state})>"
-
skipped
end
-
skipped
# :nocov:
-
-
23
private
-
-
23
def build_socket
-
15
Socket.new(Socket::PF_UNIX, :STREAM, 0)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Loggable
-
23
COLORS = {
-
black: 30,
-
red: 31,
-
green: 32,
-
yellow: 33,
-
blue: 34,
-
magenta: 35,
-
cyan: 36,
-
white: 37,
-
}.freeze
-
-
23
USE_DEBUG_LOG = ENV.key?("HTTPX_DEBUG")
-
-
23
def log(level: @options.debug_level, color: nil, &msg)
-
283717
return unless @options.debug_level >= level
-
-
127872
debug_stream = @options.debug || ($stderr if USE_DEBUG_LOG)
-
-
127872
return unless debug_stream
-
-
1236
message = (+"" << msg.call << "\n")
-
1236
message = "\e[#{COLORS[color]}m#{message}\e[0m" if color && debug_stream.respond_to?(:isatty) && debug_stream.isatty
-
1236
debug_stream << message
-
end
-
-
23
def log_exception(ex, level: @options.debug_level, color: nil)
-
895
log(level: level, color: color) { ex.full_message }
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "socket"
-
-
23
module HTTPX
-
# Contains a set of options which are passed and shared across from session to its requests or
-
# responses.
-
23
class Options
-
23
BUFFER_SIZE = 1 << 14
-
23
WINDOW_SIZE = 1 << 14 # 16K
-
23
MAX_BODY_THRESHOLD_SIZE = (1 << 10) * 112 # 112K
-
23
KEEP_ALIVE_TIMEOUT = 20
-
23
SETTINGS_TIMEOUT = 10
-
23
CLOSE_HANDSHAKE_TIMEOUT = 10
-
23
CONNECT_TIMEOUT = READ_TIMEOUT = WRITE_TIMEOUT = 60
-
23
REQUEST_TIMEOUT = OPERATION_TIMEOUT = nil
-
-
# https://github.com/ruby/resolv/blob/095f1c003f6073730500f02acbdbc55f83d70987/lib/resolv.rb#L408
-
1
ip_address_families = begin
-
23
list = Socket.ip_address_list
-
94
if list.any? { |a| a.ipv6? && !a.ipv6_loopback? && !a.ipv6_linklocal? && !a.ipv6_unique_local? }
-
[Socket::AF_INET6, Socket::AF_INET]
-
else
-
23
[Socket::AF_INET]
-
end
-
rescue NotImplementedError
-
[Socket::AF_INET]
-
end.freeze
-
-
1
DEFAULT_OPTIONS = {
-
22
:max_requests => Float::INFINITY,
-
:debug => nil,
-
23
:debug_level => (ENV["HTTPX_DEBUG"] || 1).to_i,
-
:ssl => EMPTY_HASH,
-
:http2_settings => { settings_enable_push: 0 }.freeze,
-
: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),
-
:pool_class => Class.new(Pool),
-
:connection_class => Class.new(Connection),
-
:options_class => Class.new(self),
-
:transport => nil,
-
:addresses => nil,
-
:persistent => false,
-
23
:resolver_class => (ENV["HTTPX_RESOLVER"] || :native).to_sym,
-
:resolver_options => { cache: true }.freeze,
-
:pool_options => EMPTY_HASH,
-
:ip_families => ip_address_families,
-
}.freeze
-
-
23
class << self
-
23
def new(options = {})
-
# let enhanced options go through
-
8676
return options if self == Options && options.class < self
-
6729
return options if options.is_a?(self)
-
-
3377
super
-
end
-
-
23
def method_added(meth)
-
15086
super
-
-
15086
return unless meth =~ /^option_(.+)$/
-
-
6982
optname = Regexp.last_match(1).to_sym
-
-
6982
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
-
# :pool_class :: class used to instantiate the session connection pool
-
# :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. Accepted keys depend on the resolver type.
-
# :pool_options :: hash of options passed to the connection pool (See Pool#initialize).
-
# :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.
-
23
def initialize(options = {})
-
3377
do_initialize(options)
-
3365
freeze
-
end
-
-
23
def freeze
-
8649
super
-
8649
@origin.freeze
-
8649
@base_path.freeze
-
8649
@timeout.freeze
-
8649
@headers.freeze
-
8649
@addresses.freeze
-
8649
@supported_compression_formats.freeze
-
end
-
-
23
def option_origin(value)
-
480
URI(value)
-
end
-
-
23
def option_base_path(value)
-
24
String(value)
-
end
-
-
23
def option_headers(value)
-
5960
headers_class.new(value)
-
end
-
-
23
def option_timeout(value)
-
6306
Hash[value]
-
end
-
-
23
def option_supported_compression_formats(value)
-
5516
Array(value).map(&:to_s)
-
end
-
-
23
def option_max_concurrent_requests(value)
-
727
raise TypeError, ":max_concurrent_requests must be positive" unless value.positive?
-
-
727
value
-
end
-
-
23
def option_max_requests(value)
-
5504
raise TypeError, ":max_requests must be positive" unless value.positive?
-
-
5504
value
-
end
-
-
23
def option_window_size(value)
-
5508
value = Integer(value)
-
-
5508
raise TypeError, ":window_size must be positive" unless value.positive?
-
-
5508
value
-
end
-
-
23
def option_buffer_size(value)
-
5508
value = Integer(value)
-
-
5508
raise TypeError, ":buffer_size must be positive" unless value.positive?
-
-
5508
value
-
end
-
-
23
def option_body_threshold_size(value)
-
5496
bytes = Integer(value)
-
5496
raise TypeError, ":body_threshold_size must be positive" unless bytes.positive?
-
-
5496
bytes
-
end
-
-
23
def option_transport(value)
-
35
transport = value.to_s
-
35
raise TypeError, "#{transport} is an unsupported transport type" unless %w[unix].include?(transport)
-
-
35
transport
-
end
-
-
23
def option_addresses(value)
-
32
Array(value)
-
end
-
-
23
def option_ip_families(value)
-
5496
Array(value)
-
end
-
-
23
%i[
-
ssl http2_settings
-
request_class response_class headers_class request_body_class
-
response_body_class connection_class options_class
-
pool_class pool_options
-
io fallback_protocol debug debug_level resolver_class resolver_options
-
compress_request_body decompress_response_body
-
persistent
-
].each do |method_name|
-
460
class_eval(<<-OUT, __FILE__, __LINE__ + 1)
-
# sets +v+ as the value of #{method_name}
-
def option_#{method_name}(v); v; end # def option_smth(v); v; end
-
OUT
-
end
-
-
23
REQUEST_BODY_IVARS = %i[@headers].freeze
-
-
23
def ==(other)
-
1573
super || options_equals?(other)
-
end
-
-
23
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.
-
340
ivars = instance_variables - ignore_ivars
-
340
other_ivars = other.instance_variables - ignore_ivars
-
-
340
return false if ivars.size != other_ivars.size
-
-
328
return false if ivars.sort != other_ivars.sort
-
-
328
ivars.all? do |ivar|
-
8001
instance_variable_get(ivar) == other.instance_variable_get(ivar)
-
end
-
end
-
-
23
def merge(other)
-
25523
ivar_map = nil
-
25523
other_ivars = case other
-
when Hash
-
30542
ivar_map = other.keys.to_h { |k| [:"@#{k}", k] }
-
17709
ivar_map.keys
-
else
-
7814
other.instance_variables
-
end
-
-
25523
return self if other_ivars.empty?
-
-
209137
return self if other_ivars.all? { |ivar| instance_variable_get(ivar) == access_option(other, ivar, ivar_map) }
-
-
9350
opts = dup
-
-
9350
other_ivars.each do |ivar|
-
69109
v = access_option(other, ivar, ivar_map)
-
-
69109
unless v
-
2626
opts.instance_variable_set(ivar, v)
-
2626
next
-
end
-
-
66483
v = opts.__send__(:"option_#{ivar[1..-1]}", v)
-
-
66471
orig_v = instance_variable_get(ivar)
-
-
66471
v = orig_v.merge(v) if orig_v.respond_to?(:merge) && v.respond_to?(:merge)
-
-
66471
opts.instance_variable_set(ivar, v)
-
end
-
-
9338
opts
-
end
-
-
23
def to_hash
-
2513
instance_variables.each_with_object({}) do |ivar, hs|
-
66109
hs[ivar[1..-1].to_sym] = instance_variable_get(ivar)
-
end
-
end
-
-
23
def extend_with_plugin_classes(pl)
-
5249
if defined?(pl::RequestMethods) || defined?(pl::RequestClassMethods)
-
1487
@request_class = @request_class.dup
-
1487
@request_class.__send__(:include, pl::RequestMethods) if defined?(pl::RequestMethods)
-
1487
@request_class.extend(pl::RequestClassMethods) if defined?(pl::RequestClassMethods)
-
end
-
5249
if defined?(pl::ResponseMethods) || defined?(pl::ResponseClassMethods)
-
1658
@response_class = @response_class.dup
-
1658
@response_class.__send__(:include, pl::ResponseMethods) if defined?(pl::ResponseMethods)
-
1658
@response_class.extend(pl::ResponseClassMethods) if defined?(pl::ResponseClassMethods)
-
end
-
5249
if defined?(pl::HeadersMethods) || defined?(pl::HeadersClassMethods)
-
114
@headers_class = @headers_class.dup
-
114
@headers_class.__send__(:include, pl::HeadersMethods) if defined?(pl::HeadersMethods)
-
114
@headers_class.extend(pl::HeadersClassMethods) if defined?(pl::HeadersClassMethods)
-
end
-
5249
if defined?(pl::RequestBodyMethods) || defined?(pl::RequestBodyClassMethods)
-
249
@request_body_class = @request_body_class.dup
-
249
@request_body_class.__send__(:include, pl::RequestBodyMethods) if defined?(pl::RequestBodyMethods)
-
249
@request_body_class.extend(pl::RequestBodyClassMethods) if defined?(pl::RequestBodyClassMethods)
-
end
-
5249
if defined?(pl::ResponseBodyMethods) || defined?(pl::ResponseBodyClassMethods)
-
601
@response_body_class = @response_body_class.dup
-
601
@response_body_class.__send__(:include, pl::ResponseBodyMethods) if defined?(pl::ResponseBodyMethods)
-
601
@response_body_class.extend(pl::ResponseBodyClassMethods) if defined?(pl::ResponseBodyClassMethods)
-
end
-
5249
if defined?(pl::PoolMethods)
-
427
@pool_class = @pool_class.dup
-
427
@pool_class.__send__(:include, pl::PoolMethods)
-
end
-
5249
if defined?(pl::ConnectionMethods)
-
2209
@connection_class = @connection_class.dup
-
2209
@connection_class.__send__(:include, pl::ConnectionMethods)
-
end
-
5249
return unless defined?(pl::OptionsMethods)
-
-
2161
@options_class = @options_class.dup
-
2161
@options_class.__send__(:include, pl::OptionsMethods)
-
end
-
-
23
private
-
-
23
def do_initialize(options = {})
-
3377
defaults = DEFAULT_OPTIONS.merge(options)
-
3377
defaults.each do |k, v|
-
98644
next if v.nil?
-
-
88513
option_method_name = :"option_#{k}"
-
88513
raise Error, "unknown option: #{k}" unless respond_to?(option_method_name)
-
-
88507
value = __send__(option_method_name, v)
-
88501
instance_variable_set(:"@#{k}", value)
-
end
-
end
-
-
23
def access_option(obj, k, ivar_map)
-
262663
case obj
-
when Hash
-
20537
obj[ivar_map[k]]
-
else
-
242126
obj.instance_variable_get(k)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Parser
-
23
class Error < Error; end
-
-
23
class HTTP1
-
23
VERSIONS = %w[1.0 1.1].freeze
-
-
23
attr_reader :status_code, :http_version, :headers
-
-
23
def initialize(observer)
-
3339
@observer = observer
-
3339
@state = :idle
-
3339
@buffer = "".b
-
3339
@headers = {}
-
end
-
-
23
def <<(chunk)
-
5530
@buffer << chunk
-
5530
parse
-
end
-
-
23
def reset!
-
7066
@state = :idle
-
7066
@headers.clear
-
7066
@content_length = nil
-
7066
@_has_trailers = nil
-
end
-
-
23
def upgrade?
-
3466
@upgrade
-
end
-
-
23
def upgrade_data
-
24
@buffer
-
end
-
-
23
private
-
-
23
def parse
-
5530
loop do
-
11643
state = @state
-
11643
case @state
-
when :idle
-
3726
parse_headline
-
when :headers, :trailers
-
3791
parse_headers
-
when :data
-
4124
parse_data
-
end
-
8612
return if @buffer.empty? || state == @state
-
end
-
end
-
-
23
def parse_headline
-
3726
idx = @buffer.index("\n")
-
3726
return unless idx
-
-
3726
(m = %r{\AHTTP(?:/(\d+\.\d+))?\s+(\d\d\d)(?:\s+(.*))?}in.match(@buffer)) ||
-
raise(Error, "wrong head line format")
-
3720
version, code, _ = m.captures
-
3720
raise(Error, "unsupported HTTP version (HTTP/#{version})") unless version && VERSIONS.include?(version)
-
-
3714
@http_version = version.split(".").map(&:to_i)
-
3714
@status_code = code.to_i
-
3714
raise(Error, "wrong status code (#{@status_code})") unless (100..599).cover?(@status_code)
-
-
3708
@buffer = @buffer.byteslice((idx + 1)..-1)
-
3708
nextstate(:headers)
-
end
-
-
23
def parse_headers
-
3793
headers = @headers
-
3793
buffer = @buffer
-
-
28678
while (idx = buffer.index("\n"))
-
# @type var line: String
-
28680
line = buffer.byteslice(0..idx)
-
28680
raise Error, "wrong header format" if line.start_with?("\s", "\t")
-
-
28674
line.lstrip!
-
28674
buffer = @buffer = buffer.byteslice((idx + 1)..-1)
-
28674
if line.empty?
-
3708
case @state
-
when :headers
-
3696
prepare_data(headers)
-
3696
@observer.on_headers(headers)
-
3219
return unless @state == :headers
-
-
# state might have been reset
-
# in the :headers callback
-
3164
nextstate(:data)
-
3164
headers.clear
-
when :trailers
-
12
@observer.on_trailers(headers)
-
12
headers.clear
-
12
nextstate(:complete)
-
end
-
3170
return
-
end
-
24966
separator_index = line.index(":")
-
24966
raise Error, "wrong header format" unless separator_index
-
-
# @type var key: String
-
24960
key = line.byteslice(0..(separator_index - 1))
-
-
24960
key.rstrip! # was lstripped previously!
-
# @type var value: String
-
24960
value = line.byteslice((separator_index + 1)..-1)
-
24960
value.strip!
-
24960
raise Error, "wrong header format" if value.nil?
-
-
24960
(headers[key.downcase] ||= []) << value
-
end
-
end
-
-
23
def parse_data
-
4124
if @buffer.respond_to?(:each)
-
146
@buffer.each do |chunk|
-
176
@observer.on_data(chunk)
-
end
-
3977
elsif @content_length
-
# @type var data: String
-
3954
data = @buffer.byteslice(0, @content_length)
-
3954
@buffer = @buffer.byteslice(@content_length..-1) || "".b
-
3954
@content_length -= data.bytesize
-
3954
@observer.on_data(data)
-
3943
data.clear
-
else
-
24
@observer.on_data(@buffer)
-
24
@buffer.clear
-
end
-
4107
return unless no_more_data?
-
-
3063
@buffer = @buffer.to_s
-
3063
if @_has_trailers
-
12
nextstate(:trailers)
-
else
-
3051
nextstate(:complete)
-
end
-
end
-
-
23
def prepare_data(headers)
-
3696
@upgrade = headers.key?("upgrade")
-
-
3696
@_has_trailers = headers.key?("trailer")
-
-
3696
if (tr_encodings = headers["transfer-encoding"])
-
86
tr_encodings.reverse_each do |tr_encoding|
-
86
tr_encoding.split(/ *, */).each do |encoding|
-
86
case encoding
-
when "chunked"
-
86
@buffer = Transcoder::Chunker::Decoder.new(@buffer, @_has_trailers)
-
end
-
end
-
end
-
else
-
3610
@content_length = headers["content-length"][0].to_i if headers.key?("content-length")
-
end
-
end
-
-
23
def no_more_data?
-
4107
if @content_length
-
3943
@content_length <= 0
-
163
elsif @buffer.respond_to?(:finished?)
-
140
@buffer.finished?
-
else
-
24
false
-
end
-
end
-
-
23
def nextstate(state)
-
9947
@state = state
-
9947
case state
-
when :headers
-
3708
@observer.on_start
-
when :complete
-
3063
@observer.on_complete
-
556
reset!
-
556
nextstate(:idle) unless @buffer.empty?
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
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
-
#
-
6
module Auth
-
6
module InstanceMethods
-
6
def authorization(token)
-
108
with(headers: { "authorization" => token })
-
end
-
-
6
def bearer_auth(token)
-
12
authorization("Bearer #{token}")
-
end
-
end
-
end
-
6
register_plugin :auth, Auth
-
end
-
end
-
# frozen_string_literal: true
-
-
7
require "httpx/base64"
-
-
7
module HTTPX
-
7
module Plugins
-
7
module Authentication
-
7
class Basic
-
7
def initialize(user, password, **)
-
207
@user = user
-
207
@password = password
-
end
-
-
7
def authenticate(*)
-
193
"Basic #{Base64.strict_encode64("#{@user}:#{@password}")}"
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
require "time"
-
6
require "securerandom"
-
6
require "digest"
-
-
6
module HTTPX
-
6
module Plugins
-
6
module Authentication
-
6
class Digest
-
6
def initialize(user, password, hashed: false, **)
-
132
@user = user
-
132
@password = password
-
132
@nonce = 0
-
132
@hashed = hashed
-
end
-
-
6
def can_authenticate?(authenticate)
-
120
authenticate && /Digest .*/.match?(authenticate)
-
end
-
-
6
def authenticate(request, authenticate)
-
120
"Digest #{generate_header(request.verb, request.path, authenticate)}"
-
end
-
-
6
private
-
-
6
def generate_header(meth, uri, authenticate)
-
# discard first token, it's Digest
-
120
auth_info = authenticate[/^(\w+) (.*)/, 2]
-
-
120
params = auth_info.split(/ *, */)
-
624
.to_h { |val| val.split("=", 2) }
-
624
.transform_values { |v| v.delete("\"") }
-
120
nonce = params["nonce"]
-
120
nc = next_nonce
-
-
# verify qop
-
120
qop = params["qop"]
-
-
120
if params["algorithm"] =~ /(.*?)(-sess)?$/
-
108
alg = Regexp.last_match(1)
-
108
algorithm = ::Digest.const_get(alg)
-
108
raise DigestError, "unknown algorithm \"#{alg}\"" unless algorithm
-
-
108
sess = Regexp.last_match(2)
-
else
-
12
algorithm = ::Digest::MD5
-
end
-
-
120
if qop || sess
-
120
cnonce = make_cnonce
-
120
nc = format("%<nonce>08x", nonce: nc)
-
end
-
-
120
a1 = if sess
-
[
-
24
(@hashed ? @password : algorithm.hexdigest("#{@user}:#{params["realm"]}:#{@password}")),
-
nonce,
-
cnonce,
-
3
].join ":"
-
else
-
96
@hashed ? @password : "#{@user}:#{params["realm"]}:#{@password}"
-
end
-
-
120
ha1 = algorithm.hexdigest(a1)
-
120
ha2 = algorithm.hexdigest("#{meth}:#{uri}")
-
120
request_digest = [ha1, nonce]
-
120
request_digest.push(nc, cnonce, qop) if qop
-
120
request_digest << ha2
-
120
request_digest = request_digest.join(":")
-
-
20
header = [
-
100
%(username="#{@user}"),
-
%(nonce="#{nonce}"),
-
%(uri="#{uri}"),
-
%(response="#{algorithm.hexdigest(request_digest)}"),
-
]
-
120
header << %(realm="#{params["realm"]}") if params.key?("realm")
-
120
header << %(algorithm=#{params["algorithm"]}) if params.key?("algorithm")
-
120
header << %(cnonce="#{cnonce}") if cnonce
-
120
header << %(nc=#{nc})
-
120
header << %(qop=#{qop}) if qop
-
120
header << %(opaque="#{params["opaque"]}") if params.key?("opaque")
-
120
header.join ", "
-
end
-
-
6
def make_cnonce
-
140
::Digest::MD5.hexdigest [
-
Time.now.to_i,
-
Process.pid,
-
SecureRandom.random_number(2**32),
-
].join ":"
-
end
-
-
6
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
-
-
8
module HTTPX
-
8
module Plugins
-
8
module Authentication
-
8
class Socks5
-
8
def initialize(user, password, **)
-
36
@user = user
-
36
@password = password
-
end
-
-
8
def can_authenticate?(*)
-
36
@user && @password
-
end
-
-
8
def authenticate(*)
-
36
[0x01, @user.bytesize, @user, @password.bytesize, @password].pack("CCA*CA*")
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin applies AWS Sigv4 to requests, using the AWS SDK credentials and configuration.
-
#
-
# It requires the "aws-sdk-core" gem.
-
#
-
6
module AwsSdkAuthentication
-
# Mock configuration, to be used only when resolving credentials
-
6
class Configuration
-
6
attr_reader :profile
-
-
6
def initialize(profile)
-
24
@profile = profile
-
end
-
-
6
def respond_to_missing?(*)
-
12
true
-
end
-
-
6
def method_missing(*); end
-
end
-
-
#
-
# encapsulates access to an AWS SDK credentials store.
-
#
-
6
class Credentials
-
6
def initialize(aws_credentials)
-
12
@aws_credentials = aws_credentials
-
end
-
-
6
def username
-
12
@aws_credentials.access_key_id
-
end
-
-
6
def password
-
12
@aws_credentials.secret_access_key
-
end
-
-
6
def security_token
-
12
@aws_credentials.session_token
-
end
-
end
-
-
6
class << self
-
6
def load_dependencies(_klass)
-
12
require "aws-sdk-core"
-
end
-
-
6
def configure(klass)
-
12
klass.plugin(:aws_sigv4)
-
end
-
-
6
def extra_options(options)
-
12
options.merge(max_concurrent_requests: 1)
-
end
-
-
6
def credentials(profile)
-
12
mock_configuration = Configuration.new(profile)
-
12
Credentials.new(Aws::CredentialProviderChain.new(mock_configuration).resolve)
-
end
-
-
6
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
-
12
keys = %w[AWS_REGION AMAZON_REGION AWS_DEFAULT_REGION]
-
12
env_region = ENV.values_at(*keys).compact.first
-
12
env_region = nil if env_region == ""
-
12
cfg_region = Aws.shared_config.region(profile: profile)
-
12
env_region || cfg_region
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :aws_profile :: AWS account profile to retrieve credentials from.
-
6
module OptionsMethods
-
6
def option_aws_profile(value)
-
60
String(value)
-
end
-
end
-
-
6
module InstanceMethods
-
#
-
# aws_authentication
-
# aws_authentication(credentials: Aws::Credentials.new('akid', 'secret'))
-
# aws_authentication()
-
#
-
6
def aws_sdk_authentication(
-
credentials: AwsSdkAuthentication.credentials(@options.aws_profile),
-
region: AwsSdkAuthentication.region(@options.aws_profile),
-
**options
-
)
-
-
12
aws_sigv4_authentication(
-
credentials: credentials,
-
region: region,
-
provider_prefix: "aws",
-
header_provider_field: "amz",
-
**options
-
)
-
end
-
6
alias_method :aws_auth, :aws_sdk_authentication
-
end
-
end
-
6
register_plugin :aws_sdk_authentication, AwsSdkAuthentication
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
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
-
#
-
6
module AWSSigV4
-
6
Credentials = Struct.new(:username, :password, :security_token)
-
-
# Signs requests using the AWS sigv4 signing.
-
6
class Signer
-
6
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"
-
)
-
114
@credentials = credentials || Credentials.new(username, password, security_token)
-
114
@service = service
-
114
@region = region
-
-
114
@unsigned_headers = Set.new(unsigned_headers.map(&:downcase))
-
114
@unsigned_headers << "authorization"
-
114
@unsigned_headers << "x-amzn-trace-id"
-
114
@unsigned_headers << "expect"
-
-
114
@apply_checksum_header = apply_checksum_header
-
114
@provider_prefix = provider_prefix
-
114
@header_provider_field = header_provider_field
-
-
114
@algorithm = algorithm
-
end
-
-
6
def sign!(request)
-
114
lower_provider_prefix = "#{@provider_prefix}4"
-
114
upper_provider_prefix = lower_provider_prefix.upcase
-
-
114
downcased_algorithm = @algorithm.downcase
-
-
114
datetime = (request.headers["x-#{@header_provider_field}-date"] ||= Time.now.utc.strftime("%Y%m%dT%H%M%SZ"))
-
114
date = datetime[0, 8]
-
-
114
content_hashed = request.headers["x-#{@header_provider_field}-content-#{downcased_algorithm}"] || hexdigest(request.body)
-
-
108
request.headers["x-#{@header_provider_field}-content-#{downcased_algorithm}"] ||= content_hashed if @apply_checksum_header
-
108
request.headers["x-#{@header_provider_field}-security-token"] ||= @credentials.security_token if @credentials.security_token
-
-
108
signature_headers = request.headers.each.reject do |k, _|
-
738
@unsigned_headers.include?(k)
-
end
-
# aws sigv4 needs to declare the host, regardless of protocol version
-
108
signature_headers << ["host", request.authority] unless request.headers.key?("host")
-
108
signature_headers.sort_by!(&:first)
-
-
108
signed_headers = signature_headers.map(&:first).join(";")
-
-
108
canonical_headers = signature_headers.map do |k, v|
-
# eliminate whitespace between value fields, unless it's a quoted value
-
726
"#{k}:#{v.start_with?("\"") && v.end_with?("\"") ? v : v.gsub(/\s+/, " ").strip}\n"
-
end.join
-
-
# canonical request
-
108
creq = "#{request.verb}" \
-
"\n#{request.canonical_path}" \
-
"\n#{request.canonical_query}" \
-
"\n#{canonical_headers}" \
-
"\n#{signed_headers}" \
-
"\n#{content_hashed}"
-
-
108
credential_scope = "#{date}" \
-
"/#{@region}" \
-
"/#{@service}" \
-
"/#{lower_provider_prefix}_request"
-
-
108
algo_line = "#{upper_provider_prefix}-HMAC-#{@algorithm}"
-
# string to sign
-
108
sts = "#{algo_line}" \
-
"\n#{datetime}" \
-
"\n#{credential_scope}" \
-
"\n#{OpenSSL::Digest.new(@algorithm).hexdigest(creq)}"
-
-
# signature
-
108
k_date = hmac("#{upper_provider_prefix}#{@credentials.password}", date)
-
108
k_region = hmac(k_date, @region)
-
108
k_service = hmac(k_region, @service)
-
108
k_credentials = hmac(k_service, "#{lower_provider_prefix}_request")
-
108
sig = hexhmac(k_credentials, sts)
-
-
108
credential = "#{@credentials.username}/#{credential_scope}"
-
# apply signature
-
108
request.headers["authorization"] =
-
"#{algo_line} " \
-
"Credential=#{credential}, " \
-
"SignedHeaders=#{signed_headers}, " \
-
"Signature=#{sig}"
-
end
-
-
6
private
-
-
6
def hexdigest(value)
-
108
digest = OpenSSL::Digest.new(@algorithm)
-
-
108
if value.respond_to?(:read)
-
24
if value.respond_to?(:to_path)
-
# files, pathnames
-
6
digest.file(value.to_path).hexdigest
-
else
-
# gzipped request bodies
-
18
raise Error, "request body must be rewindable" unless value.respond_to?(:rewind)
-
-
18
buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
2
begin
-
18
IO.copy_stream(value, buffer)
-
18
buffer.flush
-
-
18
digest.file(buffer.to_path).hexdigest
-
ensure
-
18
value.rewind
-
18
buffer.close
-
18
buffer.unlink
-
end
-
end
-
else
-
# error on endless generators
-
84
raise Error, "hexdigest for endless enumerators is not supported" if value.unbounded_body?
-
-
78
mb_buffer = value.each.with_object("".b) do |chunk, b|
-
42
b << chunk
-
42
break if b.bytesize >= 1024 * 1024
-
end
-
-
78
digest.hexdigest(mb_buffer)
-
end
-
end
-
-
6
def hmac(key, value)
-
432
OpenSSL::HMAC.digest(OpenSSL::Digest.new(@algorithm), key, value)
-
end
-
-
6
def hexhmac(key, value)
-
108
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new(@algorithm), key, value)
-
end
-
end
-
-
6
class << self
-
6
def load_dependencies(*)
-
114
require "set"
-
114
require "digest/sha2"
-
end
-
-
6
def configure(klass)
-
114
klass.plugin(:expect)
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :sigv4_signer :: instance of HTTPX::Plugins::AWSSigV4 used to sign requests.
-
6
module OptionsMethods
-
6
def option_sigv4_signer(value)
-
240
value.is_a?(Signer) ? value : Signer.new(value)
-
end
-
end
-
-
6
module InstanceMethods
-
6
def aws_sigv4_authentication(**options)
-
114
with(sigv4_signer: Signer.new(**options))
-
end
-
-
6
def build_request(*)
-
114
request = super
-
-
114
return request if request.headers.key?("authorization")
-
-
114
signer = request.options.sigv4_signer
-
-
114
return request unless signer
-
-
114
signer.sign!(request)
-
-
108
request
-
end
-
end
-
-
6
module RequestMethods
-
6
def canonical_path
-
108
path = uri.path.dup
-
108
path << "/" if path.empty?
-
132
path.gsub(%r{[^/]+}) { |part| CGI.escape(part.encode("UTF-8")).gsub("+", "%20").gsub("%7E", "~") }
-
end
-
-
6
def canonical_query
-
132
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
-
132
params.each.with_index.sort do |a, b|
-
48
a, a_offset = a
-
48
b, b_offset = b
-
48
a_name, a_value = a.split("=", 2)
-
48
b_name, b_value = b.split("=", 2)
-
48
if a_name == b_name
-
24
if a_value == b_value
-
12
a_offset <=> b_offset
-
else
-
12
a_value <=> b_value
-
end
-
else
-
24
a_name <=> b_name
-
end
-
end.map(&:first).join("&")
-
end
-
end
-
end
-
6
register_plugin :aws_sigv4, AWSSigV4
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
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
-
#
-
6
module BasicAuth
-
6
class << self
-
6
def load_dependencies(_klass)
-
84
require_relative "auth/basic"
-
end
-
-
6
def configure(klass)
-
84
klass.plugin(:auth)
-
end
-
end
-
-
6
module InstanceMethods
-
6
def basic_auth(user, password)
-
96
authorization(Authentication::Basic.new(user, password).authenticate)
-
end
-
end
-
end
-
6
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
-
-
23
module HTTPX
-
23
module Plugins
-
#
-
# This plugin adds suppoort for callbacks around the request/response lifecycle.
-
#
-
# https://gitlab.com/os85/httpx/-/wikis/Events
-
#
-
23
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.
-
23
class CallbackError < Exception; end # rubocop:disable Lint/InheritException
-
-
23
module InstanceMethods
-
23
include HTTPX::Callbacks
-
-
23
%i[
-
connection_opened connection_closed
-
request_error
-
request_started request_body_chunk request_completed
-
response_started response_body_chunk response_completed
-
].each do |meth|
-
207
class_eval(<<-MOD, __FILE__, __LINE__ + 1)
-
def on_#{meth}(&blk) # def on_connection_opened(&blk)
-
on(:#{meth}, &blk) # on(:connection_opened, &blk)
-
end # end
-
MOD
-
end
-
-
23
private
-
-
23
def do_init_connection(connection, selector)
-
157
super
-
157
connection.on(:open) do
-
147
next unless connection.current_session == self
-
-
147
emit_or_callback_error(:connection_opened, connection.origin, connection.io.socket)
-
end
-
157
connection.on(:close) do
-
140
next unless connection.current_session == self
-
-
140
emit_or_callback_error(:connection_closed, connection.origin) if connection.used?
-
end
-
-
157
connection
-
end
-
-
23
def set_request_callbacks(request)
-
159
super
-
-
159
request.on(:headers) do
-
135
emit_or_callback_error(:request_started, request)
-
end
-
159
request.on(:body_chunk) do |chunk|
-
12
emit_or_callback_error(:request_body_chunk, request, chunk)
-
end
-
159
request.on(:done) do
-
123
emit_or_callback_error(:request_completed, request)
-
end
-
-
159
request.on(:response_started) do |res|
-
123
if res.is_a?(Response)
-
111
emit_or_callback_error(:response_started, request, res)
-
99
res.on(:chunk_received) do |chunk|
-
114
emit_or_callback_error(:response_body_chunk, request, res, chunk)
-
end
-
else
-
12
emit_or_callback_error(:request_error, request, res.error)
-
end
-
end
-
159
request.on(:response) do |res|
-
99
emit_or_callback_error(:response_completed, request, res)
-
end
-
end
-
-
23
def emit_or_callback_error(*args)
-
881
emit(*args)
-
rescue StandardError => e
-
84
ex = CallbackError.new(e.message)
-
84
ex.set_backtrace(e.backtrace)
-
84
raise ex
-
end
-
-
23
def receive_requests(*)
-
159
super
-
rescue CallbackError => e
-
78
raise e.cause
-
end
-
-
23
def close(*)
-
157
super
-
rescue CallbackError => e
-
6
raise e.cause
-
end
-
end
-
end
-
23
register_plugin :callbacks, Callbacks
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin implements a circuit breaker around connection errors.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Circuit-Breaker
-
#
-
6
module CircuitBreaker
-
6
using URIExtensions
-
-
6
def self.load_dependencies(*)
-
42
require_relative "circuit_breaker/circuit"
-
42
require_relative "circuit_breaker/circuit_store"
-
end
-
-
6
def self.extra_options(options)
-
42
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
-
-
6
module InstanceMethods
-
6
include HTTPX::Callbacks
-
-
6
def initialize(*)
-
42
super
-
42
@circuit_store = CircuitStore.new(@options)
-
end
-
-
6
%i[circuit_open].each do |meth|
-
6
class_eval(<<-MOD, __FILE__, __LINE__ + 1)
-
def on_#{meth}(&blk) # def on_circuit_open(&blk)
-
on(:#{meth}, &blk) # on(:circuit_open, &blk)
-
end # end
-
MOD
-
end
-
-
6
private
-
-
6
def send_requests(*requests)
-
# @type var short_circuit_responses: Array[response]
-
168
short_circuit_responses = []
-
-
# run all requests through the circuit breaker, see if the circuit is
-
# open for any of them.
-
168
real_requests = requests.each_with_index.with_object([]) do |(req, idx), real_reqs|
-
168
short_circuit_response = @circuit_store.try_respond(req)
-
168
if short_circuit_response.nil?
-
132
real_reqs << req
-
132
next
-
end
-
36
short_circuit_responses[idx] = short_circuit_response
-
end
-
-
# run requests for the remainder
-
168
unless real_requests.empty?
-
132
responses = super(*real_requests)
-
-
132
real_requests.each_with_index do |request, idx|
-
132
short_circuit_responses[requests.index(request)] = responses[idx]
-
end
-
end
-
-
168
short_circuit_responses
-
end
-
-
6
def on_response(request, response)
-
132
emit(:circuit_open, request) if try_circuit_open(request, response)
-
-
132
super
-
end
-
-
6
def try_circuit_open(request, response)
-
132
if response.is_a?(ErrorResponse)
-
96
case response.error
-
when RequestTimeoutError
-
60
@circuit_store.try_open(request.uri, response)
-
else
-
36
@circuit_store.try_open(request.origin, response)
-
end
-
36
elsif (break_on = request.options.circuit_breaker_break_on) && break_on.call(response)
-
12
@circuit_store.try_open(request.uri, response)
-
else
-
24
@circuit_store.try_close(request.uri)
-
4
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>).
-
6
module OptionsMethods
-
6
def option_circuit_breaker_max_attempts(value)
-
84
attempts = Integer(value)
-
84
raise TypeError, ":circuit_breaker_max_attempts must be positive" unless attempts.positive?
-
-
84
attempts
-
end
-
-
6
def option_circuit_breaker_reset_attempts_in(value)
-
48
timeout = Float(value)
-
48
raise TypeError, ":circuit_breaker_reset_attempts_in must be positive" unless timeout.positive?
-
-
48
timeout
-
end
-
-
6
def option_circuit_breaker_break_in(value)
-
66
timeout = Float(value)
-
66
raise TypeError, ":circuit_breaker_break_in must be positive" unless timeout.positive?
-
-
66
timeout
-
end
-
-
6
def option_circuit_breaker_half_open_drip_rate(value)
-
66
ratio = Float(value)
-
66
raise TypeError, ":circuit_breaker_half_open_drip_rate must be a number between 0 and 1" unless (0..1).cover?(ratio)
-
-
66
ratio
-
end
-
-
6
def option_circuit_breaker_break_on(value)
-
12
raise TypeError, ":circuit_breaker_break_on must be called with the response" unless value.respond_to?(:call)
-
-
12
value
-
end
-
end
-
end
-
6
register_plugin :circuit_breaker, CircuitBreaker
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
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.
-
#
-
6
class Circuit
-
6
def initialize(max_attempts, reset_attempts_in, break_in, circuit_breaker_half_open_drip_rate)
-
42
@max_attempts = max_attempts
-
42
@reset_attempts_in = reset_attempts_in
-
42
@break_in = break_in
-
42
@circuit_breaker_half_open_drip_rate = circuit_breaker_half_open_drip_rate
-
42
@attempts = 0
-
-
42
total_real_attempts = @max_attempts * @circuit_breaker_half_open_drip_rate
-
42
@drip_factor = (@max_attempts / total_real_attempts).round
-
42
@state = :closed
-
end
-
-
6
def respond
-
168
try_close
-
-
168
case @state
-
when :closed
-
17
nil
-
when :half_open
-
42
@attempts += 1
-
-
# do real requests while drip rate valid
-
42
if (@real_attempts % @drip_factor).zero?
-
30
@real_attempts += 1
-
30
return
-
end
-
-
12
@response
-
when :open
-
-
24
@response
-
end
-
end
-
-
6
def try_open(response)
-
108
case @state
-
when :closed
-
90
now = Utils.now
-
-
90
if @attempts.positive?
-
# reset if error happened long ago
-
36
@attempts = 0 if now - @attempted_at > @reset_attempts_in
-
else
-
54
@attempted_at = now
-
end
-
-
90
@attempts += 1
-
-
90
return unless @attempts >= @max_attempts
-
-
48
@state = :open
-
48
@opened_at = now
-
48
@response = response
-
when :half_open
-
# open immediately
-
-
18
@state = :open
-
18
@attempted_at = @opened_at = Utils.now
-
18
@response = response
-
end
-
end
-
-
6
def try_close
-
192
case @state
-
when :closed
-
17
nil
-
when :half_open
-
-
# do not close circuit unless attempts exhausted
-
36
return unless @attempts >= @max_attempts
-
-
# reset!
-
12
@attempts = 0
-
12
@opened_at = @attempted_at = @response = nil
-
12
@state = :closed
-
-
when :open
-
54
if Utils.elapsed_time(@opened_at) > @break_in
-
30
@state = :half_open
-
30
@attempts = 0
-
30
@real_attempts = 0
-
end
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX::Plugins::CircuitBreaker
-
6
using HTTPX::URIExtensions
-
-
6
class CircuitStore
-
6
def initialize(options)
-
42
@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
-
42
@circuits_mutex = Thread::Mutex.new
-
end
-
-
6
def try_open(uri, response)
-
216
circuit = @circuits_mutex.synchronize { get_circuit_for_uri(uri) }
-
-
108
circuit.try_open(response)
-
end
-
-
6
def try_close(uri)
-
24
circuit = @circuits_mutex.synchronize do
-
24
return unless @circuits.key?(uri.origin) || @circuits.key?(uri.to_s)
-
-
24
get_circuit_for_uri(uri)
-
end
-
-
24
circuit.try_close
-
end
-
-
# if circuit is open, it'll respond with the stored response.
-
# if not, nil.
-
6
def try_respond(request)
-
336
circuit = @circuits_mutex.synchronize { get_circuit_for_uri(request.uri) }
-
-
168
circuit.respond
-
end
-
-
6
private
-
-
6
def get_circuit_for_uri(uri)
-
300
if uri.respond_to?(:origin) && @circuits.key?(uri.origin)
-
216
@circuits[uri.origin]
-
else
-
84
@circuits[uri.to_s]
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds `Content-Digest` headers to requests
-
# and can validate these headers on responses
-
#
-
# https://datatracker.ietf.org/doc/html/rfc9530
-
#
-
6
module ContentDigest
-
6
class Error < HTTPX::Error; end
-
-
# Error raised on response "content-digest" header validation.
-
6
class ValidationError < Error
-
6
attr_reader :response
-
-
6
def initialize(message, response)
-
36
super(message)
-
36
@response = response
-
end
-
end
-
-
6
class MissingContentDigestError < ValidationError; end
-
6
class InvalidContentDigestError < ValidationError; end
-
-
1
SUPPORTED_ALGORITHMS = {
-
5
"sha-256" => OpenSSL::Digest::SHA256,
-
"sha-512" => OpenSSL::Digest::SHA512,
-
}.freeze
-
-
6
class << self
-
6
def extra_options(options)
-
156
options.merge(encode_content_digest: true, validate_content_digest: false, content_digest_algorithm: "sha-256")
-
end
-
end
-
-
# add support for the following options:
-
#
-
# :content_digest_algorithm :: the digest algorithm to use. Currently supports `sha-256` and `sha-512`. (defaults to `sha-256`)
-
# :encode_content_digest :: whether a <tt>Content-Digest</tt> header should be computed for the request;
-
# can also be a callable object (i.e. <tt>->(req) { ... }</tt>, defaults to <tt>true</tt>)
-
# :validate_content_digest :: whether a <tt>Content-Digest</tt> header in the response should be validated;
-
# can also be a callable object (i.e. <tt>->(res) { ... }</tt>, defaults to <tt>false</tt>)
-
6
module OptionsMethods
-
6
def option_content_digest_algorithm(value)
-
162
raise TypeError, ":content_digest_algorithm must be one of 'sha-256', 'sha-512'" unless SUPPORTED_ALGORITHMS.key?(value)
-
-
162
value
-
end
-
-
6
def option_encode_content_digest(value)
-
156
value
-
end
-
-
6
def option_validate_content_digest(value)
-
108
value
-
end
-
end
-
-
6
module ResponseBodyMethods
-
6
attr_reader :content_digest_buffer
-
-
6
def initialize(response, options)
-
132
super
-
-
132
return unless response.headers.key?("content-digest")
-
-
96
should_validate = options.validate_content_digest
-
96
should_validate = should_validate.call(response) if should_validate.respond_to?(:call)
-
-
96
return unless should_validate
-
-
84
@content_digest_buffer = Response::Buffer.new(
-
threshold_size: @options.body_threshold_size,
-
bytesize: @length,
-
encoding: @encoding
-
)
-
end
-
-
6
def write(chunk)
-
216
@content_digest_buffer.write(chunk) if @content_digest_buffer
-
216
super
-
end
-
-
6
def close
-
84
if @content_digest_buffer
-
84
@content_digest_buffer.close
-
84
@content_digest_buffer = nil
-
end
-
84
super
-
end
-
end
-
-
6
module InstanceMethods
-
6
def build_request(*)
-
168
request = super
-
-
168
return request if request.empty?
-
-
36
return request if request.headers.key?("content-digest")
-
-
36
perform_encoding = @options.encode_content_digest
-
36
perform_encoding = perform_encoding.call(request) if perform_encoding.respond_to?(:call)
-
-
36
return request unless perform_encoding
-
-
30
digest = base64digest(request.body)
-
30
request.headers.add("content-digest", "#{@options.content_digest_algorithm}=:#{digest}:")
-
-
30
request
-
end
-
-
6
private
-
-
6
def fetch_response(request, _, _)
-
426
response = super
-
426
return response unless response.is_a?(Response)
-
-
132
perform_validation = @options.validate_content_digest
-
132
perform_validation = perform_validation.call(response) if perform_validation.respond_to?(:call)
-
-
132
validate_content_digest(response) if perform_validation
-
-
96
response
-
rescue ValidationError => e
-
36
ErrorResponse.new(request, e)
-
end
-
-
6
def validate_content_digest(response)
-
96
content_digest_header = response.headers["content-digest"]
-
-
96
raise MissingContentDigestError.new("response is missing a `content-digest` header", response) unless content_digest_header
-
-
84
digests = extract_content_digests(content_digest_header)
-
-
84
included_algorithms = SUPPORTED_ALGORITHMS.keys & digests.keys
-
-
84
raise MissingContentDigestError.new("unsupported algorithms: #{digests.keys.join(", ")}", response) if included_algorithms.empty?
-
-
84
content_buffer = response.body.content_digest_buffer
-
-
84
included_algorithms.each do |algorithm|
-
84
digest = SUPPORTED_ALGORITHMS.fetch(algorithm).new
-
84
digest_received = digests[algorithm]
-
digest_computed =
-
83
if content_buffer.respond_to?(:to_path)
-
12
content_buffer.flush
-
12
digest.file(content_buffer.to_path).base64digest
-
else
-
72
digest.base64digest(content_buffer.to_s)
-
end
-
-
raise InvalidContentDigestError.new("#{algorithm} digest does not match content",
-
83
response) unless digest_received == digest_computed
-
end
-
end
-
-
6
def extract_content_digests(header)
-
84
header.split(",").to_h do |entry|
-
96
algorithm, digest = entry.split("=", 2)
-
96
raise Error, "#{entry} is an invalid digest format" unless algorithm && digest
-
-
96
[algorithm, digest.byteslice(1..-2)]
-
end
-
end
-
-
6
def base64digest(body)
-
30
digest = SUPPORTED_ALGORITHMS.fetch(@options.content_digest_algorithm).new
-
-
30
if body.respond_to?(:read)
-
24
if body.respond_to?(:to_path)
-
6
digest.file(body.to_path).base64digest
-
else
-
18
raise ContentDigestError, "request body must be rewindable" unless body.respond_to?(:rewind)
-
-
18
buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
2
begin
-
18
IO.copy_stream(body, buffer)
-
18
buffer.flush
-
-
18
digest.file(buffer.to_path).base64digest
-
ensure
-
18
body.rewind
-
18
buffer.close
-
18
buffer.unlink
-
end
-
end
-
else
-
6
raise ContentDigestError, "base64digest for endless enumerators is not supported" if body.unbounded_body?
-
-
6
buffer = "".b
-
12
body.each { |chunk| buffer << chunk }
-
-
6
digest.base64digest(buffer)
-
end
-
end
-
end
-
end
-
6
register_plugin :content_digest, ContentDigest
-
end
-
end
-
# frozen_string_literal: true
-
-
6
require "forwardable"
-
-
6
module HTTPX
-
6
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
-
#
-
6
module Cookies
-
6
def self.load_dependencies(*)
-
108
require "httpx/plugins/cookies/jar"
-
108
require "httpx/plugins/cookies/cookie"
-
108
require "httpx/plugins/cookies/set_cookie_parser"
-
end
-
-
6
module InstanceMethods
-
6
extend Forwardable
-
-
6
def_delegator :@options, :cookies
-
-
6
def initialize(options = {}, &blk)
-
216
super({ cookies: Jar.new }.merge(options), &blk)
-
end
-
-
6
def wrap
-
12
return super unless block_given?
-
-
12
super do |session|
-
12
old_cookies_jar = @options.cookies.dup
-
1
begin
-
12
yield session
-
ensure
-
12
@options = @options.merge(cookies: old_cookies_jar)
-
end
-
end
-
end
-
-
6
def build_request(*)
-
240
request = super
-
240
request.headers.set_cookie(request.options.cookies[request.uri])
-
240
request
-
end
-
-
6
private
-
-
6
def on_response(_request, response)
-
240
if response && response.respond_to?(:headers) && (set_cookie = response.headers["set-cookie"])
-
-
48
log { "cookies: set-cookie is over #{Cookie::MAX_LENGTH}" } if set_cookie.bytesize > Cookie::MAX_LENGTH
-
-
48
@options.cookies.parse(set_cookie)
-
end
-
-
240
super
-
end
-
end
-
-
6
module HeadersMethods
-
6
def set_cookie(cookies)
-
240
return if cookies.empty?
-
-
204
header_value = cookies.sort.join("; ")
-
-
204
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)
-
6
module OptionsMethods
-
6
def option_headers(*)
-
240
value = super
-
-
240
merge_cookie_in_jar(value.delete("cookie"), @cookies) if defined?(@cookies) && value.key?("cookie")
-
-
240
value
-
end
-
-
6
def option_cookies(value)
-
360
jar = value.is_a?(Jar) ? value : Jar.new(value)
-
-
360
merge_cookie_in_jar(@headers.delete("cookie"), jar) if defined?(@headers) && @headers.key?("cookie")
-
-
360
jar
-
end
-
-
6
private
-
-
6
def merge_cookie_in_jar(cookies, jar)
-
12
cookies.each do |ck|
-
12
ck.split(/ *; */).each do |cookie|
-
24
name, value = cookie.split("=", 2)
-
24
jar.add(Cookie.new(name, value))
-
end
-
end
-
end
-
end
-
end
-
6
register_plugin :cookies, Cookies
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins::Cookies
-
# The HTTP Cookie.
-
#
-
# Contains the single cookie info: name, value and attributes.
-
6
class Cookie
-
6
include Comparable
-
# Maximum number of bytes per cookie (RFC 6265 6.1 requires 4096 at
-
# least)
-
6
MAX_LENGTH = 4096
-
-
6
attr_reader :domain, :path, :name, :value, :created_at
-
-
6
def path=(path)
-
138
path = String(path)
-
138
@path = path.start_with?("/") ? path : "/"
-
end
-
-
# See #domain.
-
6
def domain=(domain)
-
30
domain = String(domain)
-
-
30
if domain.start_with?(".")
-
12
@for_domain = true
-
12
domain = domain[1..-1]
-
end
-
-
30
return if domain.empty?
-
-
30
@domain_name = DomainName.new(domain)
-
# RFC 6265 5.3 5.
-
30
@for_domain = false if @domain_name.domain.nil? # a public suffix or IP address
-
-
30
@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.
-
6
def <=>(other)
-
# RFC 6265 5.4
-
# Precedence: 1. longer path 2. older creation
-
515
(@name <=> other.name).nonzero? ||
-
45
(other.path.length <=> @path.length).nonzero? ||
-
26
(@created_at <=> other.created_at).nonzero? || 0
-
end
-
-
6
class << self
-
6
def new(cookie, *args)
-
378
return cookie if cookie.is_a?(self)
-
-
378
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
-
6
def path_match?(base_path, target_path)
-
1014
base_path.start_with?("/") || (return false)
-
# RFC 6265 5.1.4
-
1014
bsize = base_path.size
-
1014
tsize = target_path.size
-
1014
return bsize == 1 if tsize.zero? # treat empty target_path as "/"
-
1014
return false unless target_path.start_with?(base_path)
-
1008
return true if bsize == tsize || base_path.end_with?("/")
-
-
12
target_path[bsize] == "/"
-
end
-
end
-
-
6
def initialize(arg, *attrs)
-
378
@created_at = Time.now
-
-
378
if attrs.empty?
-
18
attr_hash = Hash.try_convert(arg)
-
else
-
360
@name = arg
-
360
@value, attr_hash = attrs
-
360
attr_hash = Hash.try_convert(attr_hash)
-
end
-
-
attr_hash.each do |key, val|
-
234
key = key.downcase.tr("-", "_").to_sym unless key.is_a?(Symbol)
-
-
234
case key
-
when :domain, :path
-
145
__send__(:"#{key}=", val)
-
else
-
66
instance_variable_set(:"@#{key}", val)
-
end
-
377
end if attr_hash
-
-
378
@path ||= "/"
-
378
raise ArgumentError, "name must be specified" if @name.nil?
-
-
378
@name = @name.to_s
-
end
-
-
6
def expires
-
570
@expires || (@created_at && @max_age ? @created_at + @max_age : nil)
-
end
-
-
6
def expired?(time = Time.now)
-
546
return false unless expires
-
-
24
expires <= time
-
end
-
-
# Returns a string for use in the Cookie header, i.e. `name=value`
-
# or `name="value"`.
-
6
def cookie_value
-
414
"#{@name}=#{Scanner.quote(@value.to_s)}"
-
end
-
6
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.
-
6
def valid_for_uri?(uri)
-
534
uri = URI(uri)
-
# RFC 6265 5.4
-
-
534
return false if @secure && uri.scheme != "https"
-
-
528
acceptable_from_uri?(uri) && Cookie.path_match?(@path, uri.path)
-
end
-
-
6
private
-
-
# Tests if it is OK to accept this cookie if it is sent from a given
-
# URI/URL, `uri`.
-
6
def acceptable_from_uri?(uri)
-
552
uri = URI(uri)
-
-
552
host = DomainName.new(uri.host)
-
-
# RFC 6265 5.3
-
552
if host.hostname == @domain
-
12
true
-
539
elsif @for_domain # !host-only-flag
-
24
host.cookie_domain?(@domain_name)
-
else
-
516
@domain.nil?
-
end
-
end
-
-
6
module Scanner
-
6
RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/.freeze
-
-
6
module_function
-
-
6
def quote(s)
-
414
return s unless s.match(RE_BAD_CHAR)
-
-
6
"\"#{s.gsub(/([\\"])/, "\\\\\\1")}\""
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins::Cookies
-
# The Cookie Jar
-
#
-
# It holds a bunch of cookies.
-
6
class Jar
-
6
using URIExtensions
-
-
6
include Enumerable
-
-
6
def initialize_dup(orig)
-
162
super
-
162
@cookies = orig.instance_variable_get(:@cookies).dup
-
end
-
-
6
def initialize(cookies = nil)
-
402
@cookies = []
-
-
100
cookies.each do |elem|
-
132
cookie = case elem
-
when Cookie
-
12
elem
-
when Array
-
108
Cookie.new(*elem)
-
else
-
12
Cookie.new(elem)
-
end
-
-
132
@cookies << cookie
-
401
end if cookies
-
end
-
-
6
def parse(set_cookie)
-
108
SetCookieParser.call(set_cookie) do |name, value, attrs|
-
156
add(Cookie.new(name, value, attrs))
-
end
-
end
-
-
6
def add(cookie, path = nil)
-
342
c = cookie.dup
-
-
342
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.
-
648
@cookies.delete_if { |ck| ck.name == c.name && ck.domain == c.domain && ck.path == c.path }
-
-
342
@cookies << c
-
end
-
-
6
def [](uri)
-
354
each(uri).sort
-
end
-
-
6
def each(uri = nil, &blk)
-
888
return enum_for(__method__, uri) unless blk
-
-
510
return @cookies.each(&blk) unless uri
-
-
354
uri = URI(uri)
-
-
354
now = Time.now
-
354
tpath = uri.path
-
-
354
@cookies.delete_if do |cookie|
-
546
if cookie.expired?(now)
-
12
true
-
else
-
534
yield cookie if cookie.valid_for_uri?(uri) && Cookie.path_match?(cookie.path, tpath)
-
534
false
-
end
-
end
-
end
-
-
6
def merge(other)
-
150
cookies_dup = dup
-
-
150
other.each do |elem|
-
162
cookie = case elem
-
when Cookie
-
150
elem
-
when Array
-
6
Cookie.new(*elem)
-
else
-
6
Cookie.new(elem)
-
end
-
-
162
cookies_dup.add(cookie)
-
end
-
-
150
cookies_dup
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
require "strscan"
-
6
require "time"
-
-
6
module HTTPX
-
6
module Plugins::Cookies
-
6
module SetCookieParser
-
# Whitespace.
-
6
RE_WSP = /[ \t]+/.freeze
-
-
# A pattern that matches a cookie name or attribute name which may
-
# be empty, capturing trailing whitespace.
-
6
RE_NAME = /(?!#{RE_WSP})[^,;\\"=]*/.freeze
-
-
6
RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/.freeze
-
-
# A pattern that matches the comma in a (typically date) value.
-
6
RE_COOKIE_COMMA = /,(?=#{RE_WSP}?#{RE_NAME}=)/.freeze
-
-
6
module_function
-
-
6
def scan_dquoted(scanner)
-
12
s = +""
-
-
12
until scanner.eos?
-
48
break if scanner.skip(/"/)
-
-
36
if scanner.skip(/\\/)
-
12
s << scanner.getch
-
23
elsif scanner.scan(/[^"\\]+/)
-
24
s << scanner.matched
-
end
-
end
-
-
12
s
-
end
-
-
6
def scan_value(scanner, comma_as_separator = false)
-
330
value = +""
-
-
330
until scanner.eos?
-
570
if scanner.scan(/[^,;"]+/)
-
324
value << scanner.matched
-
245
elsif scanner.skip(/"/)
-
# RFC 6265 2.2
-
# A cookie-value may be DQUOTE'd.
-
12
value << scan_dquoted(scanner)
-
233
elsif scanner.check(/;/)
-
174
break
-
59
elsif comma_as_separator && scanner.check(RE_COOKIE_COMMA)
-
48
break
-
else
-
12
value << scanner.getch
-
end
-
end
-
-
330
value.rstrip!
-
330
value
-
end
-
-
6
def scan_name_value(scanner, comma_as_separator = false)
-
330
name = scanner.scan(RE_NAME)
-
330
name.rstrip! if name
-
-
330
if scanner.skip(/=/)
-
324
value = scan_value(scanner, comma_as_separator)
-
else
-
6
scan_value(scanner, comma_as_separator)
-
6
value = nil
-
end
-
330
[name, value]
-
end
-
-
6
def call(set_cookie)
-
108
scanner = StringScanner.new(set_cookie)
-
-
# RFC 6265 4.1.1 & 5.2
-
108
until scanner.eos?
-
156
start = scanner.pos
-
156
len = nil
-
-
156
scanner.skip(RE_WSP)
-
-
156
name, value = scan_name_value(scanner, true)
-
156
value = nil if name.empty?
-
-
156
attrs = {}
-
-
156
until scanner.eos?
-
222
if scanner.skip(/,/)
-
# The comma is used as separator for concatenating multiple
-
# values of a header.
-
48
len = (scanner.pos - 1) - start
-
48
break
-
173
elsif scanner.skip(/;/)
-
174
scanner.skip(RE_WSP)
-
-
174
aname, avalue = scan_name_value(scanner, true)
-
-
174
next if aname.empty? || value.nil?
-
-
174
aname.downcase!
-
-
174
case aname
-
when "expires"
-
# RFC 6265 5.2.1
-
12
(avalue &&= Time.parse(avalue)) || next
-
when "max-age"
-
# RFC 6265 5.2.2
-
6
next unless /\A-?\d+\z/.match?(avalue)
-
-
6
avalue = Integer(avalue)
-
when "domain"
-
# RFC 6265 5.2.3
-
# An empty value SHOULD be ignored.
-
18
next if avalue.nil? || avalue.empty?
-
when "path"
-
# RFC 6265 5.2.4
-
# A relative path must be ignored rather than normalizing it
-
# to "/".
-
132
next unless avalue.start_with?("/")
-
when "secure", "httponly"
-
# RFC 6265 5.2.5, 5.2.6
-
5
avalue = true
-
end
-
174
attrs[aname] = avalue
-
end
-
end
-
-
156
len ||= scanner.pos - start
-
-
156
next if len > Cookie::MAX_LENGTH
-
-
156
yield(name, value, attrs) if name && !name.empty? && value
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
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
-
#
-
6
module DigestAuth
-
6
DigestError = Class.new(Error)
-
-
6
class << self
-
6
def extra_options(options)
-
120
options.merge(max_concurrent_requests: 1)
-
end
-
-
6
def load_dependencies(*)
-
120
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.
-
6
module OptionsMethods
-
6
def option_digest(value)
-
240
raise TypeError, ":digest must be a #{Authentication::Digest}" unless value.is_a?(Authentication::Digest)
-
-
240
value
-
end
-
end
-
-
6
module InstanceMethods
-
6
def digest_auth(user, password, hashed: false)
-
120
with(digest: Authentication::Digest.new(user, password, hashed: hashed))
-
end
-
-
6
private
-
-
6
def send_requests(*requests)
-
144
requests.flat_map do |request|
-
144
digest = request.options.digest
-
-
144
next super(request) unless digest
-
-
240
probe_response = wrap { super(request).first }
-
-
120
return probe_response unless probe_response.is_a?(Response)
-
-
120
if probe_response.status == 401 && digest.can_authenticate?(probe_response.headers["www-authenticate"])
-
108
request.transition(:idle)
-
108
request.headers["authorization"] = digest.authenticate(request, probe_response.headers["www-authenticate"])
-
108
super(request)
-
else
-
12
probe_response
-
end
-
end
-
end
-
end
-
end
-
-
6
register_plugin :digest_auth, DigestAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
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
-
#
-
6
module Expect
-
6
EXPECT_TIMEOUT = 2
-
-
6
class << self
-
6
def no_expect_store
-
134
@no_expect_store ||= []
-
end
-
-
6
def extra_options(options)
-
162
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.
-
6
module OptionsMethods
-
6
def option_expect_timeout(value)
-
288
seconds = Float(value)
-
288
raise TypeError, ":expect_timeout must be positive" unless seconds.positive?
-
-
288
seconds
-
end
-
-
6
def option_expect_threshold_size(value)
-
12
bytes = Integer(value)
-
12
raise TypeError, ":expect_threshold_size must be positive" unless bytes.positive?
-
-
12
bytes
-
end
-
end
-
-
6
module RequestMethods
-
6
def initialize(*)
-
186
super
-
186
return if @body.empty?
-
-
126
threshold = @options.expect_threshold_size
-
126
return if threshold && !@body.unbounded_body? && @body.bytesize < threshold
-
-
114
return if Expect.no_expect_store.include?(origin)
-
-
108
@headers["expect"] = "100-continue"
-
end
-
-
6
def response=(response)
-
138
if response.is_a?(Response) &&
-
response.status == 100 &&
-
!@headers.key?("expect") &&
-
1
(@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.
-
7
@headers["expect"] = "100-continue"
-
7
@informational_status = 100
-
7
Expect.no_expect_store.delete(origin)
-
end
-
138
super
-
end
-
end
-
-
6
module ConnectionMethods
-
6
def send_request_to_parser(request)
-
84
super
-
-
84
return unless request.headers["expect"] == "100-continue"
-
-
60
expect_timeout = request.options.expect_timeout
-
-
60
return if expect_timeout.nil? || expect_timeout.infinite?
-
-
60
set_request_timeout(request, expect_timeout, :expect, %i[body response]) do
-
# expect timeout expired
-
13
if request.state == :expect && !request.expects?
-
13
Expect.no_expect_store << request.origin
-
13
request.headers.delete("expect")
-
13
consume
-
end
-
end
-
end
-
end
-
-
6
module InstanceMethods
-
6
def fetch_response(request, selector, options)
-
315
response = super
-
-
315
return unless response
-
-
84
if response.is_a?(Response) && response.status == 417 && request.headers.key?("expect")
-
12
response.close
-
12
request.headers.delete("expect")
-
12
request.transition(:idle)
-
12
send_request(request, selector, options)
-
12
return
-
end
-
-
72
response
-
end
-
end
-
end
-
6
register_plugin :expect, Expect
-
end
-
end
-
# frozen_string_literal: true
-
-
12
module HTTPX
-
12
InsecureRedirectError = Class.new(Error)
-
12
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
-
#
-
12
module FollowRedirects
-
12
MAX_REDIRECTS = 3
-
12
REDIRECT_STATUS = (300..399).freeze
-
12
REQUEST_BODY_HEADERS = %w[transfer-encoding content-encoding content-type content-length content-language content-md5 trailer].freeze
-
-
12
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>.
-
12
module OptionsMethods
-
12
def option_max_redirects(value)
-
350
num = Integer(value)
-
350
raise TypeError, ":max_redirects must be positive" if num.negative?
-
-
350
num
-
end
-
-
12
def option_follow_insecure_redirects(value)
-
18
value
-
end
-
-
12
def option_allow_auth_to_other_origins(value)
-
18
value
-
end
-
-
12
def option_redirect_on(value)
-
36
raise TypeError, ":redirect_on must be callable" unless value.respond_to?(:call)
-
-
36
value
-
end
-
end
-
-
12
module InstanceMethods
-
# returns a session with the *max_redirects* option set to +n+
-
12
def max_redirects(n)
-
36
with(max_redirects: n.to_i)
-
end
-
-
12
private
-
-
12
def fetch_response(request, selector, options)
-
1332179
redirect_request = request.redirect_request
-
1332179
response = super(redirect_request, selector, options)
-
1332179
return unless response
-
-
429
max_redirects = redirect_request.max_redirects
-
-
429
return response unless response.is_a?(Response)
-
417
return response unless REDIRECT_STATUS.include?(response.status) && response.headers.key?("location")
-
273
return response unless max_redirects.positive?
-
-
249
redirect_uri = __get_location_from_response(response)
-
-
249
if options.redirect_on
-
24
redirect_allowed = options.redirect_on.call(redirect_uri)
-
24
return response unless redirect_allowed
-
end
-
-
# build redirect request
-
237
request_body = redirect_request.body
-
237
redirect_method = "GET"
-
237
redirect_params = {}
-
-
237
if response.status == 305 && options.respond_to?(:proxy)
-
6
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.
-
6
redirect_options = options.merge(headers: redirect_request.headers,
-
proxy: { uri: redirect_uri },
-
max_redirects: max_redirects - 1)
-
-
6
redirect_params[:body] = request_body
-
6
redirect_uri = redirect_request.uri
-
6
options = redirect_options
-
else
-
231
redirect_headers = redirect_request_headers(redirect_request.uri, redirect_uri, request.headers, options)
-
231
redirect_opts = Hash[options]
-
231
redirect_params[:max_redirects] = max_redirects - 1
-
-
231
unless request_body.empty?
-
18
if response.status == 307
-
# The method and the body of the original request are reused to perform the redirected request.
-
6
redirect_method = redirect_request.verb
-
6
request_body.rewind
-
6
redirect_params[:body] = request_body
-
else
-
# redirects are **ALWAYS** GET, so remove body-related headers
-
12
REQUEST_BODY_HEADERS.each do |h|
-
84
redirect_headers.delete(h)
-
end
-
12
redirect_params[:body] = nil
-
end
-
end
-
-
231
options = options.class.new(redirect_opts.merge(headers: redirect_headers.to_h))
-
end
-
-
237
redirect_uri = Utils.to_uri(redirect_uri)
-
-
237
if !options.follow_insecure_redirects &&
-
response.uri.scheme == "https" &&
-
redirect_uri.scheme == "http"
-
6
error = InsecureRedirectError.new(redirect_uri.to_s)
-
6
error.set_backtrace(caller)
-
6
return ErrorResponse.new(request, error)
-
end
-
-
231
retry_request = build_request(redirect_method, redirect_uri, redirect_params, options)
-
-
231
request.redirect_request = retry_request
-
-
231
redirect_after = response.headers["retry-after"]
-
-
231
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.
-
#
-
24
redirect_after = Utils.parse_retry_after(redirect_after)
-
-
24
retry_start = Utils.now
-
24
log { "redirecting after #{redirect_after} secs..." }
-
24
selector.after(redirect_after) do
-
24
if request.response
-
# request has terminated abruptly meanwhile
-
12
retry_request.emit(:response, request.response)
-
else
-
12
log { "redirecting (elapsed time: #{Utils.elapsed_time(retry_start)})!!" }
-
12
send_request(retry_request, selector, options)
-
end
-
end
-
else
-
207
send_request(retry_request, selector, options)
-
end
-
37
nil
-
end
-
-
# :nodoc:
-
12
def redirect_request_headers(original_uri, redirect_uri, headers, options)
-
231
headers = headers.dup
-
-
231
return headers if options.allow_auth_to_other_origins
-
-
225
return headers unless headers.key?("authorization")
-
-
6
return headers if original_uri.origin == redirect_uri.origin
-
-
6
headers.delete("authorization")
-
-
6
headers
-
end
-
-
# :nodoc:
-
12
def __get_location_from_response(response)
-
# @type var location_uri: http_uri
-
249
location_uri = URI(response.headers["location"])
-
249
location_uri = response.uri.merge(location_uri) if location_uri.relative?
-
249
location_uri
-
end
-
end
-
-
12
module RequestMethods
-
# returns the top-most original HTTPX::Request from the redirect chain
-
12
attr_accessor :root_request
-
-
# returns the follow-up redirect request, or itself
-
12
def redirect_request
-
1332179
@redirect_request || self
-
end
-
-
# sets the follow-up redirect request
-
12
def redirect_request=(req)
-
231
@redirect_request = req
-
231
req.root_request = @root_request || self
-
231
@response = nil
-
end
-
-
12
def response
-
1444
return super unless @redirect_request && @response.nil?
-
-
58
@redirect_request.response
-
end
-
-
12
def max_redirects
-
429
@options.max_redirects || MAX_REDIRECTS
-
end
-
end
-
-
12
module ConnectionMethods
-
12
private
-
-
12
def set_request_request_timeout(request)
-
407
return unless request.root_request.nil?
-
-
193
super
-
end
-
end
-
end
-
12
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
-
-
6
module HTTPX
-
6
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
-
#
-
6
module H2C
-
6
VALID_H2C_VERBS = %w[GET OPTIONS HEAD].freeze
-
-
6
class << self
-
6
def load_dependencies(klass)
-
12
klass.plugin(:upgrade)
-
end
-
-
6
def call(connection, request, response)
-
12
connection.upgrade_to_h2c(request, response)
-
end
-
-
6
def extra_options(options)
-
12
options.merge(max_concurrent_requests: 1, upgrade_handlers: options.upgrade_handlers.merge("h2c" => self))
-
end
-
end
-
-
6
class H2CParser < Connection::HTTP2
-
6
def upgrade(request, response)
-
# skip checks, it is assumed that this is the first
-
# request in the connection
-
12
stream = @connection.upgrade
-
-
# on_settings
-
12
handle_stream(stream, request)
-
12
@streams[request] = stream
-
-
# clean up data left behind in the buffer, if the server started
-
# sending frames
-
12
data = response.read
-
12
@connection << data
-
end
-
end
-
-
6
module ConnectionMethods
-
6
using URIExtensions
-
-
6
def initialize(*)
-
12
super
-
12
@h2c_handshake = false
-
end
-
-
6
def send(request)
-
42
return super if @h2c_handshake
-
-
12
return super unless VALID_H2C_VERBS.include?(request.verb) && request.scheme == "http"
-
-
12
return super if @upgrade_protocol == "h2c"
-
-
12
@h2c_handshake = true
-
-
# build upgrade request
-
12
request.headers.add("connection", "upgrade")
-
12
request.headers.add("connection", "http2-settings")
-
12
request.headers["upgrade"] = "h2c"
-
12
request.headers["http2-settings"] = ::HTTP2::Client.settings_header(request.options.http2_settings)
-
-
12
super
-
end
-
-
6
def upgrade_to_h2c(request, response)
-
12
prev_parser = @parser
-
-
12
if prev_parser
-
12
prev_parser.reset
-
12
@inflight -= prev_parser.requests.size
-
end
-
-
12
@parser = H2CParser.new(@write_buffer, @options)
-
12
set_parser_callbacks(@parser)
-
12
@inflight += 1
-
12
@parser.upgrade(request, response)
-
12
@upgrade_protocol = "h2c"
-
-
12
prev_parser.requests.each do |req|
-
12
req.transition(:idle)
-
12
send(req)
-
end
-
end
-
-
6
private
-
-
6
def send_request_to_parser(request)
-
42
super
-
-
42
return unless request.headers["upgrade"] == "h2c" && parser.is_a?(Connection::HTTP1)
-
-
12
max_concurrent_requests = parser.max_concurrent_requests
-
-
12
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
-
6
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
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# https://gitlab.com/os85/httpx/wikis/OAuth
-
#
-
6
module OAuth
-
6
class << self
-
6
def load_dependencies(_klass)
-
108
require_relative "auth/basic"
-
end
-
end
-
-
6
SUPPORTED_GRANT_TYPES = %w[client_credentials refresh_token].freeze
-
6
SUPPORTED_AUTH_METHODS = %w[client_secret_basic client_secret_post].freeze
-
-
6
class OAuthSession
-
6
attr_reader :grant_type, :client_id, :client_secret, :access_token, :refresh_token, :scope
-
-
6
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
-
)
-
96
@issuer = URI(issuer)
-
96
@client_id = client_id
-
96
@client_secret = client_secret
-
96
@token_endpoint = URI(token_endpoint) if token_endpoint
-
96
@response_type = response_type
-
96
@scope = case scope
-
when String
-
36
scope.split
-
when Array
-
24
scope
-
end
-
96
@access_token = access_token
-
96
@refresh_token = refresh_token
-
96
@token_endpoint_auth_method = String(token_endpoint_auth_method) if token_endpoint_auth_method
-
96
@grant_type = grant_type || (@refresh_token ? "refresh_token" : "client_credentials")
-
-
96
unless @token_endpoint_auth_method.nil? || SUPPORTED_AUTH_METHODS.include?(@token_endpoint_auth_method)
-
12
raise Error, "#{@token_endpoint_auth_method} is not a supported auth method"
-
end
-
-
84
return if SUPPORTED_GRANT_TYPES.include?(@grant_type)
-
-
12
raise Error, "#{@grant_type} is not a supported grant type"
-
end
-
-
6
def token_endpoint
-
84
@token_endpoint || "#{@issuer}/token"
-
end
-
-
6
def token_endpoint_auth_method
-
120
@token_endpoint_auth_method || "client_secret_basic"
-
end
-
-
6
def load(http)
-
36
return if @grant_type && @scope
-
-
12
metadata = http.get("#{@issuer}/.well-known/oauth-authorization-server").raise_for_status.json
-
-
12
@token_endpoint = metadata["token_endpoint"]
-
12
@scope = metadata["scopes_supported"]
-
48
@grant_type = Array(metadata["grant_types_supported"]).find { |gr| SUPPORTED_GRANT_TYPES.include?(gr) }
-
12
@token_endpoint_auth_method = Array(metadata["token_endpoint_auth_methods_supported"]).find do |am|
-
12
SUPPORTED_AUTH_METHODS.include?(am)
-
end
-
2
nil
-
end
-
-
6
def merge(other)
-
72
obj = dup
-
-
72
case other
-
when OAuthSession
-
36
other.instance_variables.each do |ivar|
-
324
val = other.instance_variable_get(ivar)
-
324
next unless val
-
-
252
obj.instance_variable_set(ivar, val)
-
end
-
when Hash
-
36
other.each do |k, v|
-
72
obj.instance_variable_set(:"@#{k}", v) if obj.instance_variable_defined?(:"@#{k}")
-
end
-
end
-
72
obj
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_oauth_session(value)
-
228
case value
-
when Hash
-
12
OAuthSession.new(**value)
-
when OAuthSession
-
204
value
-
else
-
12
raise TypeError, ":oauth_session must be a #{OAuthSession}"
-
end
-
end
-
end
-
-
6
module InstanceMethods
-
6
def oauth_auth(**args)
-
84
with(oauth_session: OAuthSession.new(**args))
-
end
-
-
6
def with_access_token
-
36
oauth_session = @options.oauth_session
-
-
36
oauth_session.load(self)
-
-
36
grant_type = oauth_session.grant_type
-
-
36
headers = {}
-
36
form_post = { "grant_type" => grant_type, "scope" => Array(oauth_session.scope).join(" ") }.compact
-
-
# auth
-
36
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"
-
24
headers["authorization"] = Authentication::Basic.new(oauth_session.client_id, oauth_session.client_secret).authenticate
-
end
-
-
36
case grant_type
-
when "client_credentials"
-
# do nothing
-
when "refresh_token"
-
12
form_post["refresh_token"] = oauth_session.refresh_token
-
end
-
-
36
token_request = build_request("POST", oauth_session.token_endpoint, headers: headers, form: form_post)
-
36
token_request.headers.delete("authorization") unless oauth_session.token_endpoint_auth_method == "client_secret_basic"
-
-
36
token_response = request(token_request)
-
36
token_response.raise_for_status
-
-
36
payload = token_response.json
-
-
36
access_token = payload["access_token"]
-
36
refresh_token = payload["refresh_token"]
-
-
36
with(oauth_session: oauth_session.merge(access_token: access_token, refresh_token: refresh_token))
-
end
-
-
6
def build_request(*)
-
96
request = super
-
-
96
return request if request.headers.key?("authorization")
-
-
72
oauth_session = @options.oauth_session
-
-
72
return request unless oauth_session && oauth_session.access_token
-
-
48
request.headers["authorization"] = "Bearer #{oauth_session.access_token}"
-
-
48
request
-
end
-
end
-
end
-
6
register_plugin :oauth, OAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
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
-
#
-
8
module Persistent
-
8
def self.load_dependencies(klass)
-
314
max_retries = if klass.default_options.respond_to?(:max_retries)
-
6
[klass.default_options.max_retries, 1].max
-
else
-
308
1
-
end
-
314
klass.plugin(:retries, max_retries: max_retries, retry_change_requests: true)
-
end
-
-
8
def self.extra_options(options)
-
314
options.merge(persistent: true)
-
end
-
-
8
module InstanceMethods
-
8
private
-
-
8
def get_current_selector
-
298
super(&nil) || begin
-
292
return unless block_given?
-
-
292
default = yield
-
-
292
set_current_selector(default)
-
-
292
default
-
end
-
end
-
end
-
end
-
8
register_plugin :persistent, Persistent
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
class HTTPProxyError < ConnectionError; end
-
-
8
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
-
#
-
8
module Proxy
-
8
Error = HTTPProxyError
-
8
PROXY_ERRORS = [TimeoutError, IOError, SystemCallError, Error].freeze
-
-
8
class << self
-
8
def configure(klass)
-
254
klass.plugin(:"proxy/http")
-
254
klass.plugin(:"proxy/socks4")
-
254
klass.plugin(:"proxy/socks5")
-
end
-
-
8
def extra_options(options)
-
254
options.merge(supported_proxy_protocols: [])
-
end
-
end
-
-
8
class Parameters
-
8
attr_reader :uri, :username, :password, :scheme, :no_proxy
-
-
8
def initialize(uri: nil, scheme: nil, username: nil, password: nil, no_proxy: nil, **extra)
-
280
@no_proxy = Array(no_proxy) if no_proxy
-
280
@uris = Array(uri)
-
280
uri = @uris.first
-
-
280
@username = username
-
280
@password = password
-
-
280
@ns = 0
-
-
280
if uri
-
250
@uri = uri.is_a?(URI::Generic) ? uri : URI(uri)
-
250
@username ||= @uri.user
-
250
@password ||= @uri.password
-
end
-
-
280
@scheme = scheme
-
-
280
return unless @uri && @username && @password
-
-
159
@authenticator = nil
-
159
@scheme ||= infer_default_auth_scheme(@uri)
-
-
159
return unless @scheme
-
-
123
@authenticator = load_authenticator(@scheme, @username, @password, **extra)
-
end
-
-
8
def shift
-
# TODO: this operation must be synchronized
-
90
@ns += 1
-
90
@uri = @uris[@ns]
-
-
90
return unless @uri
-
-
12
@uri = URI(@uri) unless @uri.is_a?(URI::Generic)
-
-
12
scheme = infer_default_auth_scheme(@uri)
-
-
12
return unless scheme != @scheme
-
-
12
@scheme = scheme
-
12
@username = username || @uri.user
-
12
@password = password || @uri.password
-
12
@authenticator = load_authenticator(scheme, @username, @password)
-
end
-
-
8
def can_authenticate?(*args)
-
138
return false unless @authenticator
-
-
48
@authenticator.can_authenticate?(*args)
-
end
-
-
8
def authenticate(*args)
-
121
return unless @authenticator
-
-
121
@authenticator.authenticate(*args)
-
end
-
-
8
def ==(other)
-
329
case other
-
when Parameters
-
299
@uri == other.uri &&
-
@username == other.username &&
-
@password == other.password &&
-
@scheme == other.scheme
-
when URI::Generic, String
-
18
proxy_uri = @uri.dup
-
18
proxy_uri.user = @username
-
18
proxy_uri.password = @password
-
18
other_uri = other.is_a?(URI::Generic) ? other : URI.parse(other)
-
18
proxy_uri == other_uri
-
else
-
12
super
-
end
-
end
-
-
8
private
-
-
8
def infer_default_auth_scheme(uri)
-
159
case uri.scheme
-
when "socks5"
-
36
uri.scheme
-
when "http", "https"
-
74
"basic"
-
end
-
end
-
-
8
def load_authenticator(scheme, username, password, **extra)
-
135
auth_scheme = scheme.to_s.capitalize
-
-
135
require_relative "auth/#{scheme}" unless defined?(Authentication) && Authentication.const_defined?(auth_scheme, false)
-
-
135
Authentication.const_get(auth_scheme).new(username, password, **extra)
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :proxy :: proxy options defining *:uri*, *:username*, *:password* or
-
# *:scheme* (i.e. <tt>{ uri: "http://proxy" }</tt>)
-
8
module OptionsMethods
-
8
def option_proxy(value)
-
507
value.is_a?(Parameters) ? value : Parameters.new(**Hash[value])
-
end
-
-
8
def option_supported_proxy_protocols(value)
-
1281
raise TypeError, ":supported_proxy_protocols must be an Array" unless value.is_a?(Array)
-
-
1281
value.map(&:to_s)
-
end
-
end
-
-
8
module InstanceMethods
-
8
def find_connection(request_uri, selector, options)
-
316
return super unless options.respond_to?(:proxy)
-
-
316
if (next_proxy = request_uri.find_proxy)
-
4
return super(request_uri, selector, options.merge(proxy: Parameters.new(uri: next_proxy)))
-
end
-
-
312
proxy = options.proxy
-
-
312
return super unless proxy
-
-
304
next_proxy = proxy.uri
-
-
304
raise Error, "Failed to connect to proxy" unless next_proxy
-
-
raise Error,
-
292
"#{next_proxy.scheme}: unsupported proxy protocol" unless options.supported_proxy_protocols.include?(next_proxy.scheme)
-
-
286
if (no_proxy = proxy.no_proxy)
-
12
no_proxy = no_proxy.join(",") if no_proxy.is_a?(Array)
-
-
# TODO: setting proxy to nil leaks the connection object in the pool
-
12
return super(request_uri, selector, options.merge(proxy: nil)) unless URI::Generic.use_proxy?(request_uri.host, next_proxy.host,
-
next_proxy.port, no_proxy)
-
end
-
-
280
super(request_uri, selector, options.merge(proxy: proxy))
-
end
-
-
8
private
-
-
8
def fetch_response(request, selector, options)
-
1160
response = super
-
-
1160
if response.is_a?(ErrorResponse) && proxy_error?(request, response, options)
-
90
options.proxy.shift
-
-
# return last error response if no more proxies to try
-
90
return response if options.proxy.uri.nil?
-
-
12
log { "failed connecting to proxy, trying next..." }
-
12
request.transition(:idle)
-
12
send_request(request, selector, options)
-
12
return
-
end
-
1070
response
-
end
-
-
8
def proxy_error?(_request, response, options)
-
127
return false unless options.proxy
-
-
126
error = response.error
-
126
case error
-
when NativeResolveError
-
12
proxy_uri = URI(options.proxy.uri)
-
-
12
peer = error.connection.peer
-
-
# failed resolving proxy domain
-
12
peer.host == proxy_uri.host && peer.port == proxy_uri.port
-
when ResolveError
-
proxy_uri = URI(options.proxy.uri)
-
-
error.message.end_with?(proxy_uri.to_s)
-
when *PROXY_ERRORS
-
# timeout errors connecting to proxy
-
114
true
-
else
-
false
-
end
-
end
-
end
-
-
8
module ConnectionMethods
-
8
using URIExtensions
-
-
8
def initialize(*)
-
291
super
-
291
return unless @options.proxy
-
-
# redefining the connection origin as the proxy's URI,
-
# as this will be used as the tcp peer ip.
-
277
@proxy_uri = URI(@options.proxy.uri)
-
end
-
-
8
def peer
-
805
@proxy_uri || super
-
end
-
-
8
def connecting?
-
3448
return super unless @options.proxy
-
-
3329
super || @state == :connecting || @state == :connected
-
end
-
-
8
def call
-
794
super
-
-
794
return unless @options.proxy
-
-
768
case @state
-
when :connecting
-
160
consume
-
end
-
end
-
-
8
def reset
-
302
return super unless @options.proxy
-
-
289
@state = :open
-
-
289
super
-
# emit(:close)
-
end
-
-
8
private
-
-
8
def initialize_type(uri, options)
-
291
return super unless options.proxy
-
-
277
"tcp"
-
end
-
-
8
def connect
-
793
return super unless @options.proxy
-
-
767
case @state
-
when :idle
-
538
transition(:connecting)
-
when :connected
-
229
transition(:open)
-
end
-
end
-
-
8
def handle_transition(nextstate)
-
1630
return super unless @options.proxy
-
-
1563
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
-
295
@state = :open if @state == :connecting
-
end
-
1563
super
-
end
-
end
-
end
-
8
register_plugin :proxy, Proxy
-
end
-
-
8
class ProxySSL < SSL
-
8
def initialize(tcp, request_uri, options)
-
68
@io = tcp.to_io
-
68
super(request_uri, tcp.addresses, options)
-
68
@hostname = request_uri.host
-
68
@state = :connected
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
module Plugins
-
8
module Proxy
-
8
module HTTP
-
8
class << self
-
8
def extra_options(options)
-
254
options.merge(supported_proxy_protocols: options.supported_proxy_protocols + %w[http])
-
end
-
end
-
-
8
module InstanceMethods
-
8
def with_proxy_basic_auth(opts)
-
6
with(proxy: opts.merge(scheme: "basic"))
-
end
-
-
8
def with_proxy_digest_auth(opts)
-
18
with(proxy: opts.merge(scheme: "digest"))
-
end
-
-
8
def with_proxy_ntlm_auth(opts)
-
6
with(proxy: opts.merge(scheme: "ntlm"))
-
end
-
-
8
def fetch_response(request, selector, options)
-
1160
response = super
-
-
1160
if response &&
-
response.is_a?(Response) &&
-
response.status == 407 &&
-
!request.headers.key?("proxy-authorization") &&
-
response.headers.key?("proxy-authenticate") && options.proxy.can_authenticate?(response.headers["proxy-authenticate"])
-
6
request.transition(:idle)
-
6
request.headers["proxy-authorization"] =
-
options.proxy.authenticate(request, response.headers["proxy-authenticate"])
-
6
send_request(request, selector, options)
-
6
return
-
end
-
-
1154
response
-
end
-
end
-
-
8
module ConnectionMethods
-
8
def connecting?
-
3448
super || @state == :connecting || @state == :connected
-
end
-
-
8
private
-
-
8
def handle_transition(nextstate)
-
1812
return super unless @options.proxy && @options.proxy.uri.scheme == "http"
-
-
900
case nextstate
-
when :connecting
-
232
return unless @state == :idle
-
-
232
@io.connect
-
232
return unless @io.connected?
-
-
116
@parser || begin
-
110
@parser = self.class.parser_type(@io.protocol).new(@write_buffer, @options.merge(max_concurrent_requests: 1))
-
110
parser = @parser
-
110
parser.extend(ProxyParser)
-
110
parser.on(:response, &method(:__http_on_connect))
-
110
parser.on(:close) do |force|
-
44
next unless @parser
-
-
6
if force
-
6
reset
-
6
emit(:terminate)
-
end
-
end
-
110
parser.on(:reset) do
-
12
if parser.empty?
-
6
reset
-
else
-
6
transition(:closing)
-
6
transition(:closed)
-
-
6
parser.reset if @parser
-
6
transition(:idle)
-
6
transition(:connecting)
-
end
-
end
-
110
__http_proxy_connect(parser)
-
end
-
116
return if @state == :connected
-
when :connected
-
104
return unless @state == :idle || @state == :connecting
-
-
104
case @state
-
when :connecting
-
38
parser = @parser
-
38
@parser = nil
-
38
parser.close
-
when :idle
-
66
@parser.callbacks.clear
-
66
set_parser_callbacks(@parser)
-
end
-
end
-
718
super
-
end
-
-
8
def __http_proxy_connect(parser)
-
110
req = @pending.first
-
110
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.
-
#
-
44
connect_request = ConnectRequest.new(req.uri, @options)
-
44
@inflight += 1
-
44
parser.send(connect_request)
-
else
-
66
handle_transition(:connected)
-
end
-
end
-
-
8
def __http_on_connect(request, response)
-
50
@inflight -= 1
-
50
if response.is_a?(Response) && response.status == 200
-
38
req = @pending.first
-
38
request_uri = req.uri
-
38
@io = ProxySSL.new(@io, request_uri, @options)
-
38
transition(:connected)
-
38
throw(:called)
-
11
elsif response.is_a?(Response) &&
-
response.status == 407 &&
-
!request.headers.key?("proxy-authorization") &&
-
@options.proxy.can_authenticate?(response.headers["proxy-authenticate"])
-
-
6
request.transition(:idle)
-
6
request.headers["proxy-authorization"] = @options.proxy.authenticate(request, response.headers["proxy-authenticate"])
-
6
@parser.send(request)
-
6
@inflight += 1
-
else
-
6
pending = @pending + @parser.pending
-
16
while (req = pending.shift)
-
6
req.emit(:response, response)
-
end
-
6
reset
-
end
-
end
-
end
-
-
8
module ProxyParser
-
8
def join_headline(request)
-
110
return super if request.verb == "CONNECT"
-
-
60
"#{request.verb} #{request.uri} HTTP/#{@version.join(".")}"
-
end
-
-
8
def set_protocol_headers(request)
-
116
extra_headers = super
-
-
116
proxy_params = @options.proxy
-
116
if proxy_params.scheme == "basic"
-
# opt for basic auth
-
73
extra_headers["proxy-authorization"] = proxy_params.authenticate(extra_headers)
-
end
-
116
extra_headers["proxy-connection"] = extra_headers.delete("connection") if extra_headers.key?("connection")
-
116
extra_headers
-
end
-
end
-
-
8
class ConnectRequest < Request
-
8
def initialize(uri, options)
-
44
super("CONNECT", uri, options)
-
44
@headers.delete("accept")
-
end
-
-
8
def path
-
56
"#{@uri.hostname}:#{@uri.port}"
-
end
-
end
-
end
-
end
-
8
register_plugin :"proxy/http", Proxy::HTTP
-
end
-
end
-
# frozen_string_literal: true
-
-
8
require "resolv"
-
8
require "ipaddr"
-
-
8
module HTTPX
-
8
class Socks4Error < HTTPProxyError; end
-
-
8
module Plugins
-
8
module Proxy
-
8
module Socks4
-
8
VERSION = 4
-
8
CONNECT = 1
-
8
GRANTED = 0x5A
-
8
PROTOCOLS = %w[socks4 socks4a].freeze
-
-
8
Error = Socks4Error
-
-
8
class << self
-
8
def extra_options(options)
-
254
options.merge(supported_proxy_protocols: options.supported_proxy_protocols + PROTOCOLS)
-
end
-
end
-
-
8
module ConnectionMethods
-
8
def interests
-
2922
if @state == :connecting
-
return @write_buffer.empty? ? :r : :w
-
end
-
-
2922
super
-
end
-
-
8
private
-
-
8
def handle_transition(nextstate)
-
1860
return super unless @options.proxy && PROTOCOLS.include?(@options.proxy.uri.scheme)
-
-
329
case nextstate
-
when :connecting
-
96
return unless @state == :idle
-
-
96
@io.connect
-
96
return unless @io.connected?
-
-
48
req = @pending.first
-
48
return unless req
-
-
48
request_uri = req.uri
-
48
@write_buffer << Packet.connect(@options.proxy, request_uri)
-
48
__socks4_proxy_connect
-
when :connected
-
36
return unless @state == :connecting
-
-
36
@parser = nil
-
end
-
281
log(level: 1) { "SOCKS4: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
-
281
super
-
end
-
-
8
def __socks4_proxy_connect
-
48
@parser = SocksParser.new(@write_buffer, @options)
-
48
@parser.once(:packet, &method(:__socks4_on_packet))
-
end
-
-
8
def __socks4_on_packet(packet)
-
48
_version, status, _port, _ip = packet.unpack("CCnN")
-
48
if status == GRANTED
-
36
req = @pending.first
-
36
request_uri = req.uri
-
36
@io = ProxySSL.new(@io, request_uri, @options) if request_uri.scheme == "https"
-
36
transition(:connected)
-
36
throw(:called)
-
else
-
12
on_socks4_error("socks error: #{status}")
-
end
-
end
-
-
8
def on_socks4_error(message)
-
12
ex = Error.new(message)
-
12
ex.set_backtrace(caller)
-
12
on_error(ex)
-
12
throw(:called)
-
end
-
end
-
-
8
class SocksParser
-
8
include HTTPX::Callbacks
-
-
8
def initialize(buffer, options)
-
48
@buffer = buffer
-
48
@options = options
-
end
-
-
8
def close; end
-
-
8
def consume(*); end
-
-
8
def empty?
-
true
-
end
-
-
8
def <<(packet)
-
48
emit(:packet, packet)
-
end
-
end
-
-
8
module Packet
-
8
module_function
-
-
8
def connect(parameters, uri)
-
48
packet = [VERSION, CONNECT, uri.port].pack("CCn")
-
-
48
case parameters.uri.scheme
-
when "socks4"
-
36
socks_host = uri.host
-
5
begin
-
72
ip = IPAddr.new(socks_host)
-
36
packet << ip.hton
-
rescue IPAddr::InvalidAddressError
-
36
socks_host = Resolv.getaddress(socks_host)
-
36
retry
-
end
-
36
packet << [parameters.username].pack("Z*")
-
when "socks4a"
-
12
packet << "\x0\x0\x0\x1" << [parameters.username].pack("Z*") << uri.host << "\x0"
-
end
-
48
packet
-
end
-
end
-
end
-
end
-
8
register_plugin :"proxy/socks4", Proxy::Socks4
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
class Socks5Error < HTTPProxyError; end
-
-
8
module Plugins
-
8
module Proxy
-
8
module Socks5
-
8
VERSION = 5
-
8
NOAUTH = 0
-
8
PASSWD = 2
-
8
NONE = 0xff
-
8
CONNECT = 1
-
8
IPV4 = 1
-
8
DOMAIN = 3
-
8
IPV6 = 4
-
8
SUCCESS = 0
-
-
8
Error = Socks5Error
-
-
8
class << self
-
8
def load_dependencies(*)
-
254
require_relative "../auth/socks5"
-
end
-
-
8
def extra_options(options)
-
254
options.merge(supported_proxy_protocols: options.supported_proxy_protocols + %w[socks5])
-
end
-
end
-
-
8
module ConnectionMethods
-
8
def call
-
794
super
-
-
794
return unless @options.proxy && @options.proxy.uri.scheme == "socks5"
-
-
237
case @state
-
when :connecting,
-
:negotiating,
-
:authenticating
-
81
consume
-
end
-
end
-
-
8
def connecting?
-
3448
super || @state == :authenticating || @state == :negotiating
-
end
-
-
8
def interests
-
4603
if @state == :connecting || @state == :authenticating || @state == :negotiating
-
1681
return @write_buffer.empty? ? :r : :w
-
end
-
-
2922
super
-
end
-
-
8
private
-
-
8
def handle_transition(nextstate)
-
2076
return super unless @options.proxy && @options.proxy.uri.scheme == "socks5"
-
-
780
case nextstate
-
when :connecting
-
216
return unless @state == :idle
-
-
216
@io.connect
-
216
return unless @io.connected?
-
-
108
@write_buffer << Packet.negotiate(@options.proxy)
-
108
__socks5_proxy_connect
-
when :authenticating
-
36
return unless @state == :connecting
-
-
36
@write_buffer << Packet.authenticate(@options.proxy)
-
when :negotiating
-
144
return unless @state == :connecting || @state == :authenticating
-
-
36
req = @pending.first
-
36
request_uri = req.uri
-
36
@write_buffer << Packet.connect(request_uri)
-
when :connected
-
24
return unless @state == :negotiating
-
-
24
@parser = nil
-
end
-
564
log(level: 1) { "SOCKS5: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
-
564
super
-
end
-
-
8
def __socks5_proxy_connect
-
108
@parser = SocksParser.new(@write_buffer, @options)
-
108
@parser.on(:packet, &method(:__socks5_on_packet))
-
108
transition(:negotiating)
-
end
-
-
8
def __socks5_on_packet(packet)
-
180
case @state
-
when :connecting
-
108
version, method = packet.unpack("CC")
-
108
__socks5_check_version(version)
-
108
case method
-
when PASSWD
-
36
transition(:authenticating)
-
6
nil
-
when NONE
-
60
__on_socks5_error("no supported authorization methods")
-
else
-
12
transition(:negotiating)
-
end
-
when :authenticating
-
36
_, status = packet.unpack("CC")
-
36
return transition(:negotiating) if status == SUCCESS
-
-
12
__on_socks5_error("socks authentication error: #{status}")
-
when :negotiating
-
36
version, reply, = packet.unpack("CC")
-
36
__socks5_check_version(version)
-
36
__on_socks5_error("socks5 negotiation error: #{reply}") unless reply == SUCCESS
-
24
req = @pending.first
-
24
request_uri = req.uri
-
24
@io = ProxySSL.new(@io, request_uri, @options) if request_uri.scheme == "https"
-
24
transition(:connected)
-
24
throw(:called)
-
end
-
end
-
-
8
def __socks5_check_version(version)
-
144
__on_socks5_error("invalid SOCKS version (#{version})") if version != 5
-
end
-
-
8
def __on_socks5_error(message)
-
84
ex = Error.new(message)
-
84
ex.set_backtrace(caller)
-
84
on_error(ex)
-
84
throw(:called)
-
end
-
end
-
-
8
class SocksParser
-
8
include HTTPX::Callbacks
-
-
8
def initialize(buffer, options)
-
108
@buffer = buffer
-
108
@options = options
-
end
-
-
8
def close; end
-
-
8
def consume(*); end
-
-
8
def empty?
-
true
-
end
-
-
8
def <<(packet)
-
180
emit(:packet, packet)
-
end
-
end
-
-
8
module Packet
-
8
module_function
-
-
8
def negotiate(parameters)
-
108
methods = [NOAUTH]
-
108
methods << PASSWD if parameters.can_authenticate?
-
108
methods.unshift(methods.size)
-
108
methods.unshift(VERSION)
-
108
methods.pack("C*")
-
end
-
-
8
def authenticate(parameters)
-
36
parameters.authenticate
-
end
-
-
8
def connect(uri)
-
36
packet = [VERSION, CONNECT, 0].pack("C*")
-
5
begin
-
36
ip = IPAddr.new(uri.host)
-
-
12
ipcode = ip.ipv6? ? IPV6 : IPV4
-
-
12
packet << [ipcode].pack("C") << ip.hton
-
rescue IPAddr::InvalidAddressError
-
24
packet << [DOMAIN, uri.host.bytesize, uri.host].pack("CCA*")
-
end
-
36
packet << [uri.port].pack("n")
-
36
packet
-
end
-
end
-
end
-
end
-
8
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
-
-
6
module HTTPX
-
6
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
-
#
-
6
module PushPromise
-
6
def self.extra_options(options)
-
12
options.merge(http2_settings: { settings_enable_push: 1 },
-
max_concurrent_requests: 1)
-
end
-
-
6
module ResponseMethods
-
6
def pushed?
-
12
@__pushed
-
end
-
-
6
def mark_as_pushed!
-
6
@__pushed = true
-
end
-
end
-
-
6
module InstanceMethods
-
6
private
-
-
6
def promise_headers
-
12
@promise_headers ||= {}
-
end
-
-
6
def on_promise(parser, stream)
-
12
stream.on(:promise_headers) do |h|
-
12
__on_promise_request(parser, stream, h)
-
end
-
12
stream.on(:headers) do |h|
-
6
__on_promise_response(parser, stream, h)
-
end
-
end
-
-
6
def __on_promise_request(parser, stream, h)
-
12
log(level: 1, color: :yellow) do
-
skipped
# :nocov:
-
skipped
h.map { |k, v| "#{stream.id}: -> PROMISE HEADER: #{k}: #{v}" }.join("\n")
-
skipped
# :nocov:
-
end
-
12
headers = @options.headers_class.new(h)
-
12
path = headers[":path"]
-
12
authority = headers[":authority"]
-
-
18
request = parser.pending.find { |r| r.authority == authority && r.path == path }
-
12
if request
-
6
request.merge_headers(headers)
-
6
promise_headers[stream] = request
-
6
parser.pending.delete(request)
-
6
parser.streams[request] = stream
-
6
request.transition(:done)
-
else
-
6
stream.refuse
-
end
-
end
-
-
6
def __on_promise_response(parser, stream, h)
-
6
request = promise_headers.delete(stream)
-
6
return unless request
-
-
6
parser.__send__(:on_stream_headers, stream, request, h)
-
6
response = request.response
-
6
response.mark_as_pushed!
-
6
stream.on(:data, &parser.method(:on_stream_data).curry(3)[stream, request])
-
6
stream.on(:close, &parser.method(:on_stream_close).curry(3)[stream, request])
-
end
-
end
-
end
-
6
register_plugin(:push_promise, PushPromise)
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
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
-
#
-
6
module RateLimiter
-
6
class << self
-
6
RATE_LIMIT_CODES = [429, 503].freeze
-
-
6
def configure(klass)
-
48
klass.plugin(:retries,
-
retry_change_requests: true,
-
7
retry_on: method(:retry_on_rate_limited_response),
-
retry_after: method(:retry_after_rate_limit))
-
end
-
-
6
def retry_on_rate_limited_response(response)
-
96
return false unless response.is_a?(Response)
-
-
96
status = response.status
-
-
96
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.
-
#
-
6
def retry_after_rate_limit(_, response)
-
48
return unless response.is_a?(Response)
-
-
48
retry_after = response.headers["retry-after"]
-
-
48
return unless retry_after
-
-
24
Utils.parse_retry_after(retry_after)
-
end
-
end
-
end
-
-
6
register_plugin :rate_limiter, RateLimiter
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds support for retrying requests when certain errors happen.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Response-Cache
-
#
-
6
module ResponseCache
-
6
CACHEABLE_VERBS = %w[GET HEAD].freeze
-
6
CACHEABLE_STATUS_CODES = [200, 203, 206, 300, 301, 410].freeze
-
6
private_constant :CACHEABLE_VERBS
-
6
private_constant :CACHEABLE_STATUS_CODES
-
-
6
class << self
-
6
def load_dependencies(*)
-
132
require_relative "response_cache/store"
-
end
-
-
6
def cacheable_request?(request)
-
186
CACHEABLE_VERBS.include?(request.verb) &&
-
(
-
186
!request.headers.key?("cache-control") || !request.headers.get("cache-control").include?("no-store")
-
)
-
end
-
-
6
def cacheable_response?(response)
-
126
response.is_a?(Response) &&
-
(
-
126
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 && (
-
95
response.headers.key?("etag") || response.headers.key?("last-modified") || response.fresh?
-
)
-
end
-
-
6
def cached_response?(response)
-
60
response.is_a?(Response) && response.status == 304
-
end
-
-
6
def extra_options(options)
-
132
options.merge(response_cache_store: Store.new)
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_response_cache_store(value)
-
132
raise TypeError, "must be an instance of #{Store}" unless value.is_a?(Store)
-
-
132
value
-
end
-
end
-
-
6
module InstanceMethods
-
6
def clear_response_cache
-
12
@options.response_cache_store.clear
-
end
-
-
6
def build_request(*)
-
60
request = super
-
60
return request unless ResponseCache.cacheable_request?(request) && @options.response_cache_store.cached?(request)
-
-
24
@options.response_cache_store.prepare(request)
-
-
24
request
-
end
-
-
6
def fetch_response(request, *)
-
208
response = super
-
-
208
return unless response
-
-
60
if ResponseCache.cached_response?(response)
-
24
log { "returning cached response for #{request.uri}" }
-
24
cached_response = @options.response_cache_store.lookup(request)
-
-
24
response.copy_from_cached(cached_response)
-
-
else
-
36
@options.response_cache_store.cache(request, response)
-
end
-
-
60
response
-
end
-
end
-
-
6
module RequestMethods
-
6
def response_cache_key
-
384
@response_cache_key ||= Digest::SHA1.hexdigest("httpx-response-cache-#{@verb}-#{@uri}")
-
end
-
end
-
-
6
module ResponseMethods
-
6
def copy_from_cached(other)
-
# 304 responses do not have content-type, which are needed for decoding.
-
24
@headers = @headers.class.new(other.headers.merge(@headers))
-
-
24
@body = other.body.dup
-
-
24
@body.rewind
-
end
-
-
# A response is fresh if its age has not yet exceeded its freshness lifetime.
-
6
def fresh?
-
192
if cache_control
-
30
return false if cache_control.include?("no-cache")
-
-
# check age: max-age
-
36
max_age = cache_control.find { |directive| directive.start_with?("s-maxage") }
-
-
36
max_age ||= cache_control.find { |directive| directive.start_with?("max-age") }
-
-
18
max_age = max_age[/age=(\d+)/, 1] if max_age
-
-
18
max_age = max_age.to_i if max_age
-
-
18
return max_age > age if max_age
-
end
-
-
# check age: expires
-
162
if @headers.key?("expires")
-
2
begin
-
18
expires = Time.httpdate(@headers["expires"])
-
rescue ArgumentError
-
6
return true
-
end
-
-
12
return (expires - Time.now).to_i.positive?
-
end
-
-
144
true
-
end
-
-
6
def cache_control
-
414
return @cache_control if defined?(@cache_control)
-
-
@cache_control = begin
-
288
return unless @headers.key?("cache-control")
-
-
30
@headers["cache-control"].split(/ *, */)
-
end
-
end
-
-
6
def vary
-
210
return @vary if defined?(@vary)
-
-
@vary = begin
-
168
return unless @headers.key?("vary")
-
-
12
@headers["vary"].split(/ *, */)
-
end
-
end
-
-
6
private
-
-
6
def age
-
18
return @headers["age"].to_i if @headers.key?("age")
-
-
18
(Time.now - date).to_i
-
end
-
-
6
def date
-
18
@date ||= Time.httpdate(@headers["date"])
-
rescue NoMethodError, ArgumentError
-
6
Time.now
-
end
-
end
-
end
-
6
register_plugin :response_cache, ResponseCache
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX::Plugins
-
6
module ResponseCache
-
6
class Store
-
6
def initialize
-
186
@store = {}
-
186
@store_mutex = Thread::Mutex.new
-
end
-
-
6
def clear
-
24
@store_mutex.synchronize { @store.clear }
-
end
-
-
6
def lookup(request)
-
234
responses = _get(request)
-
-
234
return unless responses
-
-
180
responses.find(&method(:match_by_vary?).curry(2)[request])
-
end
-
-
6
def cached?(request)
-
84
lookup(request)
-
end
-
-
6
def cache(request, response)
-
126
return unless ResponseCache.cacheable_request?(request) && ResponseCache.cacheable_response?(response)
-
-
114
_set(request, response)
-
end
-
-
6
def prepare(request)
-
60
cached_response = lookup(request)
-
-
60
return unless cached_response
-
-
42
return unless match_by_vary?(request, cached_response)
-
-
42
if !request.headers.key?("if-modified-since") && (last_modified = cached_response.headers["last-modified"])
-
24
request.headers.add("if-modified-since", last_modified)
-
end
-
-
42
if !request.headers.key?("if-none-match") && (etag = cached_response.headers["etag"]) # rubocop:disable Style/GuardClause
-
42
request.headers.add("if-none-match", etag)
-
end
-
end
-
-
6
private
-
-
6
def match_by_vary?(request, response)
-
210
vary = response.vary
-
-
210
return true unless vary
-
-
54
original_request = response.instance_variable_get(:@request)
-
-
54
return request.headers.same_headers?(original_request.headers) if vary == %w[*]
-
-
30
vary.all? do |cache_field|
-
30
cache_field.downcase!
-
30
!original_request.headers.key?(cache_field) || request.headers[cache_field] == original_request.headers[cache_field]
-
end
-
end
-
-
6
def _get(request)
-
234
@store_mutex.synchronize do
-
234
responses = @store[request.response_cache_key]
-
-
234
return unless responses
-
-
180
responses.select! do |res|
-
180
!res.body.closed? && res.fresh?
-
end
-
-
180
responses
-
end
-
end
-
-
6
def _set(request, response)
-
114
@store_mutex.synchronize do
-
114
responses = (@store[request.response_cache_key] ||= [])
-
-
114
responses.reject! do |res|
-
12
res.body.closed? || !res.fresh? || match_by_vary?(request, res)
-
end
-
-
114
responses << response
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
13
module HTTPX
-
13
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
-
#
-
13
module Retries
-
13
MAX_RETRIES = 3
-
# TODO: pass max_retries in a configure/load block
-
-
13
IDEMPOTENT_METHODS = %w[GET OPTIONS HEAD PUT DELETE].freeze
-
1
RETRYABLE_ERRORS = [
-
12
IOError,
-
EOFError,
-
Errno::ECONNRESET,
-
Errno::ECONNABORTED,
-
Errno::EPIPE,
-
Errno::EINVAL,
-
Errno::ETIMEDOUT,
-
Parser::Error,
-
TLSError,
-
TimeoutError,
-
ConnectionError,
-
Connection::HTTP2::GoawayError,
-
].freeze
-
13
DEFAULT_JITTER = ->(interval) { interval * ((rand + 1) * 0.5) }
-
-
13
if ENV.key?("HTTPX_NO_JITTER")
-
13
def self.extra_options(options)
-
516
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>).
-
13
module OptionsMethods
-
13
def option_retry_after(value)
-
# return early if callable
-
156
unless value.respond_to?(:call)
-
72
value = Float(value)
-
72
raise TypeError, ":retry_after must be positive" unless value.positive?
-
end
-
-
156
value
-
end
-
-
13
def option_retry_jitter(value)
-
# return early if callable
-
36
raise TypeError, ":retry_jitter must be callable" unless value.respond_to?(:call)
-
-
36
value
-
end
-
-
13
def option_max_retries(value)
-
1628
num = Integer(value)
-
1628
raise TypeError, ":max_retries must be positive" unless num >= 0
-
-
1628
num
-
end
-
-
13
def option_retry_change_requests(v)
-
891
v
-
end
-
-
13
def option_retry_on(value)
-
173
raise TypeError, ":retry_on must be called with the response" unless value.respond_to?(:call)
-
-
173
value
-
end
-
end
-
-
13
module InstanceMethods
-
13
def max_retries(n)
-
72
with(max_retries: n)
-
end
-
-
13
private
-
-
13
def fetch_response(request, selector, options)
-
1995058
response = super
-
-
1995058
if response &&
-
request.retries.positive? &&
-
__repeatable_request?(request, options) &&
-
(
-
(
-
124
response.is_a?(ErrorResponse) && __retryable_error?(response.error)
-
) ||
-
(
-
92
options.retry_on && options.retry_on.call(response)
-
)
-
)
-
343
__try_partial_retry(request, response)
-
343
log { "failed to get response, #{request.retries} tries to go..." }
-
343
request.retries -= 1
-
343
request.transition(:idle)
-
-
343
retry_after = options.retry_after
-
343
retry_after = retry_after.call(request, response) if retry_after.respond_to?(:call)
-
-
343
if retry_after
-
# apply jitter
-
72
if (jitter = request.options.retry_jitter)
-
12
retry_after = jitter.call(retry_after)
-
end
-
-
72
retry_start = Utils.now
-
72
log { "retrying after #{retry_after} secs..." }
-
72
selector.after(retry_after) do
-
72
if request.response
-
# request has terminated abruptly meanwhile
-
request.emit(:response, request.response)
-
else
-
72
log { "retrying (elapsed time: #{Utils.elapsed_time(retry_start)})!!" }
-
72
send_request(request, selector, options)
-
end
-
end
-
else
-
271
send_request(request, selector, options)
-
end
-
-
343
return
-
end
-
1994715
response
-
end
-
-
13
def __repeatable_request?(request, options)
-
713
IDEMPOTENT_METHODS.include?(request.verb) || options.retry_change_requests
-
end
-
-
13
def __retryable_error?(ex)
-
2489
RETRYABLE_ERRORS.any? { |klass| ex.is_a?(klass) }
-
end
-
-
13
def proxy_error?(request, response, _)
-
48
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.
-
#
-
13
def __try_partial_retry(request, response)
-
343
response = response.response if response.is_a?(ErrorResponse)
-
-
343
return unless response
-
-
154
unless response.headers.key?("accept-ranges") &&
-
response.headers["accept-ranges"] == "bytes" && # there's nothing else supported though...
-
12
(original_body = response.body)
-
142
response.close if response.respond_to?(:close)
-
142
return
-
end
-
-
12
request.partial_response = response
-
-
12
size = original_body.bytesize
-
-
12
request.headers["range"] = "bytes=#{size}-"
-
end
-
end
-
-
13
module RequestMethods
-
13
attr_accessor :retries
-
-
13
attr_writer :partial_response
-
-
13
def initialize(*args)
-
530
super
-
530
@retries = @options.max_retries
-
end
-
-
13
def response=(response)
-
885
if @partial_response
-
12
if response.is_a?(Response) && response.status == 206
-
12
response.from_partial_response(@partial_response)
-
else
-
@partial_response.close
-
end
-
12
@partial_response = nil
-
end
-
-
885
super
-
end
-
end
-
-
13
module ResponseMethods
-
13
def from_partial_response(response)
-
12
@status = response.status
-
12
@headers = response.headers
-
12
@body = response.body
-
end
-
end
-
end
-
13
register_plugin :retries, Retries
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
class ServerSideRequestForgeryError < Error; end
-
-
6
module Plugins
-
#
-
# This plugin adds support for preventing Server-Side Request Forgery attacks.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Server-Side-Request-Forgery-Filter
-
#
-
6
module SsrfFilter
-
6
module IPAddrExtensions
-
6
refine IPAddr do
-
6
def prefixlen
-
96
mask_addr = @mask_addr
-
96
raise "Invalid mask" if mask_addr.zero?
-
-
96
mask_addr >>= 1 while (mask_addr & 0x1).zero?
-
-
96
length = 0
-
96
while mask_addr & 0x1 == 0x1
-
1518
length += 1
-
1518
mask_addr >>= 1
-
end
-
-
96
length
-
end
-
end
-
end
-
-
6
using IPAddrExtensions
-
-
# https://en.wikipedia.org/wiki/Reserved_IP_addresses
-
1
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
-
-
2
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|
-
96
prefixlen = ipaddr.prefixlen
-
-
96
ipv4_compatible = ipaddr.ipv4_compat.mask(96 + prefixlen)
-
96
ipv4_mapped = ipaddr.ipv4_mapped.mask(80 + prefixlen)
-
-
96
[ipv4_compatible, ipv4_mapped]
-
end).freeze
-
-
6
class << self
-
6
def extra_options(options)
-
52
options.merge(allowed_schemes: %w[https http])
-
end
-
-
6
def unsafe_ip_address?(ipaddr)
-
70
range = ipaddr.to_range
-
70
return true if range.first != range.last
-
-
82
return IPV6_BLACKLIST.any? { |r| r.include?(ipaddr) } if ipaddr.ipv6?
-
-
700
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>)
-
6
module OptionsMethods
-
6
def option_allowed_schemes(value)
-
58
Array(value)
-
end
-
end
-
-
6
module InstanceMethods
-
6
def send_requests(*requests)
-
64
responses = requests.map do |request|
-
64
next if @options.allowed_schemes.include?(request.uri.scheme)
-
-
6
error = ServerSideRequestForgeryError.new("#{request.uri} URI scheme not allowed")
-
6
error.set_backtrace(caller)
-
6
response = ErrorResponse.new(request, error)
-
6
request.emit(:response, response)
-
6
response
-
end
-
128
allowed_requests = requests.select { |req| responses[requests.index(req)].nil? }
-
64
allowed_responses = super(*allowed_requests)
-
64
allowed_responses.each_with_index do |res, idx|
-
58
req = allowed_requests[idx]
-
58
responses[requests.index(req)] = res
-
end
-
-
64
responses
-
end
-
end
-
-
6
module ConnectionMethods
-
6
def initialize(*)
-
begin
-
58
super
-
8
rescue ServerSideRequestForgeryError => e
-
# may raise when IPs are passed as options via :addresses
-
12
throw(:resolve_error, e)
-
end
-
end
-
-
6
def addresses=(addrs)
-
128
addrs = addrs.map { |addr| addr.is_a?(IPAddr) ? addr : IPAddr.new(addr) }
-
-
58
addrs.reject!(&SsrfFilter.method(:unsafe_ip_address?))
-
-
58
raise ServerSideRequestForgeryError, "#{@origin.host} has no public IP addresses" if addrs.empty?
-
-
12
super
-
end
-
end
-
end
-
-
6
register_plugin :ssrf_filter, SsrfFilter
-
end
-
end
-
# frozen_string_literal: true
-
-
11
module HTTPX
-
11
class StreamResponse
-
11
def initialize(request, session)
-
131
@request = request
-
131
@session = session
-
131
@response = nil
-
end
-
-
11
def each(&block)
-
167
return enum_for(__method__) unless block
-
-
119
@request.stream = self
-
-
13
begin
-
119
@on_chunk = block
-
-
119
if @request.response
-
# if we've already started collecting the payload, yield it first
-
# before proceeding.
-
12
body = @request.response.body
-
-
12
body.each do |chunk|
-
12
on_chunk(chunk)
-
end
-
end
-
-
119
response.raise_for_status
-
ensure
-
119
@on_chunk = nil
-
end
-
end
-
-
11
def each_line
-
82
return enum_for(__method__) unless block_given?
-
-
41
line = "".b
-
-
41
each do |chunk|
-
34
line << chunk
-
-
97
while (idx = line.index("\n"))
-
41
yield line.byteslice(0..idx - 1)
-
-
41
line = line.byteslice(idx + 1..-1)
-
end
-
end
-
-
17
yield line unless line.empty?
-
end
-
-
# This is a ghost method. It's to be used ONLY internally, when processing streams
-
11
def on_chunk(chunk)
-
176
raise NoMethodError unless @on_chunk
-
-
176
@on_chunk.call(chunk)
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<StreamResponse:#{object_id}>"
-
skipped
end
-
skipped
# :nocov:
-
-
11
def to_s
-
12
response.to_s
-
end
-
-
11
private
-
-
11
def response
-
429
return @response if @response
-
-
161
@request.response || begin
-
131
@response = @session.request(@request)
-
end
-
end
-
-
11
def respond_to_missing?(meth, *args)
-
12
response.respond_to?(meth, *args) || super
-
end
-
-
11
def method_missing(meth, *args, &block)
-
143
return super unless response.respond_to?(meth)
-
-
143
response.__send__(meth, *args, &block)
-
end
-
end
-
-
11
module Plugins
-
#
-
# This plugin adds support for stream response (text/event-stream).
-
#
-
# https://gitlab.com/os85/httpx/wikis/Stream
-
#
-
11
module Stream
-
11
def self.extra_options(options)
-
238
options.merge(timeout: { read_timeout: Float::INFINITY, operation_timeout: 60 })
-
end
-
-
11
module InstanceMethods
-
11
def request(*args, stream: false, **options)
-
371
return super(*args, **options) unless stream
-
-
143
requests = args.first.is_a?(Request) ? args : build_requests(*args, options)
-
143
raise Error, "only 1 response at a time is supported for streaming requests" unless requests.size == 1
-
-
131
request = requests.first
-
-
131
StreamResponse.new(request, self)
-
end
-
end
-
-
11
module RequestMethods
-
11
attr_accessor :stream
-
end
-
-
11
module ResponseMethods
-
11
def stream
-
223
request = @request.root_request if @request.respond_to?(:root_request)
-
223
request ||= @request
-
-
223
request.stream
-
end
-
end
-
-
11
module ResponseBodyMethods
-
11
def initialize(*)
-
223
super
-
223
@stream = @response.stream
-
end
-
-
11
def write(chunk)
-
305
return super unless @stream
-
-
186
return 0 if chunk.empty?
-
-
164
chunk = decode_chunk(chunk)
-
-
164
@stream.on_chunk(chunk.dup)
-
-
164
chunk.size
-
end
-
-
11
private
-
-
11
def transition(*)
-
148
return if @stream
-
-
148
super
-
end
-
end
-
end
-
11
register_plugin :stream, Stream
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
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
-
#
-
6
module Upgrade
-
6
class << self
-
6
def configure(klass)
-
24
klass.plugin(:"upgrade/h2")
-
end
-
-
6
def extra_options(options)
-
24
options.merge(upgrade_handlers: {})
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_upgrade_handlers(value)
-
66
raise TypeError, ":upgrade_handlers must be a Hash" unless value.is_a?(Hash)
-
-
66
value
-
end
-
end
-
-
6
module InstanceMethods
-
6
def fetch_response(request, selector, options)
-
201
response = super
-
-
201
if response
-
66
return response unless response.is_a?(Response)
-
-
66
return response unless response.headers.key?("upgrade")
-
-
24
upgrade_protocol = response.headers["upgrade"].split(/ *, */).first
-
-
24
return response unless upgrade_protocol && options.upgrade_handlers.key?(upgrade_protocol)
-
-
24
protocol_handler = options.upgrade_handlers[upgrade_protocol]
-
-
24
return response unless protocol_handler
-
-
24
log { "upgrading to #{upgrade_protocol}..." }
-
24
connection = find_connection(request.uri, selector, options)
-
-
# do not upgrade already upgraded connections
-
24
return if connection.upgrade_protocol == upgrade_protocol
-
-
24
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
-
24
return if response.status == 101 && !connection.hijacked
-
end
-
-
147
response
-
end
-
end
-
-
6
module ConnectionMethods
-
6
attr_reader :upgrade_protocol, :hijacked
-
-
6
def hijack_io
-
6
@hijacked = true
-
-
# connection is taken away from selector and not given back to the pool.
-
6
@current_session.deselect_connection(self, @current_selector, true)
-
end
-
end
-
end
-
6
register_plugin(:upgrade, Upgrade)
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
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
-
#
-
6
module H2
-
6
class << self
-
6
def extra_options(options)
-
24
options.merge(upgrade_handlers: options.upgrade_handlers.merge("h2" => self))
-
end
-
-
6
def call(connection, _request, _response)
-
6
connection.upgrade_to_h2
-
end
-
end
-
-
6
module ConnectionMethods
-
6
using URIExtensions
-
-
6
def upgrade_to_h2
-
6
prev_parser = @parser
-
-
6
if prev_parser
-
6
prev_parser.reset
-
6
@inflight -= prev_parser.requests.size
-
end
-
-
6
@parser = Connection::HTTP2.new(@write_buffer, @options)
-
6
set_parser_callbacks(@parser)
-
6
@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.
-
6
purge_after_closed
-
6
transition(:idle)
-
-
6
prev_parser.requests.each do |req|
-
req.transition(:idle)
-
send(req)
-
end
-
end
-
end
-
end
-
6
register_plugin(:"upgrade/h2", H2)
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin implements convenience methods for performing WEBDAV requests.
-
#
-
# https://gitlab.com/os85/httpx/wikis/WebDav
-
#
-
6
module WebDav
-
6
def self.configure(klass)
-
72
klass.plugin(:xml)
-
end
-
-
6
module InstanceMethods
-
6
def copy(src, dest)
-
12
request("COPY", src, headers: { "destination" => @options.origin.merge(dest) })
-
end
-
-
6
def move(src, dest)
-
12
request("MOVE", src, headers: { "destination" => @options.origin.merge(dest) })
-
end
-
-
6
def lock(path, timeout: nil, &blk)
-
36
headers = {}
-
36
headers["timeout"] = if timeout && timeout.positive?
-
12
"Second-#{timeout}"
-
else
-
24
"Infinite, Second-4100000000"
-
end
-
36
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>"
-
36
response = request("LOCK", path, headers: headers, xml: xml)
-
-
36
return response unless response.is_a?(Response)
-
-
36
return response unless blk && response.status == 200
-
-
12
lock_token = response.headers["lock-token"]
-
-
1
begin
-
12
blk.call(response)
-
ensure
-
12
unlock(path, lock_token)
-
end
-
-
12
response
-
end
-
-
6
def unlock(path, lock_token)
-
24
request("UNLOCK", path, headers: { "lock-token" => lock_token })
-
end
-
-
6
def mkcol(dir)
-
12
request("MKCOL", dir)
-
end
-
-
6
def propfind(path, xml = nil)
-
48
body = case xml
-
when :acl
-
12
'<?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
-
24
'<?xml version="1.0" encoding="utf-8"?><DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
-
else
-
12
xml
-
end
-
-
48
request("PROPFIND", path, headers: { "depth" => "1" }, xml: body)
-
end
-
-
6
def proppatch(path, xml)
-
2
body = "<?xml version=\"1.0\"?>" \
-
10
"<D:propertyupdate xmlns:D=\"DAV:\" xmlns:Z=\"http://ns.example.com/standards/z39.50/\">#{xml}</D:propertyupdate>"
-
12
request("PROPPATCH", path, xml: body)
-
end
-
# %i[ orderpatch acl report search]
-
end
-
end
-
6
register_plugin(:webdav, WebDav)
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin supports request XML encoding/response decoding using the nokogiri gem.
-
#
-
# https://gitlab.com/os85/httpx/wikis/XML
-
#
-
6
module XML
-
6
MIME_TYPES = %r{\b(application|text)/(.+\+)?xml\b}.freeze
-
6
module Transcoder
-
6
module_function
-
-
6
class Encoder
-
6
def initialize(xml)
-
120
@raw = xml
-
end
-
-
6
def content_type
-
120
charset = @raw.respond_to?(:encoding) && @raw.encoding ? @raw.encoding.to_s.downcase : "utf-8"
-
120
"application/xml; charset=#{charset}"
-
end
-
-
6
def bytesize
-
384
@raw.to_s.bytesize
-
end
-
-
6
def to_s
-
120
@raw.to_s
-
end
-
end
-
-
6
def encode(xml)
-
120
Encoder.new(xml)
-
end
-
-
6
def decode(response)
-
18
content_type = response.content_type.mime_type
-
-
18
raise HTTPX::Error, "invalid form mime type (#{content_type})" unless MIME_TYPES.match?(content_type)
-
-
18
Nokogiri::XML.method(:parse)
-
end
-
end
-
-
6
class << self
-
6
def load_dependencies(*)
-
108
require "nokogiri"
-
end
-
end
-
-
6
module ResponseMethods
-
# decodes the response payload into a Nokogiri::XML::Node object **if** the payload is valid
-
# "application/xml" (requires the "nokogiri" gem).
-
6
def xml
-
12
decode(Transcoder)
-
end
-
end
-
-
6
module RequestBodyClassMethods
-
# ..., xml: Nokogiri::XML::Node #=> xml encoder
-
6
def initialize_body(params)
-
444
if (xml = params.delete(:xml))
-
# @type var xml: Nokogiri::XML::Node | String
-
120
return Transcoder.encode(xml)
-
end
-
-
324
super
-
end
-
end
-
end
-
-
6
register_plugin(:xml, XML)
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module ResponsePatternMatchExtensions
-
23
def deconstruct
-
25
[@status, @headers, @body]
-
end
-
-
23
def deconstruct_keys(_keys)
-
50
{ status: @status, headers: @headers, body: @body }
-
end
-
end
-
-
23
module ErrorResponsePatternMatchExtensions
-
23
def deconstruct
-
5
[@error]
-
end
-
-
23
def deconstruct_keys(_keys)
-
25
{ error: @error }
-
end
-
end
-
-
23
module HeadersPatternMatchExtensions
-
23
def deconstruct
-
5
to_a
-
end
-
end
-
-
23
Headers.include HeadersPatternMatchExtensions
-
23
Response.include ResponsePatternMatchExtensions
-
23
ErrorResponse.include ErrorResponsePatternMatchExtensions
-
end
-
# frozen_string_literal: true
-
-
23
require "httpx/selector"
-
23
require "httpx/connection"
-
23
require "httpx/resolver"
-
-
23
module HTTPX
-
23
class Pool
-
23
using ArrayExtensions::FilterMap
-
23
using URIExtensions
-
-
23
POOL_TIMEOUT = 5
-
-
# Sets up the connection pool with the given +options+, which can be the following:
-
#
-
# :max_connections_per_origin :: the maximum number of connections held in the pool pointing to a given origin.
-
# :pool_timeout :: the number of seconds to wait for a connection to a given origin (before raising HTTPX::PoolTimeoutError)
-
#
-
23
def initialize(options)
-
7934
@max_connections_per_origin = options.fetch(:max_connections_per_origin, Float::INFINITY)
-
7934
@pool_timeout = options.fetch(:pool_timeout, POOL_TIMEOUT)
-
12838
@resolvers = Hash.new { |hs, resolver_type| hs[resolver_type] = [] }
-
7934
@resolver_mtx = Thread::Mutex.new
-
7934
@connections = []
-
7934
@connection_mtx = Thread::Mutex.new
-
7934
@origin_counters = Hash.new(0)
-
12353
@origin_conds = Hash.new { |hs, orig| hs[orig] = ConditionVariable.new }
-
end
-
-
23
def pop_connection
-
8407
@connection_mtx.synchronize do
-
8407
conn = @connections.shift
-
8407
@origin_conds.delete(conn.origin) if conn && (@origin_counters[conn.origin.to_s] -= 1).zero?
-
8407
conn
-
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.
-
#
-
23
def checkout_connection(uri, options)
-
5746
return checkout_new_connection(uri, options) if options.io
-
-
5696
@connection_mtx.synchronize do
-
5696
acquire_connection(uri, options) || begin
-
5243
if @origin_counters[uri.origin] == @max_connections_per_origin
-
-
12
@origin_conds[uri.origin].wait(@connection_mtx, @pool_timeout)
-
-
12
return acquire_connection(uri, options) || raise(PoolTimeoutError.new(uri.origin, @pool_timeout))
-
end
-
-
5231
@origin_counters[uri.origin] += 1
-
-
5231
checkout_new_connection(uri, options)
-
end
-
end
-
end
-
-
23
def checkin_connection(connection)
-
5789
return if connection.options.io
-
-
5739
@connection_mtx.synchronize do
-
5739
@connections << connection
-
-
5739
@origin_conds[connection.origin.to_s].signal
-
end
-
end
-
-
23
def checkout_mergeable_connection(connection)
-
5203
return if connection.options.io
-
-
5203
@connection_mtx.synchronize do
-
5203
idx = @connections.find_index do |ch|
-
177
ch != connection && ch.mergeable?(connection)
-
end
-
5203
@connections.delete_at(idx) if idx
-
end
-
end
-
-
23
def reset_resolvers
-
10234
@resolver_mtx.synchronize { @resolvers.clear }
-
end
-
-
23
def checkout_resolver(options)
-
5080
resolver_type = options.resolver_class
-
5080
resolver_type = Resolver.resolver_for(resolver_type)
-
-
5080
@resolver_mtx.synchronize do
-
5080
resolvers = @resolvers[resolver_type]
-
-
5080
idx = resolvers.find_index do |res|
-
30
res.options == options
-
end
-
5080
resolvers.delete_at(idx) if idx
-
end || checkout_new_resolver(resolver_type, options)
-
end
-
-
23
def checkin_resolver(resolver)
-
271
@resolver_mtx.synchronize do
-
271
resolvers = @resolvers[resolver.class]
-
-
271
resolver = resolver.multi
-
-
271
resolvers << resolver unless resolvers.include?(resolver)
-
end
-
end
-
-
23
private
-
-
23
def acquire_connection(uri, options)
-
5708
idx = @connections.find_index do |connection|
-
625
connection.match?(uri, options)
-
end
-
-
5708
@connections.delete_at(idx) if idx
-
end
-
-
23
def checkout_new_connection(uri, options)
-
5281
options.connection_class.new(uri, options)
-
end
-
-
23
def checkout_new_resolver(resolver_type, options)
-
5056
if resolver_type.multi?
-
5035
Resolver::Multi.new(resolver_type, options)
-
else
-
21
resolver_type.new(options)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Punycode
-
23
module_function
-
-
begin
-
23
require "idnx"
-
-
22
def encode_hostname(hostname)
-
24
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
-
-
23
require "delegate"
-
23
require "forwardable"
-
-
23
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.
-
23
class Request
-
23
extend Forwardable
-
23
include Callbacks
-
23
using URIExtensions
-
-
# default value used for "user-agent" header, when not overridden.
-
23
USER_AGENT = "httpx.rb/#{VERSION}".freeze # rubocop:disable Style/RedundantFreeze
-
-
# the upcased string HTTP verb for this request.
-
23
attr_reader :verb
-
-
# the absolute URI object for this request.
-
23
attr_reader :uri
-
-
# an HTTPX::Headers object containing the request HTTP headers.
-
23
attr_reader :headers
-
-
# an HTTPX::Request::Body object containing the request body payload (or +nil+, whenn there is none).
-
23
attr_reader :body
-
-
# a symbol describing which frame is currently being flushed.
-
23
attr_reader :state
-
-
# an HTTPX::Options object containing request options.
-
23
attr_reader :options
-
-
# the corresponding HTTPX::Response object, when there is one.
-
23
attr_reader :response
-
-
# Exception raised during enumerable body writes.
-
23
attr_reader :drain_error
-
-
# The IP address from the peer server.
-
23
attr_accessor :peer_address
-
-
23
attr_writer :persistent
-
-
# will be +true+ when request body has been completely flushed.
-
23
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.
-
23
def initialize(verb, uri, options, params = EMPTY_HASH)
-
7306
@verb = verb.to_s.upcase
-
7306
@uri = Utils.to_uri(uri)
-
-
7305
@headers = options.headers.dup
-
7305
merge_headers(params.delete(:headers)) if params.key?(:headers)
-
-
7305
@headers["user-agent"] ||= USER_AGENT
-
7305
@headers["accept"] ||= "*/*"
-
-
# forego compression in the Range request case
-
7305
if @headers.key?("range")
-
6
@headers.delete("accept-encoding")
-
else
-
7299
@headers["accept-encoding"] ||= options.supported_compression_formats
-
end
-
-
7305
@query_params = params.delete(:params) if params.key?(:params)
-
-
7305
@body = options.request_body_class.new(@headers, options, **params)
-
-
7299
@options = @body.options
-
-
7299
if @uri.relative? || @uri.host.nil?
-
452
origin = @options.origin
-
452
raise(Error, "invalid URI: #{@uri}") unless origin
-
-
432
base_path = @options.base_path
-
-
432
@uri = origin.merge("#{base_path}#{@uri}")
-
end
-
-
7279
@state = :idle
-
7279
@response = nil
-
7279
@peer_address = nil
-
7279
@persistent = @options.persistent
-
end
-
-
# the read timeout defined for this requet.
-
23
def read_timeout
-
16786
@options.timeout[:read_timeout]
-
end
-
-
# the write timeout defined for this requet.
-
23
def write_timeout
-
16786
@options.timeout[:write_timeout]
-
end
-
-
# the request timeout defined for this requet.
-
23
def request_timeout
-
16572
@options.timeout[:request_timeout]
-
end
-
-
23
def persistent?
-
3671
@persistent
-
end
-
-
# if the request contains trailer headers
-
23
def trailers?
-
2170
defined?(@trailers)
-
end
-
-
# returns an instance of HTTPX::Headers containing the trailer headers
-
23
def trailers
-
66
@trailers ||= @options.headers_class.new
-
end
-
-
# returns +:r+ or +:w+, depending on whether the request is waiting for a response or flushing.
-
23
def interests
-
19723
return :r if @state == :done || @state == :expect
-
-
2550
:w
-
end
-
-
# merges +h+ into the instance of HTTPX::Headers of the request.
-
23
def merge_headers(h)
-
615
@headers = @headers.merge(h)
-
end
-
-
# the URI scheme of the request +uri+.
-
23
def scheme
-
2587
@uri.scheme
-
end
-
-
# sets the +response+ on this request.
-
23
def response=(response)
-
6855
return unless response
-
-
6855
if response.is_a?(Response) && response.status < 200
-
# deal with informational responses
-
-
120
if response.status == 100 && @headers.key?("expect")
-
102
@informational_status = response.status
-
102
return
-
end
-
-
# 103 Early Hints advertises resources in document to browsers.
-
# not very relevant for an HTTP client, discard.
-
18
return if response.status >= 103
-
end
-
-
6753
@response = response
-
-
6753
emit(:response_started, response)
-
end
-
-
# returnns the URI path of the request +uri+.
-
23
def path
-
6416
path = uri.path.dup
-
6416
path = +"" if path.nil?
-
6416
path << "/" if path.empty?
-
6416
path << "?#{query}" unless query.empty?
-
6416
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"
-
23
def authority
-
6438
@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"
-
23
def origin
-
2802
@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"
-
23
def query
-
7124
return @query if defined?(@query)
-
-
5975
query = []
-
5975
if (q = @query_params)
-
116
query << Transcoder::Form.encode(q)
-
end
-
5975
query << @uri.query if @uri.query
-
5975
@query = query.join("&")
-
end
-
-
# consumes and returns the next available chunk of request body that can be sent
-
23
def drain_body
-
6800
return nil if @body.nil?
-
-
6800
@drainer ||= @body.each
-
6800
chunk = @drainer.next.dup
-
-
4605
emit(:body_chunk, chunk)
-
4605
chunk
-
rescue StopIteration
-
2185
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)
-
23
def transition(nextstate)
-
29477
case nextstate
-
when :idle
-
523
@body.rewind
-
523
@response = nil
-
523
@drainer = nil
-
when :headers
-
7974
return unless @state == :idle
-
when :body
-
7962
return unless @state == :headers ||
-
@state == :expect
-
-
6517
if @headers.key?("expect")
-
372
if @informational_status && @informational_status == 100
-
# check for 100 Continue response, and deallocate the var
-
# if @informational_status == 100
-
# @response = nil
-
# end
-
else
-
277
return if @state == :expect # do not re-set it
-
-
108
nextstate = :expect
-
end
-
end
-
when :trailers
-
6506
return unless @state == :body
-
when :done
-
6512
return if @state == :expect
-
end
-
25580
@state = nextstate
-
25580
emit(@state, self)
-
3501
nil
-
end
-
-
# whether the request supports the 100-continue handshake and already processed the 100 response.
-
23
def expects?
-
6022
@headers["expect"] == "100-continue" && @informational_status == 100 && !@response
-
end
-
end
-
end
-
-
23
require_relative "request/body"
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
# Implementation of the HTTP Request body as a delegator which iterates (responds to +each+) payload chunks.
-
23
class Request::Body < SimpleDelegator
-
23
class << self
-
23
def new(_, options, body: nil, **params)
-
7311
if body.is_a?(self)
-
# request derives its options from body
-
12
body.options = options.merge(params)
-
12
return body
-
end
-
-
7299
super
-
end
-
end
-
-
23
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
-
23
def initialize(h, options, **params)
-
7299
@headers = h
-
7299
@body = self.class.initialize_body(params)
-
7299
@options = options.merge(params)
-
-
7299
if @body
-
2284
if @options.compress_request_body && @headers.key?("content-encoding")
-
-
74
@headers.get("content-encoding").each do |encoding|
-
74
@body = self.class.initialize_deflater_body(@body, encoding)
-
end
-
end
-
-
2284
@headers["content-type"] ||= @body.content_type
-
2284
@headers["content-length"] = @body.bytesize unless unbounded_body?
-
end
-
-
7293
super(@body)
-
end
-
-
# consumes and yields the request payload in chunks.
-
23
def each(&block)
-
4588
return enum_for(__method__) unless block
-
2297
return if @body.nil?
-
-
2243
body = stream(@body)
-
2243
if body.respond_to?(:read)
-
939
::IO.copy_stream(body, ProcIO.new(block))
-
1303
elsif body.respond_to?(:each)
-
309
body.each(&block)
-
else
-
995
block[body.to_s]
-
end
-
end
-
-
# if the +@body+ is rewindable, it rewinnds it.
-
23
def rewind
-
571
return if empty?
-
-
120
@body.rewind if @body.respond_to?(:rewind)
-
end
-
-
# return +true+ if the +body+ has been fully drained (or does nnot exist).
-
23
def empty?
-
13974
return true if @body.nil?
-
6123
return false if chunked?
-
-
6051
@body.bytesize.zero?
-
end
-
-
# returns the +@body+ payload size in bytes.
-
23
def bytesize
-
2626
return 0 if @body.nil?
-
-
96
@body.bytesize
-
end
-
-
# sets the body to yield using chunked trannsfer encoding format.
-
23
def stream(body)
-
2243
return body unless chunked?
-
-
72
Transcoder::Chunker.encode(body.enum_for(:each))
-
end
-
-
# returns whether the body yields infinitely.
-
23
def unbounded_body?
-
2818
return @unbounded_body if defined?(@unbounded_body)
-
-
2338
@unbounded_body = !@body.nil? && (chunked? || @body.bytesize == Float::INFINITY)
-
end
-
-
# returns whether the chunked transfer encoding header is set.
-
23
def chunked?
-
14473
@headers["transfer-encoding"] == "chunked"
-
end
-
-
# sets the chunked transfer encoding header.
-
23
def chunk!
-
24
@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:
-
-
23
class << self
-
23
def initialize_body(params)
-
7179
if (body = params.delete(:body))
-
# @type var body: bodyIO
-
968
Transcoder::Body.encode(body)
-
6211
elsif (form = params.delete(:form))
-
# @type var form: Transcoder::urlencoded_input
-
1133
Transcoder::Form.encode(form)
-
5078
elsif (json = params.delete(:json))
-
# @type var body: _ToJson
-
63
Transcoder::JSON.encode(json)
-
end
-
end
-
-
# returns the +body+ wrapped with the correct deflater accordinng to the given +encodisng+.
-
23
def initialize_deflater_body(body, encoding)
-
74
case encoding
-
when "gzip"
-
38
Transcoder::GZIP.encode(body)
-
when "deflate"
-
18
Transcoder::Deflate.encode(body)
-
when "identity"
-
12
body
-
else
-
6
body
-
end
-
end
-
end
-
end
-
-
# Wrapper yielder which can be used with functions which expect an IO writer.
-
23
class ProcIO
-
23
def initialize(block)
-
939
@block = block
-
end
-
-
# Implementation the IO write protocol, which yield the given chunk to +@block+.
-
23
def write(data)
-
2623
@block.call(data.dup)
-
2617
data.bytesize
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "resolv"
-
23
require "ipaddr"
-
-
23
module HTTPX
-
23
module Resolver
-
23
RESOLVE_TIMEOUT = [2, 3].freeze
-
-
23
require "httpx/resolver/resolver"
-
23
require "httpx/resolver/system"
-
23
require "httpx/resolver/native"
-
23
require "httpx/resolver/https"
-
23
require "httpx/resolver/multi"
-
-
23
@lookup_mutex = Thread::Mutex.new
-
172
@lookups = Hash.new { |h, k| h[k] = [] }
-
-
23
@identifier_mutex = Thread::Mutex.new
-
23
@identifier = 1
-
23
@system_resolver = Resolv::Hosts.new
-
-
23
module_function
-
-
23
def resolver_for(resolver_type)
-
5115
case resolver_type
-
4965
when :native then Native
-
27
when :system then System
-
61
when :https then HTTPS
-
else
-
62
return resolver_type if resolver_type.is_a?(Class) && resolver_type < Resolver
-
-
6
raise Error, "unsupported resolver type (#{resolver_type})"
-
end
-
end
-
-
23
def nolookup_resolve(hostname)
-
4957
ip_resolve(hostname) || cached_lookup(hostname) || system_resolve(hostname)
-
end
-
-
23
def ip_resolve(hostname)
-
4957
[IPAddr.new(hostname)]
-
rescue ArgumentError
-
end
-
-
23
def system_resolve(hostname)
-
426
ips = @system_resolver.getaddresses(hostname)
-
426
return if ips.empty?
-
-
534
ips.map { |ip| IPAddr.new(ip) }
-
rescue IOError
-
end
-
-
23
def cached_lookup(hostname)
-
4558
now = Utils.now
-
4558
lookup_synchronize do |lookups|
-
4558
lookup(hostname, lookups, now)
-
end
-
end
-
-
23
def cached_lookup_set(hostname, family, entries)
-
180
now = Utils.now
-
180
entries.each do |entry|
-
229
entry["TTL"] += now
-
end
-
180
lookup_synchronize do |lookups|
-
180
case family
-
when Socket::AF_INET6
-
30
lookups[hostname].concat(entries)
-
when Socket::AF_INET
-
150
lookups[hostname].unshift(*entries)
-
end
-
180
entries.each do |entry|
-
229
next unless entry["name"] != hostname
-
-
24
case family
-
when Socket::AF_INET6
-
6
lookups[entry["name"]] << entry
-
when Socket::AF_INET
-
18
lookups[entry["name"]].unshift(entry)
-
end
-
end
-
end
-
end
-
-
# do not use directly!
-
23
def lookup(hostname, lookups, ttl)
-
4564
return unless lookups.key?(hostname)
-
-
4137
entries = lookups[hostname] = lookups[hostname].select do |address|
-
10270
address["TTL"] > ttl
-
end
-
-
4137
ips = entries.flat_map do |address|
-
10255
if address.key?("alias")
-
6
lookup(address["alias"], lookups, ttl)
-
else
-
10249
IPAddr.new(address["data"])
-
end
-
end.compact
-
-
4137
ips unless ips.empty?
-
end
-
-
23
def generate_id
-
1226
id_synchronize { @identifier = (@identifier + 1) & 0xFFFF }
-
end
-
-
23
def encode_dns_query(hostname, type: Resolv::DNS::Resource::IN::A, message_id: generate_id)
-
559
Resolv::DNS::Message.new(message_id).tap do |query|
-
613
query.rd = 1
-
613
query.add_question(hostname, type)
-
107
end.encode
-
end
-
-
23
def decode_dns_answer(payload)
-
53
begin
-
555
message = Resolv::DNS::Message.decode(payload)
-
rescue Resolv::DNS::DecodeError => e
-
5
return :decode_error, e
-
end
-
-
# no domain was found
-
550
return :no_domain_found if message.rcode == Resolv::DNS::RCode::NXDomain
-
-
224
return :message_truncated if message.tc == 1
-
-
214
return :dns_error, message.rcode if message.rcode != Resolv::DNS::RCode::NoError
-
-
204
addresses = []
-
-
204
message.each_answer do |question, _, value|
-
874
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
-
856
addresses << {
-
23
"name" => question.to_s,
-
"TTL" => value.ttl,
-
"data" => value.address.to_s,
-
}
-
end
-
end
-
-
204
[:ok, addresses]
-
end
-
-
23
def lookup_synchronize
-
9476
@lookup_mutex.synchronize { yield(@lookups) }
-
end
-
-
23
def id_synchronize(&block)
-
613
@identifier_mutex.synchronize(&block)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "resolv"
-
23
require "uri"
-
23
require "cgi"
-
23
require "forwardable"
-
23
require "httpx/base64"
-
-
23
module HTTPX
-
23
class Resolver::HTTPS < Resolver::Resolver
-
23
extend Forwardable
-
23
using URIExtensions
-
-
23
module DNSExtensions
-
23
refine Resolv::DNS do
-
23
def generate_candidates(name)
-
35
@config.generate_candidates(name)
-
end
-
end
-
end
-
23
using DNSExtensions
-
-
23
NAMESERVER = "https://1.1.1.1/dns-query"
-
-
1
DEFAULTS = {
-
22
uri: NAMESERVER,
-
use_get: false,
-
}.freeze
-
-
23
def_delegators :@resolver_connection, :state, :connecting?, :to_io, :call, :close, :terminate, :inflight?
-
-
23
def initialize(_, options)
-
75
super
-
75
@resolver_options = DEFAULTS.merge(@options.resolver_options)
-
75
@queries = {}
-
75
@requests = {}
-
75
@connections = []
-
75
@uri = URI(@resolver_options[:uri])
-
75
@uri_addresses = nil
-
75
@resolver = Resolv::DNS.new
-
75
@resolver.timeouts = @resolver_options.fetch(:timeouts, Resolver::RESOLVE_TIMEOUT)
-
75
@resolver.lazy_initialize
-
end
-
-
23
def <<(connection)
-
75
return if @uri.origin == connection.peer.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
-
-
23
def closed?
-
true
-
end
-
-
23
def empty?
-
70
true
-
end
-
-
23
def resolver_connection
-
# TODO: leaks connection object into the pool
-
55
@resolver_connection ||= @current_session.find_connection(@uri, @current_selector,
-
@options.merge(ssl: { alpn_protocols: %w[h2] })).tap do |conn|
-
35
emit_addresses(conn, @family, @uri_addresses) unless conn.addresses
-
end
-
end
-
-
23
private
-
-
23
def resolve(connection = @connections.first, hostname = nil)
-
55
return unless connection
-
-
55
hostname ||= @queries.key(connection)
-
-
55
if hostname.nil?
-
35
hostname = connection.peer.host
-
35
log { "resolver: resolve IDN #{connection.peer.non_ascii_hostname} as #{hostname}" } if connection.peer.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.peer.host, e)
-
end
-
end
-
-
23
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.peer.host, e)
-
else
-
# @type var response: HTTPX::Response
-
50
parse(request, response)
-
ensure
-
55
@requests.delete(request)
-
end
-
-
23
def on_promise(_, stream)
-
log(level: 2) { "#{stream.id}: refusing stream!" }
-
stream.refuse
-
end
-
-
23
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.peer.host, result)
-
end
-
end
-
-
23
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 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
-
-
23
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
-
-
23
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
-
-
23
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
-
-
23
require "forwardable"
-
23
require "resolv"
-
-
23
module HTTPX
-
23
class Resolver::Multi
-
23
include Callbacks
-
23
using ArrayExtensions::FilterMap
-
-
23
attr_reader :resolvers, :options
-
-
23
def initialize(resolver_type, options)
-
5035
@current_selector = nil
-
5035
@current_session = nil
-
5035
@options = options
-
5035
@resolver_options = @options.resolver_options
-
-
5035
@resolvers = options.ip_families.map do |ip_family|
-
5035
resolver = resolver_type.new(ip_family, options)
-
5035
resolver.multi = self
-
5035
resolver
-
end
-
-
5035
@errors = Hash.new { |hs, k| hs[k] = [] }
-
end
-
-
23
def current_selector=(s)
-
5059
@current_selector = s
-
10118
@resolvers.each { |r| r.__send__(__method__, s) }
-
end
-
-
23
def current_session=(s)
-
5059
@current_session = s
-
10118
@resolvers.each { |r| r.__send__(__method__, s) }
-
end
-
-
23
def closed?
-
@resolvers.all?(&:closed?)
-
end
-
-
23
def empty?
-
@resolvers.all?(&:empty?)
-
end
-
-
23
def inflight?
-
@resolvers.any(&:inflight?)
-
end
-
-
23
def timeout
-
@resolvers.filter_map(&:timeout).min
-
end
-
-
23
def close
-
@resolvers.each(&:close)
-
end
-
-
23
def connections
-
@resolvers.filter_map { |r| r.resolver_connection if r.respond_to?(:resolver_connection) }
-
end
-
-
23
def early_resolve(connection)
-
5061
hostname = connection.peer.host
-
5061
addresses = @resolver_options[:cache] && (connection.addresses || HTTPX::Resolver.nolookup_resolve(hostname))
-
5061
return false unless addresses
-
-
4708
resolved = false
-
4886
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.
-
9748
resolver = @resolvers.find { |r| r.family == family } || @resolvers.first
-
-
4874
next unless resolver # this should ever happen
-
-
# it does not matter which resolver it is, as early-resolve code is shared.
-
4874
resolver.emit_addresses(connection, family, addrs, true)
-
-
4845
resolved = true
-
end
-
-
4679
resolved
-
end
-
-
23
def lazy_resolve(connection)
-
353
@resolvers.each do |resolver|
-
353
resolver << @current_session.try_clone_connection(connection, @current_selector, resolver.family)
-
343
next if resolver.empty?
-
-
273
@current_session.select_resolver(resolver, @current_selector)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
23
require "resolv"
-
-
23
module HTTPX
-
23
class Resolver::Native < Resolver::Resolver
-
23
extend Forwardable
-
23
using URIExtensions
-
-
1
DEFAULTS = {
-
22
nameserver: nil,
-
**Resolv::DNS::Config.default_config_hash,
-
packet_size: 512,
-
timeouts: Resolver::RESOLVE_TIMEOUT,
-
}.freeze
-
-
23
DNS_PORT = 53
-
-
23
def_delegator :@connections, :empty?
-
-
23
attr_reader :state
-
-
23
def initialize(family, options)
-
4960
super
-
4960
@ns_index = 0
-
4960
@resolver_options = DEFAULTS.merge(@options.resolver_options)
-
4960
@socket_type = @resolver_options.fetch(:socket_type, :udp)
-
4960
@nameserver = if (nameserver = @resolver_options[:nameserver])
-
4955
nameserver = nameserver[family] if nameserver.is_a?(Hash)
-
4955
Array(nameserver)
-
end
-
4960
@ndots = @resolver_options.fetch(:ndots, 1)
-
14880
@search = Array(@resolver_options[:search]).map { |srch| srch.scan(/[^.]+/) }
-
4960
@_timeouts = Array(@resolver_options[:timeouts])
-
6256
@timeouts = Hash.new { |timeouts, host| timeouts[host] = @_timeouts.dup }
-
4960
@connections = []
-
4960
@queries = {}
-
4960
@read_buffer = "".b
-
4960
@write_buffer = Buffer.new(@resolver_options[:packet_size])
-
4960
@state = :idle
-
end
-
-
23
def close
-
271
transition(:closed)
-
end
-
-
23
def closed?
-
542
@state == :closed
-
end
-
-
23
def to_io
-
970
@io.to_io
-
end
-
-
23
def call
-
849
case @state
-
when :open
-
844
consume
-
end
-
72
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
-
20
handle_error(e)
-
end
-
-
23
def interests
-
3816
case @state
-
when :idle
-
3168
transition(:open)
-
when :closed
-
13
transition(:idle)
-
13
transition(:open)
-
end
-
-
3816
calculate_interests
-
end
-
-
23
def <<(connection)
-
278
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
-
273
@connections << connection
-
273
resolve
-
end
-
end
-
-
23
def timeout
-
3816
return if @connections.empty?
-
-
3816
@start_timeout = Utils.now
-
3816
hosts = @queries.keys
-
3816
@timeouts.values_at(*hosts).reject(&:empty?).map(&:first).min
-
end
-
-
23
def handle_socket_timeout(interval)
-
83
do_retry(interval)
-
end
-
-
23
private
-
-
23
def calculate_interests
-
5380
return :w unless @write_buffer.empty?
-
-
4164
return :r unless @queries.empty?
-
-
18
nil
-
end
-
-
23
def consume
-
829
dread if calculate_interests == :r
-
735
do_retry
-
735
dwrite if calculate_interests == :w
-
end
-
-
23
def do_retry(loop_time = nil)
-
818
return if @queries.empty? || !@start_timeout
-
-
641
loop_time ||= Utils.elapsed_time(@start_timeout)
-
-
641
query = @queries.first
-
-
641
return unless query
-
-
641
h, connection = query
-
641
host = connection.peer.host
-
641
timeout = (@timeouts[host][0] -= loop_time)
-
-
641
return unless timeout <= 0
-
-
63
@timeouts[host].shift
-
-
63
if !@timeouts[host].empty?
-
38
log { "resolver: timeout after #{timeout}s, retry(#{@timeouts[host].first}) #{host}..." }
-
# must downgrade to tcp AND retry on same host as last
-
38
downgrade_socket
-
38
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
ex = ResolveTimeoutError.new(loop_time, "Timed out while resolving #{connection.peer.host}")
-
5
ex.set_backtrace(ex ? ex.backtrace : caller)
-
5
emit_resolve_error(connection, host, ex)
-
5
emit(:close, self)
-
end
-
end
-
-
23
def dread(wsize = @resolver_options[:packet_size])
-
510
loop do
-
754
wsize = @large_packet.capacity if @large_packet
-
-
754
siz = @io.read(wsize, @read_buffer)
-
-
754
unless siz
-
ex = EOFError.new("descriptor closed")
-
ex.set_backtrace(caller)
-
raise ex
-
end
-
-
754
return unless siz.positive?
-
-
520
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
-
495
parse(@read_buffer)
-
end
-
-
406
return if @state == :closed
-
end
-
end
-
-
23
def dwrite
-
558
loop do
-
1116
return if @write_buffer.empty?
-
-
558
siz = @io.write(@write_buffer)
-
-
558
unless siz
-
ex = EOFError.new("descriptor closed")
-
ex.set_backtrace(caller)
-
raise ex
-
end
-
-
558
return unless siz.positive?
-
-
558
return if @state == :closed
-
end
-
end
-
-
23
def parse(buffer)
-
510
code, result = Resolver.decode_dns_answer(buffer)
-
-
510
case code
-
when :ok
-
189
parse_addresses(result)
-
when :no_domain_found
-
# Indicates no such domain was found.
-
296
hostname, connection = @queries.first
-
296
reset_hostname(hostname, reset_candidates: false)
-
-
296
unless @queries.value?(connection)
-
74
@connections.delete(connection)
-
74
ex = NativeResolveError.new(connection, connection.peer.host, "name or service not known")
-
74
ex.set_backtrace(ex ? ex.backtrace : caller)
-
74
emit_resolve_error(connection, connection.peer.host, ex)
-
74
emit(:close, self)
-
end
-
-
296
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.peer.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.peer.host, result.message)
-
5
ex.set_backtrace(result.backtrace)
-
5
raise ex
-
end
-
end
-
-
23
def parse_addresses(addresses)
-
189
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.peer.host)
-
else
-
184
address = addresses.first
-
184
name = address["name"]
-
-
184
connection = @queries.delete(name)
-
-
184
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
-
-
184
if address.key?("alias") # CNAME
-
16
hostname_alias = address["alias"]
-
# clean up intermediate queries
-
16
@timeouts.delete(name) unless connection.peer.host == name
-
-
16
if 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
-
168
reset_hostname(name, connection: connection)
-
168
@timeouts.delete(connection.peer.host)
-
168
@connections.delete(connection)
-
168
Resolver.cached_lookup_set(connection.peer.host, @family, addresses) if @resolver_options[:cache]
-
848
catch(:coalesced) { emit_addresses(connection, @family, addresses.map { |addr| addr["data"] }) }
-
end
-
end
-
169
return emit(:close, self) if @connections.empty?
-
-
2
resolve
-
end
-
-
23
def resolve(connection = @connections.first, hostname = nil)
-
639
raise Error, "no URI to resolve" unless connection
-
-
565
return unless @write_buffer.empty?
-
-
563
hostname ||= @queries.key(connection)
-
-
563
if hostname.nil?
-
283
hostname = connection.peer.host
-
283
log { "resolver: resolve IDN #{connection.peer.non_ascii_hostname} as #{hostname}" } if connection.peer.non_ascii_hostname
-
-
283
hostname = generate_candidates(hostname).each do |name|
-
1132
@queries[name] = connection
-
end.first
-
else
-
280
@queries[hostname] = connection
-
end
-
563
log { "resolver: query #{@record_type.name.split("::").last} for #{hostname}" }
-
53
begin
-
563
@write_buffer << encode_dns_query(hostname)
-
rescue Resolv::DNS::EncodeError => e
-
reset_hostname(hostname, connection: connection)
-
@connections.delete(connection)
-
emit_resolve_error(connection, hostname, e)
-
emit(:close, self) if @connections.empty?
-
end
-
end
-
-
23
def encode_dns_query(hostname)
-
563
message_id = Resolver.generate_id
-
563
msg = Resolver.encode_dns_query(hostname, type: @record_type, message_id: message_id)
-
563
msg[0, 2] = [msg.size, message_id].pack("nn") if @socket_type == :tcp
-
563
msg
-
end
-
-
23
def generate_candidates(name)
-
283
return [name] if name.end_with?(".")
-
-
283
candidates = []
-
283
name_parts = name.scan(/[^.]+/)
-
283
candidates = [name] if @ndots <= name_parts.size - 1
-
849
candidates.concat(@search.map { |domain| [*name_parts, *domain].join(".") })
-
283
fname = "#{name}."
-
283
candidates << fname unless candidates.include?(fname)
-
-
283
candidates
-
end
-
-
23
def build_socket
-
306
ip, port = @nameserver[@ns_index]
-
306
port ||= DNS_PORT
-
-
306
case @socket_type
-
when :udp
-
291
log { "resolver: server: udp://#{ip}:#{port}..." }
-
291
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
-
-
23
def downgrade_socket
-
48
return unless @socket_type == :tcp
-
-
5
@socket_type = @resolver_options.fetch(:socket_type, :udp)
-
5
transition(:idle)
-
5
transition(:open)
-
end
-
-
23
def transition(nextstate)
-
3510
case nextstate
-
when :idle
-
38
if @io
-
38
@io.close
-
38
@io = nil
-
end
-
when :open
-
3191
return unless @state == :idle
-
-
3191
@io ||= build_socket
-
-
3191
@io.connect
-
3191
return unless @io.connected?
-
-
306
resolve if @queries.empty? && !@connections.empty?
-
when :closed
-
281
return unless @state == :open
-
-
281
@io.close if @io
-
281
@start_timeout = nil
-
281
@write_buffer.clear
-
281
@read_buffer.clear
-
end
-
625
@state = nextstate
-
rescue Errno::ECONNREFUSED,
-
Errno::EADDRNOTAVAIL,
-
Errno::EHOSTUNREACH,
-
SocketError,
-
IOError,
-
ConnectTimeoutError => e
-
# these errors may happen during TCP handshake
-
# treat them as resolve errors.
-
handle_error(e)
-
end
-
-
23
def handle_error(error)
-
25
if error.respond_to?(:connection) &&
-
error.respond_to?(:host)
-
20
reset_hostname(error.host, connection: error.connection)
-
20
@connections.delete(error.connection)
-
20
emit_resolve_error(error.connection, error.host, error)
-
else
-
5
@queries.each do |host, connection|
-
5
reset_hostname(host, connection: connection)
-
5
@connections.delete(connection)
-
5
emit_resolve_error(connection, host, error)
-
end
-
end
-
25
emit(:close, self) if @connections.empty?
-
end
-
-
23
def reset_hostname(hostname, connection: @queries.delete(hostname), reset_candidates: true)
-
539
@timeouts.delete(hostname)
-
539
@timeouts.delete(hostname)
-
-
539
return unless connection && reset_candidates
-
-
# eliminate other candidates
-
837
candidates = @queries.select { |_, conn| connection == conn }.keys
-
837
@queries.delete_if { |h, _| candidates.include?(h) }
-
# reset timeouts
-
847
@timeouts.delete_if { |h, _| candidates.include?(h) }
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "resolv"
-
23
require "ipaddr"
-
-
23
module HTTPX
-
23
class Resolver::Resolver
-
23
include Callbacks
-
23
include Loggable
-
-
23
using ArrayExtensions::Intersect
-
-
1
RECORD_TYPES = {
-
22
Socket::AF_INET6 => Resolv::DNS::Resource::IN::AAAA,
-
Socket::AF_INET => Resolv::DNS::Resource::IN::A,
-
}.freeze
-
-
1
FAMILY_TYPES = {
-
22
Resolv::DNS::Resource::IN::AAAA => "AAAA",
-
Resolv::DNS::Resource::IN::A => "A",
-
}.freeze
-
-
23
class << self
-
23
def multi?
-
5035
true
-
end
-
end
-
-
23
attr_reader :family, :options
-
-
23
attr_writer :current_selector, :current_session
-
-
23
attr_accessor :multi
-
-
23
def initialize(family, options)
-
5056
@family = family
-
5056
@record_type = RECORD_TYPES[family]
-
5056
@options = options
-
-
5056
set_resolver_callbacks
-
end
-
-
23
def each_connection(&block)
-
170
enum_for(__method__) unless block
-
-
170
return unless @connections
-
-
170
@connections.each(&block)
-
end
-
-
23
def close; end
-
-
23
alias_method :terminate, :close
-
-
23
def closed?
-
true
-
end
-
-
23
def empty?
-
true
-
end
-
-
23
def inflight?
-
false
-
end
-
-
23
def emit_addresses(connection, family, addresses, early_resolve = false)
-
5103
addresses.map! do |address|
-
11546
address.is_a?(IPAddr) ? address : IPAddr.new(address.to_s)
-
end
-
-
# double emission check, but allow early resolution to work
-
5103
return if !early_resolve && connection.addresses && !addresses.intersect?(connection.addresses)
-
-
5153
log { "resolver: answer #{FAMILY_TYPES[RECORD_TYPES[family]]} #{connection.peer.host}: #{addresses.inspect}" }
-
5103
if @current_selector && # if triggered by early resolve, session may not be here yet
-
!connection.io &&
-
connection.options.ip_families.size > 1 &&
-
family == Socket::AF_INET &&
-
addresses.first.to_s != connection.peer.host.to_s
-
log { "resolver: A response, applying resolution delay..." }
-
@current_selector.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
-
5103
emit_resolved_connection(connection, addresses, early_resolve)
-
end
-
end
-
-
23
private
-
-
23
def emit_resolved_connection(connection, addresses, early_resolve)
-
begin
-
5103
connection.addresses = addresses
-
-
5069
emit(:resolve, connection)
-
24
rescue StandardError => e
-
34
if early_resolve
-
29
connection.force_reset
-
29
throw(:resolve_error, e)
-
else
-
5
emit(:error, connection, e)
-
end
-
end
-
end
-
-
23
def early_resolve(connection, hostname: connection.peer.host)
-
16
addresses = @resolver_options[:cache] && (connection.addresses || HTTPX::Resolver.nolookup_resolve(hostname))
-
-
16
return false unless addresses
-
-
5
addresses = addresses.select { |addr| addr.family == @family }
-
-
1
return false if addresses.empty?
-
-
1
emit_addresses(connection, @family, addresses, true)
-
-
1
true
-
end
-
-
23
def emit_resolve_error(connection, hostname = connection.peer.host, ex = nil)
-
135
emit_connection_error(connection, resolve_error(hostname, ex))
-
end
-
-
23
def resolve_error(hostname, ex = nil)
-
135
return ex if ex.is_a?(ResolveError) || ex.is_a?(ResolveTimeoutError)
-
-
35
message = ex ? ex.message : "Can't resolve #{hostname}"
-
35
error = ResolveError.new(message)
-
35
error.set_backtrace(ex ? ex.backtrace : caller)
-
35
error
-
end
-
-
23
def set_resolver_callbacks
-
5056
on(:resolve, &method(:resolve_connection))
-
5056
on(:error, &method(:emit_connection_error))
-
5056
on(:close, &method(:close_resolver))
-
end
-
-
23
def resolve_connection(connection)
-
5069
@current_session.__send__(:on_resolver_connection, connection, @current_selector)
-
end
-
-
23
def emit_connection_error(connection, error)
-
129
return connection.emit(:connect_error, error) if connection.connecting? && connection.callbacks_for?(:connect_error)
-
-
129
connection.emit(:error, error)
-
end
-
-
23
def close_resolver(resolver)
-
271
@current_session.__send__(:on_resolver_close, resolver, @current_selector)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
23
require "resolv"
-
-
23
module HTTPX
-
23
class Resolver::System < Resolver::Resolver
-
23
using URIExtensions
-
23
extend Forwardable
-
-
23
RESOLV_ERRORS = [Resolv::ResolvError,
-
Resolv::DNS::Requester::RequestError,
-
Resolv::DNS::EncodeError,
-
Resolv::DNS::DecodeError].freeze
-
-
23
DONE = 1
-
23
ERROR = 2
-
-
23
class << self
-
23
def multi?
-
21
false
-
end
-
end
-
-
23
attr_reader :state
-
-
23
def_delegator :@connections, :empty?
-
-
23
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
-
-
23
def resolvers
-
return enum_for(__method__) unless block_given?
-
-
yield self
-
end
-
-
23
def multi
-
self
-
end
-
-
23
def empty?
-
true
-
end
-
-
23
def close
-
transition(:closed)
-
end
-
-
23
def closed?
-
@state == :closed
-
end
-
-
23
def to_io
-
@pipe_read.to_io
-
end
-
-
23
def call
-
case @state
-
when :open
-
consume
-
end
-
nil
-
end
-
-
23
def interests
-
return if @queries.empty?
-
-
:r
-
end
-
-
23
def timeout
-
return unless @queries.empty?
-
-
_, connection = @queries.first
-
-
return unless connection
-
-
@timeouts[connection.peer.host].first
-
end
-
-
23
def <<(connection)
-
21
@connections << connection
-
21
resolve
-
end
-
-
23
def early_resolve(connection, **)
-
21
self << connection
-
10
true
-
end
-
-
23
def handle_socket_timeout(interval)
-
error = HTTPX::ResolveTimeoutError.new(interval, "timed out while waiting on select")
-
error.set_backtrace(caller)
-
on_error(error)
-
end
-
-
23
private
-
-
23
def transition(nextstate)
-
21
case nextstate
-
when :idle
-
@timeouts.clear
-
when :open
-
21
return unless @state == :idle
-
-
21
@pipe_read, @pipe_write = ::IO.pipe
-
when :closed
-
return unless @state == :open
-
-
@pipe_write.close
-
@pipe_read.close
-
end
-
21
@state = nextstate
-
end
-
-
23
def consume
-
21
return if @connections.empty?
-
-
21
if @pipe_read.wait_readable
-
21
event = @pipe_read.getbyte
-
-
21
case event
-
when DONE
-
20
*pair, addrs = @pipe_mutex.synchronize { @ips.pop }
-
10
@queries.delete(pair)
-
10
_, connection = pair
-
10
@connections.delete(connection)
-
-
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
@connections.delete(connection)
-
-
11
_, connection = pair
-
11
emit_resolve_error(connection, connection.peer.host, error)
-
end
-
end
-
-
10
return emit(:close, self) if @connections.empty?
-
-
resolve
-
end
-
-
23
def resolve(connection = @connections.first)
-
21
raise Error, "no URI to resolve" unless connection
-
21
return unless @queries.empty?
-
-
21
hostname = connection.peer.host
-
21
scheme = connection.origin.scheme
-
21
log { "resolver: resolve IDN #{connection.peer.non_ascii_hostname} as #{hostname}" } if connection.peer.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
-
-
23
def async_resolve(connection, hostname, scheme)
-
21
families = connection.options.ip_families
-
21
log { "resolver: query for #{hostname}" }
-
21
timeouts = @timeouts[connection.peer.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
-
-
23
def __addrinfo_resolve(host, scheme)
-
21
Addrinfo.getaddrinfo(host, scheme, Socket::AF_UNSPEC, Socket::SOCK_STREAM)
-
end
-
-
23
def emit_connection_error(_, error)
-
11
throw(:resolve_error, error)
-
end
-
-
23
def close_resolver(resolver); end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "objspace"
-
23
require "stringio"
-
23
require "tempfile"
-
23
require "fileutils"
-
23
require "forwardable"
-
-
23
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).
-
#
-
23
class Response
-
23
extend Forwardable
-
23
include Callbacks
-
-
# the HTTP response status code
-
23
attr_reader :status
-
-
# an HTTPX::Headers object containing the response HTTP headers.
-
23
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
-
23
attr_reader :body
-
-
# The HTTP protocol version used to fetch the response.
-
23
attr_reader :version
-
-
# returns the response body buffered in a string.
-
23
def_delegator :@body, :to_s
-
-
23
def_delegator :@body, :to_str
-
-
# implements the IO reader +#read+ interface.
-
23
def_delegator :@body, :read
-
-
# copies the response body to a different location.
-
23
def_delegator :@body, :copy_to
-
-
# closes the body.
-
23
def_delegator :@body, :close
-
-
# the corresponding request uri.
-
23
def_delegator :@request, :uri
-
-
# the IP address of the peer server.
-
23
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+.
-
23
def initialize(request, status, version, headers)
-
6666
@request = request
-
6666
@options = request.options
-
6666
@version = version
-
6666
@status = Integer(status)
-
6666
@headers = @options.headers_class.new(headers)
-
6666
@body = @options.response_body_class.new(self, @options)
-
6666
@finished = complete?
-
6666
@content_type = nil
-
end
-
-
# merges headers defined in +h+ into the response headers.
-
23
def merge_headers(h)
-
155
@headers = @headers.merge(h)
-
end
-
-
# writes +data+ chunk into the response body.
-
23
def <<(data)
-
8867
@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"
-
23
def content_type
-
6945
@content_type ||= ContentType.new(@headers["content-type"])
-
end
-
-
# returns whether the response has been fully fetched.
-
23
def finished?
-
3581
@finished
-
end
-
-
# marks the response as finished, freezes the headers.
-
23
def finish!
-
3499
@finished = true
-
3499
@headers.freeze
-
end
-
-
# returns whether the response contains body payload.
-
23
def bodyless?
-
6666
@request.verb == "HEAD" ||
-
@status < 200 || # informational response
-
@status == 204 ||
-
@status == 205 ||
-
@status == 304 || begin
-
6327
content_length = @headers["content-length"]
-
6327
return false if content_length.nil?
-
-
5474
content_length == "0"
-
end
-
end
-
-
23
def complete?
-
6666
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
-
23
def error
-
448
return if @status < 400
-
-
41
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
-
23
def raise_for_status
-
418
return self unless (err = error)
-
-
29
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
-
23
def json(*args)
-
99
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".
-
23
def form
-
48
decode(Transcoder::Form)
-
end
-
-
23
def xml
-
# TODO: remove at next major version.
-
6
warn "DEPRECATION WARNING: calling `.#{__method__}` on plain HTTPX responses is deprecated. " \
-
"Use HTTPX.plugin(:xml) sessions and call `.#{__method__}` in its responses instead."
-
6
require "httpx/plugins/xml"
-
6
decode(Plugins::XML::Transcoder)
-
end
-
-
23
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>
-
23
def decode(transcoder, *args)
-
# TODO: check if content-type is a valid format, i.e. "application/json" for json parsing
-
-
165
decoder = transcoder.decode(self)
-
-
147
raise Error, "no decoder available for \"#{transcoder}\"" unless decoder
-
-
147
@body.rewind
-
-
147
decoder.call(self, *args)
-
end
-
end
-
-
# Helper class which decodes the HTTP "content-type" header.
-
23
class ContentType
-
23
MIME_TYPE_RE = %r{^([^/]+/[^;]+)(?:$|;)}.freeze
-
23
CHARSET_RE = /;\s*charset=([^;]+)/i.freeze
-
-
23
def initialize(header_value)
-
6915
@header_value = header_value
-
end
-
-
# returns the mime type declared in the header.
-
#
-
# ContentType.new("application/json; charset=utf-8").mime_type #=> "application/json"
-
23
def mime_type
-
165
return @mime_type if defined?(@mime_type)
-
-
135
m = @header_value.to_s[MIME_TYPE_RE, 1]
-
135
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
-
23
def charset
-
6780
return @charset if defined?(@charset)
-
-
6780
m = @header_value.to_s[CHARSET_RE, 1]
-
6780
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
-
23
class ErrorResponse
-
23
include Loggable
-
23
extend Forwardable
-
-
# the corresponding HTTPX::Request instance.
-
23
attr_reader :request
-
-
# the HTTPX::Response instance, when there is one (i.e. error happens fetching the response).
-
23
attr_reader :response
-
-
# the wrapped exception.
-
23
attr_reader :error
-
-
# the request uri
-
23
def_delegator :@request, :uri
-
-
# the IP address of the peer server.
-
23
def_delegator :@request, :peer_address
-
-
23
def initialize(request, error)
-
885
@request = request
-
885
@response = request.response if request.response.is_a?(Response)
-
885
@error = error
-
885
@options = request.options
-
885
log_exception(@error)
-
end
-
-
# returns the exception full message.
-
23
def to_s
-
7
@error.full_message(highlight: false)
-
end
-
-
# closes the error resources.
-
23
def close
-
30
@response.close if @response && @response.respond_to?(:close)
-
end
-
-
# always true for error responses.
-
23
def finished?
-
6
true
-
end
-
-
# raises the wrapped exception.
-
23
def raise_for_status
-
58
raise @error
-
end
-
-
# buffers lost chunks to error response
-
23
def <<(data)
-
6
@response << data
-
end
-
end
-
end
-
-
23
require_relative "response/body"
-
23
require_relative "response/buffer"
-
23
require_relative "pmatch_extensions" if RUBY_VERSION >= "2.7.0"
-
# frozen_string_literal: true
-
-
23
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).
-
23
class Response::Body
-
# the payload encoding (i.e. "utf-8", "ASCII-8BIT")
-
23
attr_reader :encoding
-
-
# Array of encodings contained in the response "content-encoding" header.
-
23
attr_reader :encodings
-
-
# initialized with the corresponding HTTPX::Response +response+ and HTTPX::Options +options+.
-
23
def initialize(response, options)
-
6780
@response = response
-
6780
@headers = response.headers
-
6780
@options = options
-
6780
@window_size = options.window_size
-
6780
@encodings = []
-
6780
@length = 0
-
6780
@buffer = nil
-
6780
@reader = nil
-
6780
@state = :idle
-
-
# initialize response encoding
-
6780
@encoding = if (enc = response.content_type.charset)
-
167
begin
-
1144
Encoding.find(enc)
-
rescue ArgumentError
-
24
Encoding::BINARY
-
end
-
else
-
5636
Encoding::BINARY
-
end
-
-
6780
initialize_inflaters
-
end
-
-
23
def initialize_dup(other)
-
24
super
-
-
24
@buffer = other.instance_variable_get(:@buffer).dup
-
end
-
-
23
def closed?
-
222
@state == :closed
-
end
-
-
# write the response payload +chunk+ into the buffer. Inflates the chunk when required
-
# and supported.
-
23
def write(chunk)
-
8724
return if @state == :closed
-
-
8724
return 0 if chunk.empty?
-
-
8410
chunk = decode_chunk(chunk)
-
-
8410
size = chunk.bytesize
-
8410
@length += size
-
8410
transition(:open)
-
8410
@buffer.write(chunk)
-
-
8410
@response.emit(:chunk_received, chunk)
-
8398
size
-
end
-
-
# reads a chunk from the payload (implementation of the IO reader protocol).
-
23
def read(*args)
-
233
return unless @buffer
-
-
233
unless @reader
-
93
rewind
-
93
@reader = @buffer
-
end
-
-
233
@reader.read(*args)
-
end
-
-
# size of the decoded response payload. May differ from "content-length" header if
-
# response was encoded over-the-wire.
-
23
def bytesize
-
169
@length
-
end
-
-
# yields the payload in chunks.
-
23
def each
-
48
return enum_for(__method__) unless block_given?
-
-
5
begin
-
36
if @buffer
-
36
rewind
-
96
while (chunk = @buffer.read(@window_size))
-
36
yield(chunk.force_encoding(@encoding))
-
end
-
end
-
ensure
-
36
close
-
end
-
end
-
-
# returns the declared filename in the "contennt-disposition" header, when present.
-
23
def filename
-
36
return unless @headers.key?("content-disposition")
-
-
30
Utils.get_filename(@headers["content-disposition"])
-
end
-
-
# returns the full response payload as a string.
-
23
def to_s
-
3338
return "".b unless @buffer
-
-
3099
@buffer.to_s
-
end
-
-
23
alias_method :to_str, :to_s
-
-
# whether the payload is empty.
-
23
def empty?
-
24
@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"))
-
23
def copy_to(dest)
-
36
return unless @buffer
-
-
36
rewind
-
-
36
if dest.respond_to?(:path) && @buffer.respond_to?(:path)
-
6
FileUtils.mv(@buffer.path, dest.path)
-
else
-
30
::IO.copy_stream(@buffer, dest)
-
end
-
end
-
-
# closes/cleans the buffer, resets everything
-
23
def close
-
506
if @buffer
-
375
@buffer.close
-
375
@buffer = nil
-
end
-
506
@length = 0
-
506
transition(:closed)
-
end
-
-
23
def ==(other)
-
88
object_id == other.object_id || begin
-
88
if other.respond_to?(:read)
-
60
_with_same_buffer_pos { FileUtils.compare_stream(@buffer, other) }
-
else
-
58
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.
-
23
def rewind
-
342
return unless @buffer
-
-
# in case there's some reading going on
-
342
@reader = nil
-
-
342
@buffer.rewind
-
end
-
-
23
private
-
-
# prepares inflaters for the advertised encodings in "content-encoding" header.
-
23
def initialize_inflaters
-
6780
@inflaters = nil
-
-
6780
return unless @headers.key?("content-encoding")
-
-
144
return unless @options.decompress_response_body
-
-
132
@inflaters = @headers.get("content-encoding").filter_map do |encoding|
-
132
next if encoding == "identity"
-
-
132
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.
-
132
break unless inflater
-
-
132
@encodings << encoding
-
132
inflater
-
end
-
end
-
-
# passes the +chunk+ through all inflaters to decode it.
-
23
def decode_chunk(chunk)
-
@inflaters.reverse_each do |inflater|
-
387
chunk = inflater.call(chunk)
-
8528
end if @inflaters
-
-
8529
chunk
-
end
-
-
# tries transitioning the body STM to the +nextstate+.
-
23
def transition(nextstate)
-
8916
case nextstate
-
when :open
-
8410
return unless @state == :idle
-
-
5241
@buffer = Response::Buffer.new(
-
threshold_size: @options.body_threshold_size,
-
bytesize: @length,
-
encoding: @encoding
-
)
-
when :closed
-
506
return if @state == :closed
-
end
-
-
5747
@state = nextstate
-
end
-
-
23
def _with_same_buffer_pos # :nodoc:
-
30
return yield unless @buffer && @buffer.respond_to?(:pos)
-
-
# @type ivar @buffer: StringIO | Tempfile
-
30
current_pos = @buffer.pos
-
30
@buffer.rewind
-
4
begin
-
30
yield
-
ensure
-
30
@buffer.pos = current_pos
-
end
-
end
-
-
23
class << self
-
23
def initialize_inflater_by_encoding(encoding, response, **kwargs) # :nodoc:
-
132
case encoding
-
when "gzip"
-
120
Transcoder::GZIP.decode(response, **kwargs)
-
when "deflate"
-
12
Transcoder::Deflate.decode(response, **kwargs)
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "delegate"
-
23
require "stringio"
-
23
require "tempfile"
-
-
23
module HTTPX
-
# wraps and delegates to an internal buffer, which can be a StringIO or a Tempfile.
-
23
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+.
-
23
def initialize(threshold_size:, bytesize: 0, encoding: Encoding::BINARY)
-
5391
@threshold_size = threshold_size
-
5391
@bytesize = bytesize
-
5391
@encoding = encoding
-
5391
@buffer = StringIO.new("".b)
-
5391
super(@buffer)
-
end
-
-
23
def initialize_dup(other)
-
24
super
-
-
24
@buffer = other.instance_variable_get(:@buffer).dup
-
end
-
-
# size in bytes of the buffered content.
-
23
def size
-
254
@bytesize
-
end
-
-
# writes the +chunk+ into the buffer.
-
23
def write(chunk)
-
8697
@bytesize += chunk.bytesize
-
8697
try_upgrade_buffer
-
8697
@buffer.write(chunk)
-
end
-
-
# returns the buffered content as a string.
-
23
def to_s
-
3171
case @buffer
-
when StringIO
-
475
begin
-
3111
@buffer.string.force_encoding(@encoding)
-
rescue ArgumentError
-
@buffer.string
-
end
-
when Tempfile
-
60
rewind
-
120
content = _with_same_buffer_pos { @buffer.read }
-
9
begin
-
60
content.force_encoding(@encoding)
-
rescue ArgumentError # ex: unknown encoding name - utf
-
content
-
end
-
end
-
end
-
-
# closes the buffer.
-
23
def close
-
459
@buffer.close
-
459
@buffer.unlink if @buffer.respond_to?(:unlink)
-
end
-
-
23
private
-
-
# initializes the buffer into a StringIO, or turns it into a Tempfile when the threshold
-
# has been reached.
-
23
def try_upgrade_buffer
-
8697
return unless @bytesize > @threshold_size
-
-
381
return if @buffer.is_a?(Tempfile)
-
-
123
aux = @buffer
-
-
123
@buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
-
123
if aux
-
123
aux.rewind
-
123
::IO.copy_stream(aux, @buffer)
-
123
aux.close
-
end
-
-
123
__setobj__(@buffer)
-
end
-
-
23
def _with_same_buffer_pos # :nodoc:
-
60
current_pos = @buffer.pos
-
60
@buffer.rewind
-
9
begin
-
60
yield
-
ensure
-
60
@buffer.pos = current_pos
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "io/wait"
-
-
23
module HTTPX
-
23
class Selector
-
23
extend Forwardable
-
-
23
READABLE = %i[rw r].freeze
-
23
WRITABLE = %i[rw w].freeze
-
-
23
private_constant :READABLE
-
23
private_constant :WRITABLE
-
-
23
def_delegator :@timers, :after
-
-
23
def_delegator :@selectables, :empty?
-
-
23
def initialize
-
5409
@timers = Timers.new
-
5409
@selectables = []
-
end
-
-
23
def each(&blk)
-
@selectables.each(&blk)
-
end
-
-
23
def next_tick
-
3345336
catch(:jump_tick) do
-
3345336
timeout = next_timeout
-
3345336
if timeout && timeout.negative?
-
@timers.fire
-
throw(:jump_tick)
-
end
-
-
1313616
begin
-
3345336
select(timeout, &:call)
-
3345167
@timers.fire
-
rescue TimeoutError => e
-
@timers.fire(e)
-
end
-
end
-
rescue StandardError => e
-
91
emit_error(e)
-
rescue Exception # rubocop:disable Lint/RescueException
-
78
each_connection(&:force_reset)
-
78
raise
-
end
-
-
23
def terminate
-
# array may change during iteration
-
5117
selectables = @selectables.reject(&:inflight?)
-
-
5117
selectables.each(&:terminate)
-
-
5111
until selectables.empty?
-
2011
next_tick
-
-
2011
selectables &= @selectables
-
end
-
end
-
-
23
def find_resolver(options)
-
5082
res = @selectables.find do |c|
-
44
c.is_a?(Resolver::Resolver) && options == c.options
-
end
-
-
5082
res.multi if res
-
end
-
-
23
def each_connection(&block)
-
24341
return enum_for(__method__) unless block
-
-
12358
@selectables.each do |c|
-
1769
if c.is_a?(Resolver::Resolver)
-
170
c.each_connection(&block)
-
else
-
1599
yield c
-
end
-
end
-
end
-
-
23
def find_connection(request_uri, options)
-
6757
each_connection.find do |connection|
-
1056
connection.match?(request_uri, options)
-
end
-
end
-
-
23
def find_mergeable_connection(connection)
-
5226
each_connection.find do |ch|
-
232
ch != connection && ch.mergeable?(connection)
-
end
-
end
-
-
23
def empty?
-
762
@selectables.empty?
-
end
-
-
# deregisters +io+ from selectables.
-
23
def deregister(io)
-
6103
@selectables.delete(io)
-
end
-
-
# register +io+.
-
23
def register(io)
-
6231
return if @selectables.include?(io)
-
-
5949
@selectables << io
-
end
-
-
23
private
-
-
23
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.
-
3345336
return if interval.nil? && @selectables.empty?
-
-
3343325
return select_one(interval, &block) if @selectables.size == 1
-
-
261
select_many(interval, &block)
-
end
-
-
23
def select_many(interval, &block)
-
261
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
-
begin
-
261
@selectables.delete_if do |io|
-
333
interests = io.interests
-
-
333
(r ||= []) << io if READABLE.include?(interests)
-
333
(w ||= []) << io if WRITABLE.include?(interests)
-
-
333
io.state == :closed
-
end
-
-
# TODO: what to do if there are no selectables?
-
-
261
readers, writers = IO.select(r, w, nil, interval)
-
-
261
if readers.nil? && writers.nil? && interval
-
103
[*r, *w].each { |io| io.handle_socket_timeout(interval) }
-
103
return
-
end
-
end
-
-
158
if writers
-
readers.each do |io|
-
91
yield io
-
-
# so that we don't yield 2 times
-
91
writers.delete(io)
-
157
end if readers
-
-
158
writers.each(&block)
-
else
-
readers.each(&block) if readers
-
end
-
end
-
-
23
def select_one(interval)
-
3343064
io = @selectables.first
-
-
3343064
return unless io
-
-
3343064
interests = io.interests
-
-
3343064
result = case interests
-
9708
when :r then io.to_io.wait_readable(interval)
-
7121
when :w then io.to_io.wait_writable(interval)
-
when :rw then io.to_io.wait(interval, :read_write)
-
3326235
when nil then return
-
end
-
-
16829
unless result || interval.nil?
-
417
io.handle_socket_timeout(interval)
-
417
return
-
end
-
# raise TimeoutError.new(interval, "timed out while waiting on select")
-
-
16412
yield io
-
# rescue IOError, SystemCallError
-
# @selectables.reject!(&:closed?)
-
# raise unless @selectables.empty?
-
end
-
-
23
def next_timeout
-
[
-
2031719
@timers.wait_interval,
-
@selectables.filter_map(&:timeout).min,
-
1313616
].compact.min
-
end
-
-
23
def emit_error(e)
-
91
@selectables.each do |c|
-
next if c.is_a?(Resolver::Resolver)
-
-
c.emit(:error, e)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
# 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
-
23
class Session
-
23
include Loggable
-
23
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.
-
23
def initialize(options = EMPTY_HASH, &blk)
-
7922
@options = self.class.default_options.merge(options)
-
7922
@responses = {}
-
7922
@persistent = @options.persistent
-
7922
@pool = @options.pool_class.new(@options.pool_options)
-
7922
@wrapped = false
-
7922
@closing = false
-
7922
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
-
23
def wrap
-
395
prev_wrapped = @wrapped
-
395
@wrapped = true
-
395
was_initialized = false
-
395
current_selector = get_current_selector do
-
395
selector = Selector.new
-
-
395
set_current_selector(selector)
-
-
395
was_initialized = true
-
-
395
selector
-
end
-
50
begin
-
395
yield self
-
ensure
-
395
unless prev_wrapped
-
395
if @persistent
-
1
deactivate(current_selector)
-
else
-
394
close(current_selector)
-
end
-
end
-
395
@wrapped = prev_wrapped
-
395
set_current_selector(nil) if was_initialized
-
end
-
end
-
-
# closes all the active connections from the session.
-
#
-
# when called directly without specifying +selector+, all available connections
-
# will be picked up from the connection pool and closed. Connections in use
-
# by other sessions, or same session in a different thread, will not be reaped.
-
23
def close(selector = Selector.new)
-
# throw resolvers away from the pool
-
5117
@pool.reset_resolvers
-
-
# preparing to throw away connections
-
12262
while (connection = @pool.pop_connection)
-
3290
next if connection.state == :closed
-
-
120
connection.current_session = self
-
120
connection.current_selector = selector
-
120
select_connection(connection, selector)
-
end
-
763
begin
-
5117
@closing = true
-
5117
selector.terminate
-
ensure
-
5117
@closing = false
-
end
-
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" })
-
#
-
23
def request(*args, **params)
-
5303
raise ArgumentError, "must perform at least one request" if args.empty?
-
-
5303
requests = args.first.is_a?(Request) ? args : build_requests(*args, params)
-
5282
responses = send_requests(*requests)
-
5193
return responses.first if responses.size == 1
-
-
146
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)
-
23
def build_request(verb, uri, params = EMPTY_HASH, options = @options)
-
6492
rklass = options.request_class
-
6492
request = rklass.new(verb, uri, options, params)
-
6471
request.persistent = @persistent
-
6471
set_request_callbacks(request)
-
6471
request
-
end
-
-
23
def select_connection(connection, selector)
-
6231
selector.register(connection)
-
end
-
-
23
alias_method :select_resolver, :select_connection
-
-
23
def deselect_connection(connection, selector, cloned = false)
-
5832
selector.deregister(connection)
-
-
# when connections coalesce
-
5832
return if connection.state == :idle
-
-
5801
return if cloned
-
-
5795
return if @closing && connection.state == :closed
-
-
5789
@pool.checkin_connection(connection)
-
end
-
-
23
def deselect_resolver(resolver, selector)
-
271
selector.deregister(resolver)
-
-
271
return if @closing && resolver.closed?
-
-
271
@pool.checkin_resolver(resolver)
-
end
-
-
23
def try_clone_connection(connection, selector, family)
-
353
connection.family ||= family
-
-
353
return connection if connection.family == family
-
-
new_connection = connection.class.new(connection.origin, connection.options)
-
-
new_connection.family = family
-
new_connection.current_session = self
-
new_connection.current_selector = selector
-
-
connection.once(:tcp_open) { new_connection.force_reset(true) }
-
connection.once(:connect_error) do |err|
-
if new_connection.connecting?
-
new_connection.merge(connection)
-
connection.emit(:cloned, new_connection)
-
connection.force_reset(true)
-
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(true)
-
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(true)
-
else
-
new_connection.__send__(:handle_error, err)
-
end
-
end
-
-
do_init_connection(new_connection, selector)
-
new_connection
-
end
-
-
# returns the HTTPX::Connection through which the +request+ should be sent through.
-
23
def find_connection(request_uri, selector, options)
-
6757
if (connection = selector.find_connection(request_uri, options))
-
1011
return connection
-
end
-
-
5746
connection = @pool.checkout_connection(request_uri, options)
-
-
5728
connection.current_session = self
-
5728
connection.current_selector = selector
-
-
5728
case connection.state
-
when :idle
-
5219
do_init_connection(connection, selector)
-
when :open
-
50
select_connection(connection, selector) if options.io
-
when :closed
-
454
connection.idling
-
454
select_connection(connection, selector)
-
when :closing
-
connection.once(:close) do
-
connection.idling
-
select_connection(connection, selector)
-
end
-
end
-
-
5678
connection
-
end
-
-
23
private
-
-
23
def deactivate(selector)
-
297
selector.each_connection do |connection|
-
255
connection.deactivate
-
255
deselect_connection(connection, selector) if connection.state == :inactive
-
end
-
end
-
-
# callback executed when a response for a given request has been received.
-
23
def on_response(request, response)
-
6683
@responses[request] = response
-
end
-
-
# callback executed when an HTTP/2 promise frame has been received.
-
23
def on_promise(_, stream)
-
6
log(level: 2) { "#{stream.id}: refusing stream!" }
-
6
stream.refuse
-
end
-
-
# returns the corresponding HTTP::Response to the given +request+ if it has been received.
-
23
def fetch_response(request, _selector, _options)
-
3349354
@responses.delete(request)
-
end
-
-
# sends the +request+ to the corresponding HTTPX::Connection
-
23
def send_request(request, selector, options = request.options)
-
895
error = begin
-
6704
catch(:resolve_error) do
-
6704
connection = find_connection(request.uri, selector, options)
-
6618
connection.send(request)
-
end
-
rescue StandardError => e
-
24
e
-
end
-
6699
return unless error && error.is_a?(Exception)
-
-
86
if error.is_a?(Error)
-
86
request.emit(:response, ErrorResponse.new(request, error))
-
else
-
raise error if selector.empty?
-
end
-
end
-
-
# returns a set of HTTPX::Request objects built from the given +args+ and +options+.
-
23
def build_requests(*args, params)
-
4906
requests = if args.size == 1
-
59
reqs = args.first
-
59
reqs.map do |verb, uri, ps = EMPTY_HASH|
-
118
request_params = params
-
118
request_params = request_params.merge(ps) unless ps.empty?
-
118
build_request(verb, uri, request_params)
-
end
-
else
-
4847
verb, uris = args
-
4847
if uris.respond_to?(:each)
-
4667
uris.enum_for(:each).map do |uri, ps = EMPTY_HASH|
-
5375
request_params = params
-
5375
request_params = request_params.merge(ps) unless ps.empty?
-
5375
build_request(verb, uri, request_params)
-
end
-
else
-
180
[build_request(verb, uris, params)]
-
end
-
end
-
4885
raise ArgumentError, "wrong number of URIs (given 0, expect 1..+1)" if requests.empty?
-
-
4885
requests
-
end
-
-
23
def set_request_callbacks(request)
-
6471
request.on(:response, &method(:on_response).curry(2)[request])
-
6471
request.on(:promise, &method(:on_promise))
-
end
-
-
23
def do_init_connection(connection, selector)
-
5219
resolve_connection(connection, selector) unless connection.family
-
end
-
-
# sends an array of HTTPX::Request +requests+, returns the respective array of HTTPX::Response objects.
-
23
def send_requests(*requests)
-
10215
selector = get_current_selector { Selector.new }
-
779
begin
-
5356
_send_requests(requests, selector)
-
5351
receive_requests(requests, selector)
-
ensure
-
5356
unless @wrapped
-
4864
if @persistent
-
296
deactivate(selector)
-
else
-
4568
close(selector)
-
end
-
end
-
end
-
end
-
-
# sends an array of HTTPX::Request objects
-
23
def _send_requests(requests, selector)
-
5356
requests.each do |request|
-
6112
send_request(request, selector)
-
end
-
end
-
-
# returns the array of HTTPX::Response objects corresponding to the array of HTTPX::Request +requests+.
-
23
def receive_requests(requests, selector)
-
# @type var responses: Array[response]
-
5351
responses = []
-
-
# guarantee ordered responses
-
5351
loop do
-
6113
request = requests.first
-
-
6113
return responses unless request
-
-
3348494
catch(:coalesced) { selector.next_tick } until (response = fetch_response(request, selector, request.options))
-
6029
request.emit(:complete, response)
-
-
6029
responses << response
-
6029
requests.shift
-
-
6029
break if requests.empty?
-
-
762
next unless selector.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, selector, request.options)
-
request.emit(:complete, response) if response
-
responses << response
-
end
-
break
-
end
-
5267
responses
-
end
-
-
23
def resolve_connection(connection, selector)
-
5239
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.
-
#
-
157
connection.once(:connect_error, &connection.method(:handle_error))
-
157
on_resolver_connection(connection, selector)
-
157
return
-
end
-
-
5082
resolver = find_resolver_for(connection, selector)
-
-
5082
resolver.early_resolve(connection) || resolver.lazy_resolve(connection)
-
end
-
-
23
def on_resolver_connection(connection, selector)
-
5226
from_pool = false
-
5226
found_connection = selector.find_mergeable_connection(connection) || begin
-
5203
from_pool = true
-
5203
@pool.checkout_mergeable_connection(connection)
-
end
-
-
5226
return select_connection(connection, selector) unless found_connection
-
-
23
if found_connection.open?
-
22
coalesce_connections(found_connection, connection, selector, from_pool)
-
else
-
1
found_connection.once(:open) do
-
1
coalesce_connections(found_connection, connection, selector, from_pool)
-
end
-
end
-
end
-
-
23
def on_resolver_close(resolver, selector)
-
271
return if resolver.closed?
-
-
271
deselect_resolver(resolver, selector)
-
271
resolver.close unless resolver.closed?
-
end
-
-
23
def find_resolver_for(connection, selector)
-
5082
resolver = selector.find_resolver(connection.options)
-
-
5082
unless resolver
-
5080
resolver = @pool.checkout_resolver(connection.options)
-
5080
resolver.current_session = self
-
5080
resolver.current_selector = selector
-
end
-
-
5082
resolver
-
end
-
-
# coalesces +conn2+ into +conn1+. if +conn1+ was loaded from the connection pool
-
# (it is known via +from_pool+), then it adds its to the +selector+.
-
23
def coalesce_connections(conn1, conn2, selector, from_pool)
-
23
unless conn1.coalescable?(conn2)
-
12
select_connection(conn2, selector)
-
12
@pool.checkin_connection(conn1) if from_pool
-
12
return false
-
end
-
-
11
conn2.emit(:tcp_open, conn1)
-
11
conn1.merge(conn2)
-
11
conn2.coalesced_connection = conn1
-
11
select_connection(conn1, selector) if from_pool
-
11
deselect_connection(conn2, selector)
-
11
true
-
end
-
-
23
def get_current_selector
-
5751
selector_store[self] || (yield if block_given?)
-
end
-
-
23
def set_current_selector(selector)
-
1082
if selector
-
687
selector_store[self] = selector
-
else
-
395
selector_store.delete(self)
-
end
-
end
-
-
23
def selector_store
-
6833
th_current = Thread.current
-
6833
th_current.thread_variable_get(:httpx_persistent_selector_store) || begin
-
85
{}.compare_by_identity.tap do |store|
-
85
th_current.thread_variable_set(:httpx_persistent_selector_store, store)
-
end
-
end
-
end
-
-
23
@default_options = Options.new
-
23
@default_options.freeze
-
23
@plugins = []
-
-
23
class << self
-
23
attr_reader :default_options
-
-
23
def inherited(klass)
-
4021
super
-
4021
klass.instance_variable_set(:@default_options, @default_options)
-
4021
klass.instance_variable_set(:@plugins, @plugins.dup)
-
4021
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)
-
#
-
23
def plugin(pl, options = nil, &block)
-
# raise Error, "Cannot add a plugin to a frozen config" if frozen?
-
5439
pl = Plugins.load_plugin(pl) if pl.is_a?(Symbol)
-
5439
if !@plugins.include?(pl)
-
5249
@plugins << pl
-
5249
pl.load_dependencies(self, &block) if pl.respond_to?(:load_dependencies)
-
-
5249
@default_options = @default_options.dup
-
-
5249
include(pl::InstanceMethods) if defined?(pl::InstanceMethods)
-
5249
extend(pl::ClassMethods) if defined?(pl::ClassMethods)
-
-
5249
opts = @default_options
-
5249
opts.extend_with_plugin_classes(pl)
-
5249
if defined?(pl::OptionsMethods)
-
-
2161
(pl::OptionsMethods.instance_methods - Object.instance_methods).each do |meth|
-
6217
opts.options_class.method_added(meth)
-
end
-
2161
@default_options = opts.options_class.new(opts)
-
end
-
-
5249
@default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
-
5249
@default_options = @default_options.merge(options) if options
-
-
5249
pl.configure(self, &block) if pl.respond_to?(:configure)
-
-
5249
@default_options.freeze
-
189
elsif options
-
# this can happen when two plugins are loaded, an one of them calls the other under the hood,
-
# albeit changing some default.
-
12
@default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
-
12
@default_options = @default_options.merge(options) if options
-
-
12
@default_options.freeze
-
end
-
5439
self
-
end
-
end
-
end
-
-
# session may be overridden by certain adapters.
-
23
S = Session
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
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
-
-
23
module HTTPX
-
23
class Timers
-
23
def initialize
-
5409
@intervals = []
-
end
-
-
23
def after(interval_in_secs, cb = nil, &blk)
-
33333
return unless interval_in_secs
-
-
33333
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.
-
61188
unless (interval = @intervals.find { |t| t.interval == interval_in_secs })
-
6455
interval = Interval.new(interval_in_secs)
-
12658
interval.on_empty { @intervals.delete(interval) }
-
6455
@intervals << interval
-
6455
@intervals.sort!
-
end
-
-
33333
interval << callback
-
-
33333
@next_interval_at = nil
-
-
33333
interval
-
end
-
-
23
def wait_interval
-
3345336
return if @intervals.empty?
-
-
3329743
@next_interval_at = Utils.now
-
-
3329743
@intervals.first.interval
-
end
-
-
23
def fire(error = nil)
-
3345167
raise error if error && error.timeout != @intervals.first
-
3345167
return if @intervals.empty? || !@next_interval_at
-
-
3324917
elapsed_time = Utils.elapsed_time(@next_interval_at)
-
-
6649847
@intervals = @intervals.drop_while { |interval| interval.elapse(elapsed_time) <= 0 }
-
-
3324917
@next_interval_at = nil if @intervals.empty?
-
end
-
-
23
class Interval
-
23
include Comparable
-
-
23
attr_reader :interval
-
-
23
def initialize(interval)
-
6455
@interval = interval
-
6455
@callbacks = []
-
6455
@on_empty = nil
-
end
-
-
23
def on_empty(&blk)
-
6455
@on_empty = blk
-
end
-
-
23
def <=>(other)
-
555
@interval <=> other.interval
-
end
-
-
23
def ==(other)
-
1844
return @interval == other if other.is_a?(Numeric)
-
-
1844
@interval == other.to_f # rubocop:disable Lint/FloatComparison
-
end
-
-
23
def to_f
-
1844
Float(@interval)
-
end
-
-
23
def <<(callback)
-
33333
@callbacks << callback
-
end
-
-
23
def delete(callback)
-
49288
@callbacks.delete(callback)
-
49288
@on_empty.call if @callbacks.empty?
-
end
-
-
23
def no_callbacks?
-
49288
@callbacks.empty?
-
end
-
-
23
def elapsed?
-
930
@interval <= 0
-
end
-
-
23
def elapse(elapsed)
-
3324930
@interval -= elapsed
-
-
3324930
if @interval <= 0
-
416
cb = @callbacks.dup
-
416
cb.each(&:call)
-
end
-
-
3324930
@interval
-
end
-
end
-
23
private_constant :Interval
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Transcoder
-
23
module_function
-
-
23
def normalize_keys(key, value, cond = nil, &block)
-
2570
if cond && cond.call(value)
-
803
block.call(key.to_s, value)
-
1766
elsif value.respond_to?(:to_ary)
-
341
if value.empty?
-
96
block.call("#{key}[]")
-
else
-
245
value.to_ary.each do |element|
-
394
normalize_keys("#{key}[]", element, cond, &block)
-
end
-
end
-
1425
elsif value.respond_to?(:to_hash)
-
384
value.to_hash.each do |child_key, child_value|
-
384
normalize_keys("#{key}[#{child_key}]", child_value, cond, &block)
-
end
-
else
-
1042
block.call(key.to_s, value)
-
end
-
end
-
-
# based on https://github.com/rack/rack/blob/d15dd728440710cfc35ed155d66a98dc2c07ae42/lib/rack/query_parser.rb#L82
-
23
def normalize_query(params, name, v, depth)
-
138
raise Error, "params depth surpasses what's supported" if depth <= 0
-
-
138
name =~ /\A[\[\]]*([^\[\]]+)\]*/
-
138
k = Regexp.last_match(1) || ""
-
138
after = Regexp.last_match ? Regexp.last_match.post_match : ""
-
-
138
if k.empty?
-
12
return Array(v) if !v.empty? && name == "[]"
-
-
6
return
-
end
-
-
126
case after
-
when ""
-
42
params[k] = v
-
when "["
-
6
params[name] = v
-
when "[]"
-
12
params[k] ||= []
-
12
raise Error, "expected Array (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Array)
-
-
12
params[k] << v
-
when /^\[\]\[([^\[\]]+)\]$/, /^\[\](.+)$/
-
24
child_key = Regexp.last_match(1)
-
24
params[k] ||= []
-
24
raise Error, "expected Array (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Array)
-
-
24
if params[k].last.is_a?(Hash) && !params_hash_has_key?(params[k].last, child_key)
-
6
normalize_query(params[k].last, child_key, v, depth - 1)
-
else
-
18
params[k] << normalize_query({}, child_key, v, depth - 1)
-
end
-
else
-
42
params[k] ||= {}
-
42
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
-
-
126
params
-
end
-
-
23
def params_hash_has_key?(hash, key)
-
12
return false if key.include?("[]")
-
-
12
key.split(/[\[\]]+/).inject(hash) do |h, part|
-
12
next h if part == ""
-
12
return false unless h.is_a?(Hash) && h.key?(part)
-
-
6
h[part]
-
end
-
-
6
true
-
end
-
end
-
end
-
-
23
require "httpx/transcoder/body"
-
23
require "httpx/transcoder/form"
-
23
require "httpx/transcoder/json"
-
23
require "httpx/transcoder/chunker"
-
23
require "httpx/transcoder/deflate"
-
23
require "httpx/transcoder/gzip"
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
-
23
module HTTPX::Transcoder
-
23
module Body
-
23
class Error < HTTPX::Error; end
-
-
23
module_function
-
-
23
class Encoder
-
23
extend Forwardable
-
-
23
def_delegator :@raw, :to_s
-
-
23
def_delegator :@raw, :==
-
-
23
def initialize(body)
-
968
@raw = body
-
end
-
-
23
def bytesize
-
3602
if @raw.respond_to?(:bytesize)
-
1871
@raw.bytesize
-
1730
elsif @raw.respond_to?(:to_ary)
-
717
@raw.sum(&:bytesize)
-
1013
elsif @raw.respond_to?(:size)
-
600
@raw.size || Float::INFINITY
-
413
elsif @raw.respond_to?(:length)
-
192
@raw.length || Float::INFINITY
-
221
elsif @raw.respond_to?(:each)
-
216
Float::INFINITY
-
else
-
6
raise Error, "cannot determine size of body: #{@raw.inspect}"
-
end
-
end
-
-
23
def content_type
-
932
"application/octet-stream"
-
end
-
-
23
private
-
-
23
def respond_to_missing?(meth, *args)
-
3553
@raw.respond_to?(meth, *args) || super
-
end
-
-
23
def method_missing(meth, *args, &block)
-
866
return super unless @raw.respond_to?(meth)
-
-
866
@raw.__send__(meth, *args, &block)
-
end
-
end
-
-
23
def encode(body)
-
968
Encoder.new(body)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
-
23
module HTTPX::Transcoder
-
23
module Chunker
-
23
class Error < HTTPX::Error; end
-
-
23
CRLF = "\r\n".b
-
-
23
class Encoder
-
23
extend Forwardable
-
-
23
def initialize(body)
-
72
@raw = body
-
end
-
-
23
def each
-
72
return enum_for(__method__) unless block_given?
-
-
72
@raw.each do |chunk|
-
336
yield "#{chunk.bytesize.to_s(16)}#{CRLF}#{chunk}#{CRLF}"
-
end
-
72
yield "0#{CRLF}"
-
end
-
-
23
def respond_to_missing?(meth, *args)
-
120
@raw.respond_to?(meth, *args) || super
-
end
-
end
-
-
23
class Decoder
-
23
extend Forwardable
-
-
23
def_delegator :@buffer, :empty?
-
-
23
def_delegator :@buffer, :<<
-
-
23
def_delegator :@buffer, :clear
-
-
23
def initialize(buffer, trailers = false)
-
86
@buffer = buffer
-
86
@chunk_buffer = "".b
-
86
@finished = false
-
86
@state = :length
-
86
@trailers = trailers
-
end
-
-
23
def to_s
-
80
@buffer
-
end
-
-
23
def each
-
146
loop do
-
894
case @state
-
when :length
-
256
index = @buffer.index(CRLF)
-
256
return unless index && index.positive?
-
-
# Read hex-length
-
256
hexlen = @buffer.byteslice(0, index)
-
256
@buffer = @buffer.byteslice(index..-1) || "".b
-
256
hexlen[/\h/] || raise(Error, "wrong chunk size line: #{hexlen}")
-
256
@chunk_length = hexlen.hex
-
# check if is last chunk
-
256
@finished = @chunk_length.zero?
-
256
nextstate(:crlf)
-
when :crlf
-
426
crlf_size = @finished && !@trailers ? 4 : 2
-
# consume CRLF
-
426
return if @buffer.bytesize < crlf_size
-
426
raise Error, "wrong chunked encoding format" unless @buffer.start_with?(CRLF * (crlf_size / 2))
-
-
426
@buffer = @buffer.byteslice(crlf_size..-1)
-
426
if @chunk_length.nil?
-
170
nextstate(:length)
-
else
-
256
return if @finished
-
-
176
nextstate(:data)
-
end
-
when :data
-
212
chunk = @buffer.byteslice(0, @chunk_length)
-
212
@buffer = @buffer.byteslice(@chunk_length..-1) || "".b
-
212
@chunk_buffer << chunk
-
212
@chunk_length -= chunk.bytesize
-
212
if @chunk_length.zero?
-
176
yield @chunk_buffer unless @chunk_buffer.empty?
-
170
@chunk_buffer.clear
-
170
@chunk_length = nil
-
170
nextstate(:crlf)
-
end
-
end
-
808
break if @buffer.empty?
-
end
-
end
-
-
23
def finished?
-
140
@finished
-
end
-
-
23
private
-
-
23
def nextstate(state)
-
772
@state = state
-
end
-
end
-
-
23
module_function
-
-
23
def encode(chunks)
-
72
Encoder.new(chunks)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "zlib"
-
23
require_relative "utils/deflater"
-
-
23
module HTTPX
-
23
module Transcoder
-
23
module Deflate
-
23
class Deflater < Transcoder::Deflater
-
23
def deflate(chunk)
-
54
@deflater ||= Zlib::Deflate.new
-
-
54
if chunk.nil?
-
36
unless @deflater.closed?
-
18
last = @deflater.finish
-
18
@deflater.close
-
18
last.empty? ? nil : last
-
end
-
else
-
18
@deflater.deflate(chunk)
-
end
-
end
-
end
-
-
23
module_function
-
-
23
def encode(body)
-
18
Deflater.new(body)
-
end
-
-
23
def decode(response, bytesize: nil)
-
12
bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
-
12
GZIP::Inflater.new(bytesize)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
23
require "uri"
-
23
require_relative "multipart"
-
-
23
module HTTPX
-
23
module Transcoder
-
23
module Form
-
23
module_function
-
-
23
PARAM_DEPTH_LIMIT = 32
-
-
23
class Encoder
-
23
extend Forwardable
-
-
23
def_delegator :@raw, :to_s
-
-
23
def_delegator :@raw, :to_str
-
-
23
def_delegator :@raw, :bytesize
-
-
23
def_delegator :@raw, :==
-
-
23
def initialize(form)
-
533
@raw = form.each_with_object("".b) do |(key, val), buf|
-
893
HTTPX::Transcoder.normalize_keys(key, val) do |k, v|
-
1042
buf << "&" unless buf.empty?
-
1042
buf << URI.encode_www_form_component(k)
-
1042
buf << "=#{URI.encode_www_form_component(v.to_s)}" unless v.nil?
-
end
-
end
-
end
-
-
23
def content_type
-
417
"application/x-www-form-urlencoded"
-
end
-
end
-
-
23
module Decoder
-
23
module_function
-
-
23
def call(response, *)
-
30
URI.decode_www_form(response.to_s).each_with_object({}) do |(field, value), params|
-
72
HTTPX::Transcoder.normalize_query(params, field, value, PARAM_DEPTH_LIMIT)
-
end
-
end
-
end
-
-
23
def encode(form)
-
1249
if multipart?(form)
-
716
Multipart::Encoder.new(form)
-
else
-
533
Encoder.new(form)
-
end
-
end
-
-
23
def decode(response)
-
48
content_type = response.content_type.mime_type
-
-
48
case content_type
-
when "application/x-www-form-urlencoded"
-
30
Decoder
-
when "multipart/form-data"
-
12
Multipart::Decoder.new(response)
-
else
-
6
raise Error, "invalid form mime type (#{content_type})"
-
end
-
end
-
-
23
def multipart?(data)
-
1249
data.any? do |_, v|
-
1657
Multipart::MULTIPART_VALUE_COND.call(v) ||
-
1277
(v.respond_to?(:to_ary) && v.to_ary.any?(&Multipart::MULTIPART_VALUE_COND)) ||
-
1565
(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
-
-
23
require "zlib"
-
-
23
module HTTPX
-
23
module Transcoder
-
23
module GZIP
-
23
class Deflater < Transcoder::Deflater
-
23
def initialize(body)
-
38
@compressed_chunk = "".b
-
38
super
-
end
-
-
23
def deflate(chunk)
-
76
@deflater ||= Zlib::GzipWriter.new(self)
-
-
76
if chunk.nil?
-
38
unless @deflater.closed?
-
38
@deflater.flush
-
38
@deflater.close
-
38
compressed_chunk
-
end
-
else
-
38
@deflater.write(chunk)
-
38
compressed_chunk
-
end
-
end
-
-
23
private
-
-
23
def write(chunk)
-
114
@compressed_chunk << chunk
-
end
-
-
23
def compressed_chunk
-
76
@compressed_chunk.dup
-
ensure
-
76
@compressed_chunk.clear
-
end
-
end
-
-
23
class Inflater
-
23
def initialize(bytesize)
-
132
@inflater = Zlib::Inflate.new(Zlib::MAX_WBITS + 32)
-
132
@bytesize = bytesize
-
end
-
-
23
def call(chunk)
-
387
buffer = @inflater.inflate(chunk)
-
387
@bytesize -= chunk.bytesize
-
387
if @bytesize <= 0
-
84
buffer << @inflater.finish
-
84
@inflater.close
-
end
-
387
buffer
-
end
-
end
-
-
23
module_function
-
-
23
def encode(body)
-
38
Deflater.new(body)
-
end
-
-
23
def decode(response, bytesize: nil)
-
120
bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
-
120
Inflater.new(bytesize)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
-
23
module HTTPX::Transcoder
-
23
module JSON
-
23
module_function
-
-
23
JSON_REGEX = %r{
-
\b
-
application/
-
# optional vendor specific type
-
(?:
-
# token as per https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.6
-
[!#$%&'*+\-.^_`|~0-9a-z]+
-
# literal plus sign
-
\+
-
)?
-
json
-
\b
-
}ix.freeze
-
-
23
class Encoder
-
23
extend Forwardable
-
-
23
def_delegator :@raw, :to_s
-
-
23
def_delegator :@raw, :bytesize
-
-
23
def_delegator :@raw, :==
-
-
23
def initialize(json)
-
63
@raw = JSON.json_dump(json)
-
63
@charset = @raw.encoding.name.downcase
-
end
-
-
23
def content_type
-
63
"application/json; charset=#{@charset}"
-
end
-
end
-
-
23
def encode(json)
-
63
Encoder.new(json)
-
end
-
-
23
def decode(response)
-
99
content_type = response.content_type.mime_type
-
-
99
raise HTTPX::Error, "invalid json mime type (#{content_type})" unless JSON_REGEX.match?(content_type)
-
-
87
method(:json_load)
-
end
-
-
# rubocop:disable Style/SingleLineMethods
-
23
if defined?(MultiJson)
-
4
def json_load(*args); MultiJson.load(*args); end
-
2
def json_dump(*args); MultiJson.dump(*args); end
-
21
elsif defined?(Oj)
-
4
def json_load(response, *args); Oj.load(response.to_s, *args); end
-
2
def json_dump(obj, options = {}); Oj.dump(obj, { mode: :compat }.merge(options)); end
-
20
elsif defined?(Yajl)
-
4
def json_load(response, *args); Yajl::Parser.new(*args).parse(response.to_s); end
-
2
def json_dump(*args); Yajl::Encoder.encode(*args); end
-
else
-
20
require "json"
-
98
def json_load(*args); ::JSON.parse(*args); end
-
80
def json_dump(*args); ::JSON.dump(*args); end
-
end
-
# rubocop:enable Style/SingleLineMethods
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require_relative "multipart/encoder"
-
23
require_relative "multipart/decoder"
-
23
require_relative "multipart/part"
-
23
require_relative "multipart/mime_type_detector"
-
-
23
module HTTPX::Transcoder
-
23
module Multipart
-
23
MULTIPART_VALUE_COND = lambda do |value|
-
3670
value.respond_to?(:read) ||
-
2635
(value.respond_to?(:to_hash) &&
-
value.key?(:body) &&
-
484
(value.key?(:filename) || value.key?(:content_type)))
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "tempfile"
-
23
require "delegate"
-
-
23
module HTTPX
-
23
module Transcoder
-
23
module Multipart
-
23
class FilePart < SimpleDelegator
-
23
attr_reader :original_filename, :content_type
-
-
23
def initialize(filename, content_type)
-
24
@original_filename = filename
-
24
@content_type = content_type
-
24
@file = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
24
super(@file)
-
end
-
end
-
-
23
class Decoder
-
23
include HTTPX::Utils
-
-
23
CRLF = "\r\n"
-
23
BOUNDARY_RE = /;\s*boundary=([^;]+)/i.freeze
-
23
MULTIPART_CONTENT_TYPE = /Content-Type: (.*)#{CRLF}/ni.freeze
-
23
MULTIPART_CONTENT_DISPOSITION = /Content-Disposition:.*;\s*name=(#{VALUE})/ni.freeze
-
23
MULTIPART_CONTENT_ID = /Content-ID:\s*([^#{CRLF}]*)/ni.freeze
-
23
WINDOW_SIZE = 2 << 14
-
-
23
def initialize(response)
-
@boundary = begin
-
12
m = response.headers["content-type"].to_s[BOUNDARY_RE, 1]
-
12
raise Error, "no boundary declared in content-type header" unless m
-
-
12
m.strip
-
end
-
12
@buffer = "".b
-
12
@parts = {}
-
12
@intermediate_boundary = "--#{@boundary}"
-
12
@state = :idle
-
end
-
-
23
def call(response, *)
-
12
response.body.each do |chunk|
-
12
@buffer << chunk
-
-
12
parse
-
end
-
-
12
raise Error, "invalid or unsupported multipart format" unless @buffer.empty?
-
-
12
@parts
-
end
-
-
23
private
-
-
23
def parse
-
12
case @state
-
when :idle
-
12
raise Error, "payload does not start with boundary" unless @buffer.start_with?("#{@intermediate_boundary}#{CRLF}")
-
-
12
@buffer = @buffer.byteslice(@intermediate_boundary.bytesize + 2..-1)
-
-
12
@state = :part_header
-
when :part_header
-
36
idx = @buffer.index("#{CRLF}#{CRLF}")
-
-
# raise Error, "couldn't parse part headers" unless idx
-
36
return unless idx
-
-
36
head = @buffer.byteslice(0..idx + 4 - 1)
-
-
36
@buffer = @buffer.byteslice(head.bytesize..-1)
-
-
36
content_type = head[MULTIPART_CONTENT_TYPE, 1]
-
66
if (name = head[MULTIPART_CONTENT_DISPOSITION, 1])
-
36
name = /\A"(.*)"\Z/ =~ name ? Regexp.last_match(1) : name.dup
-
36
name.gsub!(/\\(.)/, "\\1")
-
6
name
-
else
-
name = head[MULTIPART_CONTENT_ID, 1]
-
end
-
-
36
filename = HTTPX::Utils.get_filename(head)
-
-
36
name = filename || +"#{content_type || "text/plain"}[]" if name.nil? || name.empty?
-
-
36
@current = name
-
-
36
@parts[name] = if filename
-
24
FilePart.new(filename, content_type)
-
else
-
12
"".b
-
end
-
-
36
@state = :part_body
-
when :part_body
-
36
part = @parts[@current]
-
-
36
body_separator = if part.is_a?(FilePart)
-
24
"#{CRLF}#{CRLF}"
-
else
-
12
CRLF
-
end
-
36
idx = @buffer.index(body_separator)
-
-
36
if idx
-
36
payload = @buffer.byteslice(0..idx - 1)
-
36
@buffer = @buffer.byteslice(idx + body_separator.bytesize..-1)
-
36
part << payload
-
36
part.rewind if part.respond_to?(:rewind)
-
36
@state = :parse_boundary
-
else
-
part << @buffer
-
@buffer.clear
-
end
-
when :parse_boundary
-
36
raise Error, "payload does not start with boundary" unless @buffer.start_with?(@intermediate_boundary)
-
-
36
@buffer = @buffer.byteslice(@intermediate_boundary.bytesize..-1)
-
-
36
if @buffer == "--"
-
12
@buffer.clear
-
12
@state = :done
-
12
return
-
23
elsif @buffer.start_with?(CRLF)
-
24
@buffer = @buffer.byteslice(2..-1)
-
24
@state = :part_header
-
else
-
return
-
end
-
when :done
-
raise Error, "parsing should have been over by now"
-
end until @buffer.empty?
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Transcoder::Multipart
-
23
class Encoder
-
23
attr_reader :bytesize
-
-
23
def initialize(form)
-
716
@boundary = ("-" * 21) << SecureRandom.hex(21)
-
716
@part_index = 0
-
716
@buffer = "".b
-
-
716
@form = form
-
716
@parts = to_parts(form)
-
end
-
-
23
def content_type
-
716
"multipart/form-data; boundary=#{@boundary}"
-
end
-
-
23
def to_s
-
15
read
-
ensure
-
15
rewind
-
end
-
-
23
def read(length = nil, outbuf = nil)
-
2923
data = String(outbuf).clear.force_encoding(Encoding::BINARY) if outbuf
-
2923
data ||= "".b
-
-
2923
read_chunks(data, length)
-
-
2923
data unless length && data.empty?
-
end
-
-
23
def rewind
-
39
form = @form.each_with_object([]) do |(key, val), aux|
-
39
if val.respond_to?(:path) && val.respond_to?(:reopen) && val.respond_to?(:closed?) && val.closed?
-
39
val = val.reopen(val.path, File::RDONLY)
-
end
-
39
val.rewind if val.respond_to?(:rewind)
-
39
aux << [key, val]
-
end
-
39
@form = form
-
39
@parts = to_parts(form)
-
39
@part_index = 0
-
end
-
-
23
private
-
-
23
def to_parts(form)
-
755
@bytesize = 0
-
755
params = form.each_with_object([]) do |(key, val), aux|
-
899
Transcoder.normalize_keys(key, val, MULTIPART_VALUE_COND) do |k, v|
-
899
next if v.nil?
-
-
899
value, content_type, filename = Part.call(v)
-
-
899
header = header_part(k, content_type, filename)
-
899
@bytesize += header.size
-
899
aux << header
-
-
899
@bytesize += value.size
-
899
aux << value
-
-
899
delimiter = StringIO.new("\r\n")
-
899
@bytesize += delimiter.size
-
899
aux << delimiter
-
end
-
end
-
755
final_delimiter = StringIO.new("--#{@boundary}--\r\n")
-
755
@bytesize += final_delimiter.size
-
755
params << final_delimiter
-
-
755
params
-
end
-
-
23
def header_part(key, content_type, filename)
-
899
header = "--#{@boundary}\r\n".b
-
899
header << "Content-Disposition: form-data; name=#{key.inspect}".b
-
899
header << "; filename=#{filename.inspect}" if filename
-
899
header << "\r\nContent-Type: #{content_type}\r\n\r\n"
-
899
StringIO.new(header)
-
end
-
-
23
def read_chunks(buffer, length = nil)
-
2923
while @part_index < @parts.size
-
8243
chunk = read_from_part(length)
-
-
8243
next unless chunk
-
-
4831
buffer << chunk.force_encoding(Encoding::BINARY)
-
-
4831
next unless length
-
-
4776
length -= chunk.bytesize
-
-
4776
break if length.zero?
-
end
-
end
-
-
# if there's a current part to read from, tries to read a chunk.
-
23
def read_from_part(max_length = nil)
-
8243
part = @parts[@part_index]
-
-
8243
chunk = part.read(max_length, @buffer)
-
-
8243
return chunk if chunk && !chunk.empty?
-
-
3412
part.close if part.respond_to?(:close)
-
-
3412
@part_index += 1
-
-
552
nil
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Transcoder::Multipart
-
23
module MimeTypeDetector
-
23
module_function
-
-
23
DEFAULT_MIMETYPE = "application/octet-stream"
-
-
# inspired by https://github.com/shrinerb/shrine/blob/master/lib/shrine/plugins/determine_mime_type.rb
-
23
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
-
21
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
-
-
20
elsif defined?(MimeMagic)
-
-
1
def call(file, _)
-
1
mime = MimeMagic.by_magic(file)
-
1
mime.type if mime
-
end
-
-
19
elsif system("which file", out: File::NULL)
-
20
require "open3"
-
-
20
def call(file, _)
-
511
return if file.eof? # file command returns "application/x-empty" for empty files
-
-
477
Open3.popen3(*%w[file --mime-type --brief -]) do |stdin, stdout, stderr, thread|
-
75
begin
-
477
::IO.copy_stream(file, stdin.binmode)
-
rescue Errno::EPIPE
-
end
-
477
file.rewind
-
477
stdin.close
-
-
477
status = thread.value
-
-
# call to file command failed
-
477
if status.nil? || !status.success?
-
$stderr.print(stderr.read)
-
else
-
-
477
output = stdout.read.strip
-
-
477
if output.include?("cannot open")
-
$stderr.print(output)
-
else
-
477
output
-
end
-
end
-
end
-
end
-
-
else
-
-
def call(_, _); end
-
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Transcoder::Multipart
-
23
module Part
-
23
module_function
-
-
23
def call(value)
-
# take out specialized objects of the way
-
899
if value.respond_to?(:filename) && value.respond_to?(:content_type) && value.respond_to?(:read)
-
96
return value, value.content_type, value.filename
-
end
-
-
803
content_type = filename = nil
-
-
803
if value.is_a?(Hash)
-
242
content_type = value[:content_type]
-
242
filename = value[:filename]
-
242
value = value[:body]
-
end
-
-
803
value = value.open(File::RDONLY) if Object.const_defined?(:Pathname) && value.is_a?(Pathname)
-
-
803
if value.respond_to?(:path) && value.respond_to?(:read)
-
# either a File, a Tempfile, or something else which has to quack like a file
-
515
filename ||= File.basename(value.path)
-
515
content_type ||= MimeTypeDetector.call(value, filename) || "application/octet-stream"
-
515
[value, content_type, filename]
-
else
-
288
[StringIO.new(value.to_s), content_type || "text/plain", filename]
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "stringio"
-
-
23
module HTTPX
-
23
module Transcoder
-
23
class BodyReader
-
23
def initialize(body)
-
171
@body = if body.respond_to?(:read)
-
16
body.rewind if body.respond_to?(:rewind)
-
16
body
-
154
elsif body.respond_to?(:each)
-
30
body.enum_for(:each)
-
else
-
125
StringIO.new(body.to_s)
-
end
-
end
-
-
23
def bytesize
-
335
return @body.bytesize if @body.respond_to?(:bytesize)
-
-
305
Float::INFINITY
-
end
-
-
23
def read(length = nil, outbuf = nil)
-
370
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
-
-
23
def close
-
38
@body.close if @body.respond_to?(:close)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require_relative "body_reader"
-
-
23
module HTTPX
-
23
module Transcoder
-
23
class Deflater
-
23
attr_reader :content_type
-
-
23
def initialize(body)
-
66
@content_type = body.content_type
-
66
@body = BodyReader.new(body)
-
66
@closed = false
-
end
-
-
23
def bytesize
-
254
buffer_deflate!
-
-
254
@buffer.size
-
end
-
-
23
def read(length = nil, outbuf = nil)
-
326
return @buffer.read(length, outbuf) if @buffer
-
-
188
return if @closed
-
-
150
chunk = @body.read(length)
-
-
150
compressed_chunk = deflate(chunk)
-
-
150
return unless compressed_chunk
-
-
122
if outbuf
-
110
outbuf.clear.force_encoding(Encoding::BINARY)
-
110
outbuf << compressed_chunk
-
else
-
12
compressed_chunk
-
end
-
end
-
-
23
def close
-
38
return if @closed
-
-
38
@buffer.close if @buffer
-
-
38
@body.close
-
-
38
@closed = true
-
end
-
-
23
def rewind
-
22
return unless @buffer
-
-
12
@buffer.rewind
-
end
-
-
23
private
-
-
# rubocop:disable Naming/MemoizedInstanceVariableName
-
23
def buffer_deflate!
-
254
return @buffer if defined?(@buffer)
-
-
66
buffer = Response::Buffer.new(
-
threshold_size: Options::MAX_BODY_THRESHOLD_SIZE
-
)
-
66
::IO.copy_stream(self, buffer)
-
-
66
buffer.rewind if buffer.respond_to?(:rewind)
-
-
66
@buffer = buffer
-
end
-
# rubocop:enable Naming/MemoizedInstanceVariableName
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Utils
-
23
using URIExtensions
-
-
23
TOKEN = %r{[^\s()<>,;:\\"/\[\]?=]+}.freeze
-
23
VALUE = /"(?:\\"|[^"])*"|#{TOKEN}/.freeze
-
23
FILENAME_REGEX = /\s*filename=(#{VALUE})/.freeze
-
23
FILENAME_EXTENSION_REGEX = /\s*filename\*=(#{VALUE})/.freeze
-
-
23
module_function
-
-
23
def now
-
3349742
Process.clock_gettime(Process::CLOCK_MONOTONIC)
-
end
-
-
23
def elapsed_time(monotonic_timestamp)
-
3325820
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.
-
23
def parse_retry_after(retry_after)
-
# first: bet on it being an integer
-
48
Integer(retry_after)
-
rescue ArgumentError
-
# Then it's a datetime
-
12
time = Time.httpdate(retry_after)
-
12
time - Time.now
-
end
-
-
23
def get_filename(header, _prefix_regex = nil)
-
66
filename = nil
-
66
case header
-
when FILENAME_REGEX
-
42
filename = Regexp.last_match(1)
-
42
filename = Regexp.last_match(1) if filename =~ /^"(.*)"$/
-
when FILENAME_EXTENSION_REGEX
-
12
filename = Regexp.last_match(1)
-
12
encoding, _, filename = filename.split("'", 3)
-
end
-
-
66
return unless filename
-
-
102
filename = URI::DEFAULT_PARSER.unescape(filename) if filename.scan(/%.?.?/).all? { |s| /%[0-9a-fA-F]{2}/.match?(s) }
-
-
54
filename.scrub!
-
-
54
filename = filename.gsub(/\\(.)/, '\1') unless /\\[^\\"]/.match?(filename)
-
-
54
filename.force_encoding ::Encoding.find(encoding) if encoding
-
-
54
filename
-
end
-
-
23
URIParser = URI::RFC2396_Parser.new
-
-
23
def to_uri(uri)
-
12824
return URI(uri) unless uri.is_a?(String) && !uri.ascii_only?
-
-
25
uri = URI(URIParser.escape(uri))
-
-
25
non_ascii_hostname = URIParser.unescape(uri.host)
-
-
25
non_ascii_hostname.force_encoding(Encoding::UTF_8)
-
-
25
idna_hostname = Punycode.encode_hostname(non_ascii_hostname)
-
-
25
uri.host = idna_hostname
-
24
uri.non_ascii_hostname = non_ascii_hostname
-
24
uri
-
end
-
end
-
end