-
# frozen_string_literal: true
-
-
26
require "httpx/version"
-
-
# Top-Level Namespace
-
#
-
26
module HTTPX
-
26
EMPTY = [].freeze
-
26
EMPTY_HASH = {}.freeze
-
-
# All plugins should be stored under this module/namespace. Can register and load
-
# plugins.
-
#
-
26
module Plugins
-
26
@plugins = {}
-
26
@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.
-
#
-
26
def self.load_plugin(name)
-
5312
h = @plugins
-
5312
m = @plugins_mutex
-
10624
unless (plugin = m.synchronize { h[name] })
-
125
require "httpx/plugins/#{name}"
-
250
raise "Plugin #{name} hasn't been registered" unless (plugin = m.synchronize { h[name] })
-
end
-
5312
plugin
-
end
-
-
# Registers a plugin (+mod+) in the central store indexed by +name+.
-
#
-
26
def self.register_plugin(name, mod)
-
302
h = @plugins
-
302
m = @plugins_mutex
-
576
m.synchronize { h[name] = mod }
-
end
-
end
-
end
-
-
26
require "httpx/extensions"
-
-
26
require "httpx/errors"
-
26
require "httpx/utils"
-
26
require "httpx/punycode"
-
26
require "httpx/domain_name"
-
26
require "httpx/altsvc"
-
26
require "httpx/callbacks"
-
26
require "httpx/loggable"
-
26
require "httpx/transcoder"
-
26
require "httpx/timers"
-
26
require "httpx/pool"
-
26
require "httpx/headers"
-
26
require "httpx/request"
-
26
require "httpx/response"
-
26
require "httpx/options"
-
26
require "httpx/chainable"
-
-
26
require "httpx/session"
-
26
require "httpx/session_extensions"
-
-
# load integrations when possible
-
-
26
require "httpx/adapters/datadog" if defined?(DDTrace) || defined?(Datadog::Tracing)
-
26
require "httpx/adapters/sentry" if defined?(Sentry)
-
26
require "httpx/adapters/webmock" if defined?(WebMock)
-
# frozen_string_literal: true
-
-
6
require "datadog/tracing/contrib/integration"
-
6
require "datadog/tracing/contrib/configuration/settings"
-
6
require "datadog/tracing/contrib/patcher"
-
-
6
module Datadog::Tracing
-
6
module Contrib
-
6
module HTTPX
-
6
DATADOG_VERSION = defined?(::DDTrace) ? ::DDTrace::VERSION : ::Datadog::VERSION
-
-
6
METADATA_MODULE = Datadog::Tracing::Metadata
-
-
6
TYPE_OUTBOUND = Datadog::Tracing::Metadata::Ext::HTTP::TYPE_OUTBOUND
-
-
6
TAG_PEER_SERVICE = Datadog::Tracing::Metadata::Ext::TAG_PEER_SERVICE
-
-
6
TAG_URL = Datadog::Tracing::Metadata::Ext::HTTP::TAG_URL
-
6
TAG_METHOD = Datadog::Tracing::Metadata::Ext::HTTP::TAG_METHOD
-
6
TAG_TARGET_HOST = Datadog::Tracing::Metadata::Ext::NET::TAG_TARGET_HOST
-
6
TAG_TARGET_PORT = Datadog::Tracing::Metadata::Ext::NET::TAG_TARGET_PORT
-
-
6
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.
-
#
-
6
module Plugin
-
6
class RequestTracer
-
6
include Contrib::HttpAnnotationHelper
-
-
6
SPAN_REQUEST = "httpx.request"
-
-
# initializes the tracer object on the +request+.
-
6
def initialize(request)
-
245
@request = request
-
245
@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.
-
271
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.
-
386
request.on(:headers) { call }
-
end
-
-
# sets up the span start time, while preparing the on response callback.
-
6
def call(*args)
-
152
return if @start_time
-
-
146
start(*args)
-
-
146
@request.once(:response, &method(:finish))
-
end
-
-
6
private
-
-
# just sets the span init time. It can be passed a +start_time+ in cases where
-
# this is collected outside the request transaction.
-
6
def start(start_time = now)
-
152
@start_time = start_time
-
end
-
-
# resets the start time for already finished request transactions.
-
6
def reset
-
26
return unless @start_time
-
-
6
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.
-
6
def finish(response)
-
146
return unless @start_time
-
-
146
span = initialize_span
-
-
146
return unless span
-
-
146
if response.is_a?(::HTTPX::ErrorResponse)
-
11
span.set_error(response.error)
-
else
-
135
span.set_tag(TAG_STATUS_CODE, response.status.to_s)
-
-
135
span.set_error(::HTTPX::HTTPError.new(response)) if response.status >= 400 && response.status <= 599
-
end
-
-
146
span.finish
-
ensure
-
146
@start_time = nil
-
end
-
-
# return a span initialized with the +@request+ state.
-
6
def initialize_span
-
146
verb = @request.verb
-
146
uri = @request.uri
-
-
146
span = create_span(@request)
-
-
146
span.resource = verb
-
-
# Add additional request specific tags to the span.
-
-
146
span.set_tag(TAG_URL, @request.path)
-
146
span.set_tag(TAG_METHOD, verb)
-
-
146
span.set_tag(TAG_TARGET_HOST, uri.host)
-
146
span.set_tag(TAG_TARGET_PORT, uri.port.to_s)
-
-
# Tag as an external peer service
-
146
span.set_tag(TAG_PEER_SERVICE, span.service)
-
-
146
if configuration[:distributed_tracing]
-
140
propagate_trace_http(
-
Datadog::Tracing.active_trace.to_digest,
-
@request.headers
-
)
-
end
-
-
# Set analytics sample rate
-
146
if Contrib::Analytics.enabled?(configuration[:analytics_enabled])
-
12
Contrib::Analytics.set_sample_rate(span, configuration[:analytics_sample_rate])
-
end
-
-
146
span
-
rescue StandardError => e
-
Datadog.logger.error("error preparing span for http request: #{e}")
-
Datadog.logger.error(e.backtrace)
-
end
-
-
6
def now
-
141
::Datadog::Core::Utils::Time.now.utc
-
end
-
-
6
def configuration
-
450
@configuration ||= Datadog.configuration.tracing[:httpx, @request.uri.host]
-
end
-
-
6
if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("2.0.0")
-
3
def propagate_trace_http(digest, headers)
-
73
Datadog::Tracing::Contrib::HTTP.inject(digest, headers)
-
end
-
-
3
def create_span(request)
-
76
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
-
-
6
module RequestMethods
-
# intercepts request initialization to inject the tracing logic.
-
6
def initialize(*)
-
234
super
-
-
234
return unless Datadog::Tracing.enabled?
-
-
234
RequestTracer.new(self)
-
end
-
end
-
-
6
module ConnectionMethods
-
6
attr_reader :init_time
-
-
6
def initialize(*)
-
219
super
-
-
219
@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.
-
6
def handle_error(error, request = nil)
-
11
return super unless Datadog::Tracing.enabled?
-
-
11
return super unless error.respond_to?(:connection)
-
-
11
@pending.each do |req|
-
11
next if request and request == req
-
-
11
RequestTracer.new(req).call(error.connection.init_time)
-
end
-
-
11
RequestTracer.new(request).call(error.connection.init_time) if request
-
-
11
super
-
end
-
end
-
end
-
-
6
module Configuration
-
# Default settings for httpx
-
#
-
6
class Settings < Datadog::Tracing::Contrib::Configuration::Settings
-
6
DEFAULT_ERROR_HANDLER = lambda do |response|
-
Datadog::Ext::HTTP::ERROR_RANGE.cover?(response.status)
-
end
-
-
6
option :service_name, default: "httpx"
-
6
option :distributed_tracing, default: true
-
6
option :split_by_domain, default: false
-
-
6
if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
-
6
option :enabled do |o|
-
6
o.type :bool
-
6
o.env "DD_TRACE_HTTPX_ENABLED"
-
6
o.default true
-
end
-
-
6
option :analytics_enabled do |o|
-
6
o.type :bool
-
6
o.env "DD_TRACE_HTTPX_ANALYTICS_ENABLED"
-
6
o.default false
-
end
-
-
6
option :analytics_sample_rate do |o|
-
6
o.type :float
-
6
o.env "DD_TRACE_HTTPX_ANALYTICS_SAMPLE_RATE"
-
6
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
-
-
6
if defined?(Datadog::Tracing::Contrib::SpanAttributeSchema)
-
6
option :service_name do |o|
-
6
o.default do
-
71
Datadog::Tracing::Contrib::SpanAttributeSchema.fetch_service_name(
-
"DD_TRACE_HTTPX_SERVICE_NAME",
-
"httpx"
-
)
-
end
-
6
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
-
-
6
option :distributed_tracing, default: true
-
-
6
if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.15.0")
-
6
option :error_handler do |o|
-
6
o.type :proc
-
6
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.
-
#
-
6
module Patcher
-
6
include Datadog::Tracing::Contrib::Patcher
-
-
6
module_function
-
-
6
def target_version
-
12
Integration.version
-
end
-
-
# loads a session instannce with the datadog plugin, and replaces the
-
# base HTTPX::Session with the patched session class.
-
6
def patch
-
6
datadog_session = ::HTTPX.plugin(Plugin)
-
-
6
::HTTPX.send(:remove_const, :Session)
-
6
::HTTPX.send(:const_set, :Session, datadog_session.class)
-
end
-
end
-
-
# Datadog Integration for HTTPX.
-
#
-
6
class Integration
-
6
include Contrib::Integration
-
-
6
MINIMUM_VERSION = Gem::Version.new("0.10.2")
-
-
6
register_as :httpx
-
-
6
def self.version
-
246
Gem.loaded_specs["httpx"] && Gem.loaded_specs["httpx"].version
-
end
-
-
6
def self.loaded?
-
78
defined?(::HTTPX::Request)
-
end
-
-
6
def self.compatible?
-
78
super && version >= MINIMUM_VERSION
-
end
-
-
6
def new_configuration
-
83
Configuration::Settings.new
-
end
-
-
6
def patcher
-
156
Patcher
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
9
require "delegate"
-
9
require "httpx"
-
9
require "faraday"
-
-
9
module Faraday
-
9
class Adapter
-
9
class HTTPX < Faraday::Adapter
-
9
module RequestMixin
-
9
def build_connection(env)
-
217
return @connection if defined?(@connection)
-
-
217
@connection = ::HTTPX.plugin(:persistent).plugin(ReasonPlugin)
-
217
@connection = @connection.with(@connection_options) unless @connection_options.empty?
-
217
connection_opts = options_from_env(env)
-
-
217
if (bind = env.request.bind)
-
8
@bind = TCPSocket.new(bind[:host], bind[:port])
-
7
connection_opts[:io] = @bind
-
end
-
217
@connection = @connection.with(connection_opts)
-
-
217
if (proxy = env.request.proxy)
-
8
proxy_options = { uri: proxy.uri }
-
8
proxy_options[:username] = proxy.user if proxy.user
-
8
proxy_options[:password] = proxy.password if proxy.password
-
-
8
@connection = @connection.plugin(:proxy).with(proxy: proxy_options)
-
end
-
217
@connection = @connection.plugin(OnDataPlugin) if env.request.stream_response?
-
-
217
@connection = @config_block.call(@connection) || @connection if @config_block
-
217
@connection
-
end
-
-
9
def close
-
224
@connection.close if @connection
-
224
@bind.close if @bind
-
end
-
-
9
private
-
-
9
def connect(env, &blk)
-
217
connection(env, &blk)
-
rescue ::HTTPX::TLSError => e
-
8
raise Faraday::SSLError, e
-
rescue Errno::ECONNABORTED,
-
Errno::ECONNREFUSED,
-
Errno::ECONNRESET,
-
Errno::EHOSTUNREACH,
-
Errno::EINVAL,
-
Errno::ENETUNREACH,
-
Errno::EPIPE,
-
::HTTPX::ConnectionError => e
-
8
raise Faraday::ConnectionFailed, e
-
end
-
-
9
def build_request(env)
-
225
meth = env[:method]
-
-
28
request_options = {
-
196
headers: env.request_headers,
-
body: env.body,
-
**options_from_env(env),
-
}
-
225
[meth.to_s.upcase, env.url, request_options]
-
end
-
-
9
def options_from_env(env)
-
442
timeout_options = {}
-
442
req_opts = env.request
-
442
if (sec = request_timeout(:read, req_opts))
-
14
timeout_options[:read_timeout] = sec
-
end
-
-
442
if (sec = request_timeout(:write, req_opts))
-
14
timeout_options[:write_timeout] = sec
-
end
-
-
442
if (sec = request_timeout(:open, req_opts))
-
14
timeout_options[:connect_timeout] = sec
-
end
-
-
55
{
-
386
ssl: ssl_options_from_env(env),
-
timeout: timeout_options,
-
}
-
end
-
-
9
if defined?(::OpenSSL)
-
9
def ssl_options_from_env(env)
-
442
ssl_options = {}
-
-
442
unless env.ssl.verify.nil?
-
28
ssl_options[:verify_mode] = env.ssl.verify ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
-
end
-
-
442
ssl_options[:ca_file] = env.ssl.ca_file if env.ssl.ca_file
-
442
ssl_options[:ca_path] = env.ssl.ca_path if env.ssl.ca_path
-
442
ssl_options[:cert_store] = env.ssl.cert_store if env.ssl.cert_store
-
442
ssl_options[:cert] = env.ssl.client_cert if env.ssl.client_cert
-
442
ssl_options[:key] = env.ssl.client_key if env.ssl.client_key
-
442
ssl_options[:ssl_version] = env.ssl.version if env.ssl.version
-
442
ssl_options[:verify_depth] = env.ssl.verify_depth if env.ssl.verify_depth
-
442
ssl_options[:min_version] = env.ssl.min_version if env.ssl.min_version
-
442
ssl_options[:max_version] = env.ssl.max_version if env.ssl.max_version
-
442
ssl_options
-
end
-
else
-
skipped
# :nocov:
-
skipped
def ssl_options_from_env(*)
-
skipped
{}
-
skipped
end
-
skipped
# :nocov:
-
end
-
end
-
-
9
include RequestMixin
-
-
9
module OnDataPlugin
-
9
module RequestMethods
-
9
attr_writer :response_on_data
-
-
9
def response=(response)
-
16
super
-
-
16
return if response.is_a?(::HTTPX::ErrorResponse)
-
-
16
response.body.on_data = @response_on_data
-
end
-
end
-
-
9
module ResponseBodyMethods
-
9
attr_writer :on_data
-
-
9
def write(chunk)
-
46
return super unless @on_data
-
-
46
@on_data.call(chunk, chunk.bytesize)
-
end
-
end
-
end
-
-
9
module ReasonPlugin
-
9
def self.load_dependencies(*)
-
217
require "net/http/status"
-
end
-
-
9
module ResponseMethods
-
9
def reason
-
177
Net::HTTP::STATUS_CODES.fetch(@status)
-
end
-
end
-
end
-
-
9
class ParallelManager
-
9
class ResponseHandler < SimpleDelegator
-
9
attr_reader :env
-
-
9
def initialize(env)
-
32
@env = env
-
32
super
-
end
-
-
9
def on_response(&blk)
-
64
if blk
-
32
@on_response = ->(response) do
-
32
blk.call(response)
-
end
-
32
self
-
else
-
32
@on_response
-
end
-
end
-
-
9
def on_complete(&blk)
-
96
if blk
-
32
@on_complete = blk
-
32
self
-
else
-
64
@on_complete
-
end
-
end
-
end
-
-
9
include RequestMixin
-
-
9
def initialize(options)
-
32
@handlers = []
-
32
@connection_options = options
-
end
-
-
9
def enqueue(request)
-
32
handler = ResponseHandler.new(request)
-
32
@handlers << handler
-
32
handler
-
end
-
-
9
def run
-
32
return unless @handlers.last
-
-
24
env = @handlers.last.env
-
-
24
connect(env) do |session|
-
56
requests = @handlers.map { |handler| session.build_request(*build_request(handler.env)) }
-
-
24
if env.request.stream_response?
-
8
requests.each do |request|
-
8
request.response_on_data = env.request.on_data
-
end
-
end
-
-
24
responses = session.request(*requests)
-
24
Array(responses).each_with_index do |response, index|
-
32
handler = @handlers[index]
-
32
handler.on_response.call(response)
-
32
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
-
9
def connection(env)
-
24
conn = build_connection(env)
-
24
return conn unless block_given?
-
-
24
yield conn
-
end
-
-
9
private
-
-
# from Faraday::Adapter#request_timeout
-
9
def request_timeout(type, options)
-
168
key = Faraday::Adapter::TIMEOUT_KEYS[type]
-
168
options[key] || options[:timeout]
-
end
-
end
-
-
9
self.supports_parallel = true
-
-
9
class << self
-
9
def setup_parallel_manager(options = {})
-
32
ParallelManager.new(options)
-
end
-
end
-
-
9
def call(env)
-
225
super
-
225
if parallel?(env)
-
32
handler = env[:parallel_manager].enqueue(env)
-
32
handler.on_response do |response|
-
32
if response.is_a?(::HTTPX::Response)
-
24
save_response(env, response.status, response.body.to_s, response.headers, response.reason) do |response_headers|
-
24
response_headers.merge!(response.headers)
-
end
-
else
-
7
env[:error] = response.error
-
8
save_response(env, 0, "", {}, nil)
-
end
-
end
-
28
return handler
-
end
-
-
193
response = connect_and_request(env)
-
153
save_response(env, response.status, response.body.to_s, response.headers, response.reason) do |response_headers|
-
153
response_headers.merge!(response.headers)
-
end
-
153
@app.call(env)
-
end
-
-
9
private
-
-
9
def connect_and_request(env)
-
193
connect(env) do |session|
-
193
request = session.build_request(*build_request(env))
-
-
193
request.response_on_data = env.request.on_data if env.request.stream_response?
-
-
193
response = session.request(request)
-
# do not call #raise_for_status for HTTP 4xx or 5xx, as faraday has a middleware for that.
-
193
response.raise_for_status unless response.is_a?(::HTTPX::Response)
-
153
response
-
end
-
rescue ::HTTPX::TimeoutError => e
-
24
raise Faraday::TimeoutError, e
-
end
-
-
9
def parallel?(env)
-
225
env[:parallel_manager]
-
end
-
end
-
-
9
register_middleware httpx: HTTPX
-
end
-
end
-
# frozen_string_literal: true
-
-
6
require "sentry-ruby"
-
-
6
module HTTPX::Plugins
-
6
module Sentry
-
6
module Tracer
-
6
module_function
-
-
6
def call(request)
-
60
sentry_span = start_sentry_span
-
-
60
return unless sentry_span
-
-
60
set_sentry_trace_header(request, sentry_span)
-
-
60
request.on(:response, &method(:finish_sentry_span).curry(3)[sentry_span, request])
-
end
-
-
6
def start_sentry_span
-
60
return unless ::Sentry.initialized? && (span = ::Sentry.get_current_scope.get_span)
-
60
return if span.sampled == false
-
-
60
span.start_child(op: "httpx.client", start_timestamp: ::Sentry.utc_now.to_f)
-
end
-
-
6
def set_sentry_trace_header(request, sentry_span)
-
60
return unless sentry_span
-
-
60
config = ::Sentry.configuration
-
60
url = request.uri.to_s
-
-
120
return unless config.propagate_traces && config.trace_propagation_targets.any? { |target| url.match?(target) }
-
-
60
trace = ::Sentry.get_current_client.generate_sentry_trace(sentry_span)
-
60
request.headers[::Sentry::SENTRY_TRACE_HEADER_NAME] = trace if trace
-
end
-
-
6
def finish_sentry_span(span, request, response)
-
62
return unless ::Sentry.initialized?
-
-
62
record_sentry_breadcrumb(request, response)
-
62
record_sentry_span(request, response, span)
-
end
-
-
6
def record_sentry_breadcrumb(req, res)
-
62
return unless ::Sentry.configuration.breadcrumbs_logger.include?(:http_logger)
-
-
62
request_info = extract_request_info(req)
-
-
62
data = if res.is_a?(HTTPX::ErrorResponse)
-
7
{ error: res.error.message, **request_info }
-
else
-
55
{ status: res.status, **request_info }
-
end
-
-
62
crumb = ::Sentry::Breadcrumb.new(
-
level: :info,
-
category: "httpx",
-
type: :info,
-
data: data
-
)
-
62
::Sentry.add_breadcrumb(crumb)
-
end
-
-
6
def record_sentry_span(req, res, sentry_span)
-
62
return unless sentry_span
-
-
62
request_info = extract_request_info(req)
-
62
sentry_span.set_description("#{request_info[:method]} #{request_info[:url]}")
-
62
if res.is_a?(HTTPX::ErrorResponse)
-
7
sentry_span.set_data(:error, res.error.message)
-
else
-
55
sentry_span.set_data(:status, res.status)
-
end
-
62
sentry_span.set_timestamp(::Sentry.utc_now.to_f)
-
end
-
-
6
def extract_request_info(req)
-
124
uri = req.uri
-
-
result = {
-
124
method: req.verb,
-
}
-
-
124
if ::Sentry.configuration.send_default_pii
-
24
uri += "?#{req.query}" unless req.query.empty?
-
24
result[:body] = req.body.to_s unless req.body.empty? || req.body.unbounded_body?
-
end
-
-
124
result[:url] = uri.to_s
-
-
124
result
-
end
-
end
-
-
6
module RequestMethods
-
6
def __sentry_enable_trace!
-
62
return if @__sentry_enable_trace
-
-
60
Tracer.call(self)
-
60
@__sentry_enable_trace = true
-
end
-
end
-
-
6
module ConnectionMethods
-
6
def send(request)
-
62
request.__sentry_enable_trace!
-
-
62
super
-
end
-
end
-
end
-
end
-
-
6
Sentry.register_patch(:httpx) do
-
30
sentry_session = HTTPX.plugin(HTTPX::Plugins::Sentry)
-
-
30
HTTPX.send(:remove_const, :Session)
-
30
HTTPX.send(:const_set, :Session, sentry_session.class)
-
end
-
# frozen_string_literal: true
-
-
8
module WebMock
-
8
module HttpLibAdapters
-
8
require "net/http/status"
-
8
HTTP_REASONS = Net::HTTP::STATUS_CODES
-
-
#
-
# HTTPX plugin for webmock.
-
#
-
# Requests are "hijacked" at the session, before they're distributed to a connection.
-
#
-
8
module Plugin
-
8
class << self
-
8
def build_webmock_request_signature(request)
-
188
uri = WebMock::Util::URI.heuristic_parse(request.uri)
-
188
uri.query = request.query
-
188
uri.path = uri.normalized_path.gsub("[^:]//", "/")
-
-
188
WebMock::RequestSignature.new(
-
request.verb.downcase.to_sym,
-
uri.to_s,
-
body: request.body.to_s,
-
headers: request.headers.to_h
-
)
-
end
-
-
8
def build_webmock_response(_request, response)
-
6
webmock_response = WebMock::Response.new
-
6
webmock_response.status = [response.status, HTTP_REASONS[response.status]]
-
6
webmock_response.body = response.body.to_s
-
6
webmock_response.headers = response.headers.to_h
-
6
webmock_response
-
end
-
-
8
def build_from_webmock_response(request, webmock_response)
-
158
return build_error_response(request, HTTPX::TimeoutError.new(1, "Timed out")) if webmock_response.should_timeout
-
-
140
return build_error_response(request, webmock_response.exception) if webmock_response.exception
-
-
133
request.options.response_class.new(request,
-
webmock_response.status[0],
-
"2.0",
-
webmock_response.headers).tap do |res|
-
133
res.mocked = true
-
end
-
end
-
-
8
def build_error_response(request, exception)
-
25
HTTPX::ErrorResponse.new(request, exception)
-
end
-
end
-
-
8
module InstanceMethods
-
8
private
-
-
8
def do_init_connection(connection, selector)
-
170
super
-
-
170
connection.once(:unmock_connection) do
-
24
unless connection.addresses
-
24
connection.__send__(:callbacks)[:connect_error].clear
-
24
deselect_connection(connection, selector)
-
end
-
24
resolve_connection(connection, selector)
-
end
-
end
-
end
-
-
8
module ResponseMethods
-
8
attr_accessor :mocked
-
-
8
def initialize(*)
-
157
super
-
157
@mocked = false
-
end
-
end
-
-
8
module ResponseBodyMethods
-
8
def decode_chunk(chunk)
-
96
return chunk if @response.mocked
-
-
42
super
-
end
-
end
-
-
8
module ConnectionMethods
-
8
def initialize(*)
-
170
super
-
170
@mocked = true
-
end
-
-
8
def open?
-
194
return true if @mocked
-
-
24
super
-
end
-
-
8
def interests
-
277
return if @mocked
-
-
247
super
-
end
-
-
8
def terminate
-
145
force_reset
-
end
-
-
8
def send(request)
-
188
request_signature = Plugin.build_webmock_request_signature(request)
-
188
WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
-
-
188
if (mock_response = WebMock::StubRegistry.instance.response_for_request(request_signature))
-
158
response = Plugin.build_from_webmock_response(request, mock_response)
-
158
WebMock::CallbackRegistry.invoke_callbacks({ lib: :httpx }, request_signature, mock_response)
-
158
log { "mocking #{request.uri} with #{mock_response.inspect}" }
-
158
request.response = response
-
158
request.emit(:response, response)
-
158
response << mock_response.body.dup unless response.is_a?(HTTPX::ErrorResponse)
-
30
elsif WebMock.net_connect_allowed?(request_signature.uri)
-
24
if WebMock::CallbackRegistry.any_callbacks?
-
6
request.on(:response) do |resp|
-
6
unless resp.is_a?(HTTPX::ErrorResponse)
-
6
webmock_response = Plugin.build_webmock_response(request, resp)
-
6
WebMock::CallbackRegistry.invoke_callbacks(
-
{ lib: :httpx, real_request: true }, request_signature,
-
webmock_response
-
)
-
end
-
end
-
end
-
24
@mocked = false
-
24
emit(:unmock_connection, self)
-
24
super
-
else
-
6
raise WebMock::NetConnectNotAllowedError, request_signature
-
end
-
end
-
end
-
end
-
-
8
class HttpxAdapter < HttpLibAdapter
-
8
adapter_for :httpx
-
-
8
class << self
-
8
def enable!
-
370
@original_session ||= HTTPX::Session
-
-
370
webmock_session = HTTPX.plugin(Plugin)
-
-
370
HTTPX.send(:remove_const, :Session)
-
370
HTTPX.send(:const_set, :Session, webmock_session.class)
-
end
-
-
8
def disable!
-
370
return unless @original_session
-
-
362
HTTPX.send(:remove_const, :Session)
-
362
HTTPX.send(:const_set, :Session, @original_session)
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "strscan"
-
-
26
module HTTPX
-
26
module AltSvc
-
# makes connections able to accept requests destined to primary service.
-
26
module ConnectionMixin
-
26
using URIExtensions
-
-
26
def send(request)
-
8
request.headers["alt-used"] = @origin.authority if @parser && !@write_buffer.full? && match_altsvcs?(request.uri)
-
-
8
super
-
end
-
-
26
def match?(uri, options)
-
8
return false if !used? && (@state == :closing || @state == :closed)
-
-
8
match_altsvcs?(uri) && match_altsvc_options?(uri, options)
-
end
-
-
26
private
-
-
# checks if this is connection is an alternative service of
-
# +uri+
-
26
def match_altsvcs?(uri)
-
24
@origins.any? { |origin| altsvc_match?(uri, origin) } ||
-
AltSvc.cached_altsvc(@origin).any? do |altsvc|
-
origin = altsvc["origin"]
-
altsvc_match?(origin, uri.origin)
-
end
-
end
-
-
26
def match_altsvc_options?(uri, options)
-
8
return @options == options unless @options.ssl.all? do |k, v|
-
8
v == (k == :hostname ? uri.host : options.ssl[k])
-
end
-
-
8
@options.options_equals?(options, Options::REQUEST_BODY_IVARS + %i[@ssl])
-
end
-
-
26
def altsvc_match?(uri, other_uri)
-
16
other_uri = URI(other_uri)
-
-
16
uri.origin == other_uri.origin || begin
-
7
case uri.scheme
-
when "h2"
-
(other_uri.scheme == "https" || other_uri.scheme == "h2") &&
-
uri.host == other_uri.host &&
-
uri.port == other_uri.port
-
else
-
8
false
-
end
-
end
-
end
-
end
-
-
26
@altsvc_mutex = Thread::Mutex.new
-
47
@altsvcs = Hash.new { |h, k| h[k] = [] }
-
-
26
module_function
-
-
26
def cached_altsvc(origin)
-
40
now = Utils.now
-
40
@altsvc_mutex.synchronize do
-
40
lookup(origin, now)
-
end
-
end
-
-
26
def cached_altsvc_set(origin, entry)
-
24
now = Utils.now
-
24
@altsvc_mutex.synchronize do
-
24
return if @altsvcs[origin].any? { |altsvc| altsvc["origin"] == entry["origin"] }
-
-
24
entry["TTL"] = Integer(entry["ma"]) + now if entry.key?("ma")
-
24
@altsvcs[origin] << entry
-
24
entry
-
end
-
end
-
-
26
def lookup(origin, ttl)
-
40
return [] unless @altsvcs.key?(origin)
-
-
28
@altsvcs[origin] = @altsvcs[origin].select do |entry|
-
24
!entry.key?("TTL") || entry["TTL"] > ttl
-
end
-
48
@altsvcs[origin].reject { |entry| entry["noop"] }
-
end
-
-
26
def emit(request, response)
-
7517
return unless response.respond_to?(:headers)
-
# Alt-Svc
-
7491
return unless response.headers.key?("alt-svc")
-
-
80
origin = request.origin
-
80
host = request.uri.host
-
-
80
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).
-
80
if altsvc == "clear"
-
8
@altsvc_mutex.synchronize do
-
8
@altsvcs[origin].clear
-
end
-
-
7
return
-
end
-
-
72
parse(altsvc) do |alt_origin, alt_params|
-
8
alt_origin.host ||= host
-
8
yield(alt_origin, origin, alt_params)
-
end
-
end
-
-
26
def parse(altsvc)
-
184
return enum_for(__method__, altsvc) unless block_given?
-
-
128
scanner = StringScanner.new(altsvc)
-
134
until scanner.eos?
-
128
alt_service = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
-
-
128
alt_params = []
-
128
loop do
-
152
alt_param = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
-
152
alt_params << alt_param.strip if alt_param
-
152
scanner.skip(/;/)
-
152
break if scanner.eos? || scanner.scan(/ *, */)
-
end
-
256
alt_params = Hash[alt_params.map { |field| field.split("=", 2) }]
-
-
128
alt_proto, alt_authority = alt_service.split("=", 2)
-
128
alt_origin = parse_altsvc_origin(alt_proto, alt_authority)
-
128
return unless alt_origin
-
-
48
yield(alt_origin, alt_params.merge("proto" => alt_proto))
-
end
-
end
-
-
26
def parse_altsvc_scheme(alt_proto)
-
135
case alt_proto
-
when "h2c"
-
8
"http"
-
when "h2"
-
56
"https"
-
end
-
end
-
-
26
def parse_altsvc_origin(alt_proto, alt_origin)
-
128
alt_scheme = parse_altsvc_scheme(alt_proto)
-
-
128
return unless alt_scheme
-
-
48
alt_origin = alt_origin[1..-2] if alt_origin.start_with?("\"") && alt_origin.end_with?("\"")
-
-
48
URI.parse("#{alt_scheme}://#{alt_origin}")
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "forwardable"
-
-
26
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
-
#
-
26
class Buffer
-
26
extend Forwardable
-
-
26
def_delegator :@buffer, :<<
-
-
26
def_delegator :@buffer, :to_s
-
-
26
def_delegator :@buffer, :to_str
-
-
26
def_delegator :@buffer, :empty?
-
-
26
def_delegator :@buffer, :bytesize
-
-
26
def_delegator :@buffer, :clear
-
-
26
def_delegator :@buffer, :replace
-
-
26
attr_reader :limit
-
-
26
def initialize(limit)
-
20463
@buffer = "".b
-
20463
@limit = limit
-
end
-
-
26
def full?
-
2874062
@buffer.bytesize >= @limit
-
end
-
-
26
def capacity
-
12
@limit - @buffer.bytesize
-
end
-
-
26
def shift!(fin)
-
20498
@buffer = @buffer.byteslice(fin..-1) || "".b
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
26
module Callbacks
-
26
def on(type, &action)
-
259277
callbacks(type) << action
-
259277
self
-
end
-
-
26
def once(type, &block)
-
93272
on(type) do |*args, &callback|
-
92071
block.call(*args, &callback)
-
92007
:delete
-
end
-
93272
self
-
end
-
-
26
def emit(type, *args)
-
269960
callbacks(type).delete_if { |pr| :delete == pr.call(*args) } # rubocop:disable Style/YodaCondition
-
end
-
-
26
def callbacks_for?(type)
-
3036
@callbacks.key?(type) && @callbacks[type].any?
-
end
-
-
26
protected
-
-
26
def callbacks(type = nil)
-
389014
return @callbacks unless type
-
-
595626
@callbacks ||= Hash.new { |h, k| h[k] = [] }
-
388903
@callbacks[type]
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
# Session mixin, implements most of the APIs that the users call.
-
# delegates to a default session when extended.
-
26
module Chainable
-
26
%w[head get post put delete trace options connect patch].each do |meth|
-
225
class_eval(<<-MOD, __FILE__, __LINE__ + 1)
-
9
def #{meth}(*uri, **options) # def get(*uri, **options)
-
18
request("#{meth.upcase}", uri, **options) # request("GET", uri, **options)
-
end # end
-
MOD
-
end
-
-
# delegates to the default session (see HTTPX::Session#request).
-
26
def request(*args, **options)
-
2466
branch(default_options).request(*args, **options)
-
end
-
-
26
def accept(type)
-
16
with(headers: { "accept" => String(type) })
-
end
-
-
# delegates to the default session (see HTTPX::Session#wrap).
-
26
def wrap(&blk)
-
89
branch(default_options).wrap(&blk)
-
end
-
-
# returns a new instance loaded with the +pl+ plugin and +options+.
-
26
def plugin(pl, options = nil, &blk)
-
4909
klass = is_a?(S) ? self.class : Session
-
4909
klass = Class.new(klass)
-
4909
klass.instance_variable_set(:@default_options, klass.default_options.merge(default_options))
-
4909
klass.plugin(pl, options, &blk).new
-
end
-
-
# returns a new instance loaded with +options+.
-
26
def with(options, &blk)
-
2573
branch(default_options.merge(options), &blk)
-
end
-
-
26
private
-
-
# returns default instance of HTTPX::Options.
-
26
def default_options
-
10093
@options || Session.default_options
-
end
-
-
# returns a default instance of HTTPX::Session.
-
26
def branch(options, &blk)
-
5112
return self.class.new(options, &blk) if is_a?(S)
-
-
2959
Session.new(options, &blk)
-
end
-
-
26
def method_missing(meth, *args, **options, &blk)
-
652
case meth
-
when /\Awith_(.+)/
-
-
729
option = Regexp.last_match(1)
-
-
729
return super unless option
-
-
729
with(option.to_sym => args.first || options)
-
when /\Aon_(.+)/
-
9
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
-
2
].include?(callback)
-
-
9
warn "DEPRECATION WARNING: calling `.#{meth}` on plain HTTPX sessions is deprecated. " \
-
1
"Use `HTTPX.plugin(:callbacks).#{meth}` instead."
-
-
9
plugin(:callbacks).__send__(meth, *args, **options, &blk)
-
else
-
super
-
end
-
end
-
-
26
def respond_to_missing?(meth, *)
-
49
case meth
-
when /\Awith_(.+)/
-
40
option = Regexp.last_match(1)
-
-
40
default_options.respond_to?(option) || super
-
when /\Aon_(.+)/
-
16
callback = Regexp.last_match(1)
-
-
12
%w[
-
connection_opened connection_closed
-
request_error
-
request_started request_body_chunk request_completed
-
response_started response_body_chunk response_completed
-
3
].include?(callback) || super
-
else
-
super
-
end
-
end
-
end
-
-
26
extend Chainable
-
end
-
# frozen_string_literal: true
-
-
26
require "resolv"
-
26
require "forwardable"
-
26
require "httpx/io"
-
26
require "httpx/buffer"
-
-
26
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.
-
#
-
26
class Connection
-
26
extend Forwardable
-
26
include Loggable
-
26
include Callbacks
-
-
26
using URIExtensions
-
-
26
require "httpx/connection/http2"
-
26
require "httpx/connection/http1"
-
-
26
def_delegator :@io, :closed?
-
-
26
def_delegator :@write_buffer, :empty?
-
-
26
attr_reader :type, :io, :origin, :origins, :state, :pending, :options, :ssl_session
-
-
26
attr_writer :current_selector, :coalesced_connection
-
-
26
attr_accessor :current_session, :family
-
-
26
def initialize(uri, options)
-
6948
@current_session = @current_selector = @coalesced_connection = nil
-
6948
@exhausted = @cloned = false
-
-
6948
@options = Options.new(options)
-
6948
@type = initialize_type(uri, @options)
-
6948
@origins = [uri.origin]
-
6948
@origin = Utils.to_uri(uri.origin)
-
6948
@window_size = @options.window_size
-
6948
@read_buffer = Buffer.new(@options.buffer_size)
-
6948
@write_buffer = Buffer.new(@options.buffer_size)
-
6948
@pending = []
-
-
6948
on(:error, &method(:on_error))
-
6948
if @options.io
-
# if there's an already open IO, get its
-
# peer address, and force-initiate the parser
-
66
transition(:already_open)
-
66
@io = build_socket
-
66
parser
-
else
-
6882
transition(:idle)
-
end
-
6948
on(:activate) do
-
159
@current_session.select_connection(self, @current_selector)
-
end
-
6948
on(:close) do
-
7310
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
-
-
7302
next unless @current_session
-
-
7302
@current_session.deselect_connection(self, @current_selector, @cloned)
-
end
-
6948
on(:terminate) do
-
2563
next if @exhausted # it'll reset
-
-
# may be called after ":close" above, so after the connection has been checked back in.
-
2555
next unless @current_session
-
-
16
@current_session.deselect_connection(self, @current_selector)
-
end
-
-
6948
on(:altsvc) do |alt_origin, origin, alt_params|
-
8
build_altsvc_connection(alt_origin, origin, alt_params)
-
end
-
-
6948
@inflight = 0
-
6948
@keep_alive_timeout = @options.timeout[:keep_alive_timeout]
-
-
6948
@intervals = []
-
-
6948
self.addresses = @options.addresses if @options.addresses
-
end
-
-
26
def peer
-
14807
@origin
-
end
-
-
# this is a semi-private method, to be used by the resolver
-
# to initiate the io object.
-
26
def addresses=(addrs)
-
6698
if @io
-
205
@io.add_addresses(addrs)
-
else
-
6493
@io = build_socket(addrs)
-
end
-
end
-
-
26
def addresses
-
13879
@io && @io.addresses
-
end
-
-
26
def match?(uri, options)
-
2021
return false if !used? && (@state == :closing || @state == :closed)
-
-
296
(
-
1739
@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
-
1803
(@origins.size == 1 || @origin == uri.origin || (@io.is_a?(SSL) && @io.verify_hostname(uri.host)))
-
) && @options == options
-
end
-
-
26
def expired?
-
return false unless @io
-
-
@io.expired?
-
end
-
-
26
def mergeable?(connection)
-
314
return false if @state == :closing || @state == :closed || !@io
-
-
64
return false unless connection.addresses
-
-
2
(
-
64
(open? && @origin == connection.origin) ||
-
64
!(@io.addresses & (connection.addresses || [])).empty?
-
) && @options == connection.options
-
end
-
-
# coalescable connections need to be mergeable!
-
# but internally, #mergeable? is called before #coalescable?
-
26
def coalescable?(connection)
-
27
if @io.protocol == "h2" &&
-
@origin.scheme == "https" &&
-
connection.origin.scheme == "https" &&
-
@io.can_verify_peer?
-
13
@io.verify_hostname(connection.origin.host)
-
else
-
14
@origin == connection.origin
-
end
-
end
-
-
26
def create_idle(options = {})
-
self.class.new(@origin, @options.merge(options))
-
end
-
-
26
def merge(connection)
-
27
@origins |= connection.instance_variable_get(:@origins)
-
29
if connection.ssl_session
-
7
@ssl_session = connection.ssl_session
-
1
@io.session_new_cb do |sess|
-
14
@ssl_session = sess
-
7
end if @io
-
end
-
29
connection.purge_pending do |req|
-
7
send(req)
-
end
-
end
-
-
26
def purge_pending(&block)
-
29
pendings = []
-
29
if @parser
-
14
@inflight -= @parser.pending.size
-
16
pendings << @parser.pending
-
end
-
29
pendings << @pending
-
29
pendings.each do |pending|
-
45
pending.reject!(&block)
-
end
-
end
-
-
26
def connecting?
-
2906546
@state == :idle
-
end
-
-
26
def inflight?
-
2695
@parser && (
-
# parser may be dealing with other requests (possibly started from a different fiber)
-
2252
!@parser.empty? ||
-
# connection may be doing connection termination handshake
-
!@write_buffer.empty?
-
)
-
end
-
-
26
def interests
-
# connecting
-
2895783
if connecting?
-
10469
connect
-
-
10468
return @io.interests if connecting?
-
end
-
-
# if the write buffer is full, we drain it
-
2885961
return :w unless @write_buffer.empty?
-
-
2847024
return @parser.interests if @parser
-
-
21
nil
-
rescue StandardError => e
-
emit(:error, e)
-
nil
-
end
-
-
26
def to_io
-
20540
@io.to_io
-
end
-
-
26
def call
-
18048
case @state
-
when :idle
-
9667
connect
-
9652
consume
-
when :closed
-
return
-
when :closing
-
consume
-
transition(:closed)
-
when :open
-
9993
consume
-
end
-
8078
nil
-
rescue StandardError => e
-
21
emit(:error, e)
-
21
raise e
-
end
-
-
26
def close
-
2533
transition(:active) if @state == :inactive
-
-
2533
@parser.close if @parser
-
end
-
-
26
def terminate
-
2533
@connected_at = nil if @state == :closed
-
-
2533
close
-
end
-
-
# bypasses the state machine to force closing of connections still connecting.
-
# **only** used for Happy Eyeballs v2.
-
26
def force_reset(cloned = false)
-
292
@state = :closing
-
292
@cloned = cloned
-
292
transition(:closed)
-
end
-
-
26
def reset
-
7187
return if @state == :closing || @state == :closed
-
-
7139
transition(:closing)
-
-
7139
transition(:closed)
-
end
-
-
26
def send(request)
-
8472
return @coalesced_connection.send(request) if @coalesced_connection
-
-
8466
if @parser && !@write_buffer.full?
-
409
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.
-
8
log(level: 3) { "keep alive timeout expired, pinging connection..." }
-
8
@pending << request
-
8
transition(:active) if @state == :inactive
-
8
parser.ping
-
7
return
-
end
-
-
401
send_request_to_parser(request)
-
else
-
8057
@pending << request
-
end
-
end
-
-
26
def timeout
-
2779890
return if @state == :closed || @state == :inactive
-
-
2779890
return @timeout if @timeout
-
-
2768404
return @options.timeout[:connect_timeout] if @state == :idle
-
-
2768404
@options.timeout[:operation_timeout]
-
end
-
-
26
def idling
-
783
purge_after_closed
-
783
@write_buffer.clear
-
783
transition(:idle)
-
783
@parser = nil if @parser
-
end
-
-
26
def used?
-
2215
@connected_at
-
end
-
-
26
def deactivate
-
326
transition(:inactive)
-
end
-
-
26
def open?
-
6791
@state == :open || @state == :inactive
-
end
-
-
26
def handle_socket_timeout(interval)
-
461
@intervals.delete_if(&:elapsed?)
-
-
461
unless @intervals.empty?
-
# remove the intervals which will elapse
-
-
361
return
-
end
-
-
32
error = HTTPX::TimeoutError.new(interval, "timed out while waiting on select")
-
32
error.set_backtrace(caller)
-
32
on_error(error)
-
end
-
-
26
private
-
-
26
def connect
-
19124
transition(:open)
-
end
-
-
26
def disconnect
-
7310
emit(:close)
-
7294
@current_session = nil
-
7294
@current_selector = nil
-
end
-
-
26
def consume
-
22512
return unless @io
-
-
22512
catch(:called) do
-
22512
epiped = false
-
22512
loop do
-
# connection may have
-
41521
return if @state == :idle
-
-
38662
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)
-
38646
if @pending.empty? && @inflight.zero? && @write_buffer.empty?
-
2643
log(level: 3) { "NO MORE REQUESTS..." }
-
2627
return
-
end
-
-
36019
@timeout = @current_timeout
-
-
36019
read_drained = false
-
36019
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.
-
#
-
7102
loop do
-
46782
siz = @io.read(@window_size, @read_buffer)
-
46895
log(level: 3, color: :cyan) { "IO READ: #{siz} bytes... (wsize: #{@window_size}, rbuffer: #{@read_buffer.bytesize})" }
-
46782
unless siz
-
18
ex = EOFError.new("descriptor closed")
-
18
ex.set_backtrace(caller)
-
18
on_error(ex)
-
18
return
-
end
-
-
# socket has been drained. mark and exit the read loop.
-
46764
if siz.zero?
-
9248
read_drained = @read_buffer.empty?
-
9248
epiped = false
-
9248
break
-
end
-
-
37516
parser << @read_buffer.to_s
-
-
# continue reading if possible.
-
33312
break if interests == :w && !epiped
-
-
# exit the read loop if connection is preparing to be closed
-
26319
break if @state == :closing || @state == :closed
-
-
# exit #consume altogether if all outstanding requests have been dealt with
-
26312
return if @pending.empty? && @inflight.zero?
-
36019
end unless ((ints = interests).nil? || ints == :w || @state == :closing) && !epiped
-
-
#
-
# tight write loop.
-
#
-
# flush as many bytes as the sockets allow.
-
#
-
5782
loop do
-
# buffer has been drainned, mark and exit the write loop.
-
22567
if @write_buffer.empty?
-
# we only mark as drained on the first loop
-
2724
write_drained = write_drained.nil? && @inflight.positive?
-
-
2724
break
-
end
-
-
1945
begin
-
19843
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.
-
27
log(level: 2) { "pipe broken, could not flush buffer..." }
-
27
epiped = true
-
27
read_drained = false
-
27
break
-
end
-
19895
log(level: 3, color: :cyan) { "IO WRITE: #{siz} bytes..." }
-
19808
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.
-
19808
if siz.zero?
-
24
write_drained = !@write_buffer.empty?
-
24
break
-
end
-
-
# exit write loop if marked to consume from peer, or is closing.
-
19784
break if interests == :r || @state == :closing || @state == :closed
-
-
2843
write_drained = false
-
28963
end unless (ints = interests) == :r
-
-
28955
send_pending if @state == :open
-
-
# return if socket is drained
-
28955
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;
-
9983
log(level: 3) { "(#{ints}): WAITING FOR EVENTS..." }
-
9946
return
-
end
-
end
-
end
-
-
26
def send_pending
-
76209
while !@write_buffer.full? && (request = @pending.shift)
-
18213
send_request_to_parser(request)
-
end
-
end
-
-
26
def parser
-
102954
@parser ||= build_parser
-
end
-
-
26
def send_request_to_parser(request)
-
17743
@inflight += 1
-
18614
request.peer_address = @io.ip
-
18614
parser.send(request)
-
-
18614
set_request_timeouts(request)
-
-
18614
return unless @state == :inactive
-
-
7
transition(:active)
-
end
-
-
26
def build_parser(protocol = @io.protocol)
-
7006
parser = self.class.parser_type(protocol).new(@write_buffer, @options)
-
7006
set_parser_callbacks(parser)
-
7006
parser
-
end
-
-
26
def set_parser_callbacks(parser)
-
7117
parser.on(:response) do |request, response|
-
7509
AltSvc.emit(request, response) do |alt_origin, origin, alt_params|
-
8
emit(:altsvc, alt_origin, origin, alt_params)
-
end
-
7509
@response_received_at = Utils.now
-
6713
@inflight -= 1
-
7509
request.emit(:response, response)
-
end
-
7117
parser.on(:altsvc) do |alt_origin, origin, alt_params|
-
emit(:altsvc, alt_origin, origin, alt_params)
-
end
-
-
7117
parser.on(:pong, &method(:send_pending))
-
-
7117
parser.on(:promise) do |request, stream|
-
24
request.emit(:promise, parser, stream)
-
end
-
7117
parser.on(:exhausted) do
-
8
@exhausted = true
-
8
current_session = @current_session
-
8
current_selector = @current_selector
-
8
parser.close
-
8
@pending.concat(parser.pending)
-
7
case @state
-
when :closed
-
8
idling
-
8
@exhausted = false
-
8
@current_session = current_session
-
8
@current_selector = current_selector
-
when :closing
-
once(:close) do
-
idling
-
@exhausted = false
-
@current_session = current_session
-
@current_selector = current_selector
-
end
-
end
-
end
-
7117
parser.on(:origin) do |origin|
-
@origins |= [origin]
-
end
-
7117
parser.on(:close) do |force|
-
2563
if force
-
2563
reset
-
2555
emit(:terminate)
-
end
-
end
-
7117
parser.on(:close_handshake) do
-
8
consume
-
end
-
7117
parser.on(:reset) do
-
3829
@pending.concat(parser.pending) unless parser.empty?
-
3829
current_session = @current_session
-
3829
current_selector = @current_selector
-
3829
reset
-
3821
unless @pending.empty?
-
171
idling
-
171
@current_session = current_session
-
171
@current_selector = current_selector
-
end
-
end
-
7117
parser.on(:current_timeout) do
-
2952
@current_timeout = @timeout = parser.timeout
-
end
-
7117
parser.on(:timeout) do |tout|
-
2517
@timeout = tout
-
end
-
7117
parser.on(:error) do |request, ex|
-
47
case ex
-
when MisdirectedRequestError
-
8
current_session = @current_session
-
8
current_selector = @current_selector
-
8
parser.close
-
-
8
other_connection = current_session.find_connection(@origin, current_selector,
-
@options.merge(ssl: { alpn_protocols: %w[http/1.1] }))
-
8
other_connection.merge(self)
-
8
request.transition(:idle)
-
8
other_connection.send(request)
-
else
-
45
response = ErrorResponse.new(request, ex)
-
45
request.response = response
-
45
request.emit(:response, response)
-
end
-
end
-
end
-
-
26
def transition(nextstate)
-
43331
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
-
75
error = ConnectionError.new(e.message)
-
75
error.set_backtrace(e.backtrace)
-
75
connecting? && callbacks_for?(:connect_error) ? emit(:connect_error, error) : handle_error(error)
-
75
@state = :closed
-
75
disconnect
-
rescue TLSError, ::HTTP2::Error::ProtocolError, ::HTTP2::Error::HandshakeError => e
-
# connect errors, exit gracefully
-
25
handle_error(e)
-
25
connecting? && callbacks_for?(:connect_error) ? emit(:connect_error, e) : handle_error(e)
-
25
@state = :closed
-
25
disconnect
-
end
-
-
26
def handle_transition(nextstate)
-
38223
case nextstate
-
when :idle
-
7681
@timeout = @current_timeout = @options.timeout[:connect_timeout]
-
-
7681
@connected_at = nil
-
when :open
-
19424
return if @state == :closed
-
-
19424
@io.connect
-
19325
emit(:tcp_open, self) if @io.state == :connected
-
-
19325
return unless @io.connected?
-
-
7012
@connected_at = Utils.now
-
-
7012
send_pending
-
-
7012
@timeout = @current_timeout = parser.timeout
-
7012
emit(:open)
-
when :inactive
-
326
return unless @state == :open
-
-
# do not deactivate connection in use
-
325
return if @inflight.positive?
-
when :closing
-
7147
return unless @state == :idle || @state == :open
-
-
7147
unless @write_buffer.empty?
-
# preset state before handshake, as error callbacks
-
# may take it back here.
-
2548
@state = nextstate
-
# handshakes, try sending
-
2548
consume
-
2547
@write_buffer.clear
-
2547
return
-
end
-
when :closed
-
7439
return unless @state == :closing
-
7438
return unless @write_buffer.empty?
-
-
7413
purge_after_closed
-
7413
disconnect if @pending.empty?
-
when :already_open
-
66
nextstate = :open
-
# the first check for given io readiness must still use a timeout.
-
# connect is the reasonable choice in such a case.
-
66
@timeout = @options.timeout[:connect_timeout]
-
66
send_pending
-
when :active
-
159
return unless @state == :inactive
-
-
159
nextstate = :open
-
159
emit(:activate)
-
end
-
27801
@state = nextstate
-
end
-
-
26
def purge_after_closed
-
8204
@io.close if @io
-
8204
@read_buffer.clear
-
8204
@timeout = nil
-
end
-
-
26
def initialize_type(uri, options)
-
6582
options.transport || begin
-
5830
case uri.scheme
-
when "http"
-
3775
"tcp"
-
when "https"
-
2779
"ssl"
-
else
-
raise UnsupportedSchemeError, "#{uri}: #{uri.scheme}: unsupported URI scheme"
-
end
-
end
-
end
-
-
# returns an HTTPX::Connection for the negotiated Alternative Service (or none).
-
26
def build_altsvc_connection(alt_origin, origin, alt_params)
-
# do not allow security downgrades on altsvc negotiation
-
8
return if @origin.scheme == "https" && alt_origin.scheme != "https"
-
-
8
altsvc = AltSvc.cached_altsvc_set(origin, alt_params.merge("origin" => alt_origin))
-
-
# altsvc already exists, somehow it wasn't advertised, probably noop
-
8
return unless altsvc
-
-
8
alt_options = @options.merge(ssl: @options.ssl.merge(hostname: URI(origin).host))
-
-
8
connection = @current_session.find_connection(alt_origin, @current_selector, alt_options)
-
-
# advertised altsvc is the same origin being used, ignore
-
8
return if connection == self
-
-
8
connection.extend(AltSvc::ConnectionMixin) unless connection.is_a?(AltSvc::ConnectionMixin)
-
-
8
log(level: 1) { "#{origin} alt-svc: #{alt_origin}" }
-
-
8
connection.merge(self)
-
8
terminate
-
rescue UnsupportedSchemeError
-
altsvc["noop"] = true
-
nil
-
end
-
-
26
def build_socket(addrs = nil)
-
5805
case @type
-
when "tcp"
-
3853
TCP.new(peer, addrs, @options)
-
when "ssl"
-
2678
SSL.new(peer, addrs, @options) do |sock|
-
2656
sock.ssl_session = @ssl_session
-
2656
sock.session_new_cb do |sess|
-
4660
@ssl_session = sess
-
-
4660
sock.ssl_session = sess
-
end
-
end
-
when "unix"
-
28
path = Array(addrs).first
-
-
28
path = String(path) if path
-
-
28
UNIX.new(peer, path, @options)
-
else
-
raise Error, "unsupported transport (#{@type})"
-
end
-
end
-
-
26
def on_error(error, request = nil)
-
771
if error.instance_of?(TimeoutError)
-
-
# inactive connections do not contribute to the select loop, therefore
-
# they should not fail due to such errors.
-
32
return if @state == :inactive
-
-
32
if @timeout
-
28
@timeout -= error.timeout
-
32
return unless @timeout <= 0
-
end
-
-
32
error = error.to_connection_error if connecting?
-
end
-
771
handle_error(error, request)
-
771
reset
-
end
-
-
26
def handle_error(error, request = nil)
-
896
parser.handle_error(error, request) if @parser && parser.respond_to?(:handle_error)
-
1983
while (req = @pending.shift)
-
414
next if request && req == request
-
-
414
response = ErrorResponse.new(req, error)
-
414
req.response = response
-
414
req.emit(:response, response)
-
end
-
-
896
return unless request
-
-
409
response = ErrorResponse.new(request, error)
-
409
request.response = response
-
409
request.emit(:response, response)
-
end
-
-
26
def set_request_timeouts(request)
-
18614
set_request_write_timeout(request)
-
18614
set_request_read_timeout(request)
-
18614
set_request_request_timeout(request)
-
end
-
-
26
def set_request_read_timeout(request)
-
18614
read_timeout = request.read_timeout
-
-
18614
return if read_timeout.nil? || read_timeout.infinite?
-
-
18328
set_request_timeout(request, read_timeout, :done, :response) do
-
24
read_timeout_callback(request, read_timeout)
-
end
-
end
-
-
26
def set_request_write_timeout(request)
-
18614
write_timeout = request.write_timeout
-
-
18614
return if write_timeout.nil? || write_timeout.infinite?
-
-
18614
set_request_timeout(request, write_timeout, :headers, %i[done response]) do
-
24
write_timeout_callback(request, write_timeout)
-
end
-
end
-
-
26
def set_request_request_timeout(request)
-
18330
request_timeout = request.request_timeout
-
-
18330
return if request_timeout.nil? || request_timeout.infinite?
-
-
512
set_request_timeout(request, request_timeout, :headers, :complete) do
-
361
read_timeout_callback(request, request_timeout, RequestTimeoutError)
-
end
-
end
-
-
26
def write_timeout_callback(request, write_timeout)
-
24
return if request.state == :done
-
-
24
@write_buffer.clear
-
24
error = WriteTimeoutError.new(request, nil, write_timeout)
-
-
24
on_error(error, request)
-
end
-
-
26
def read_timeout_callback(request, read_timeout, error_type = ReadTimeoutError)
-
385
response = request.response
-
-
385
return if response && response.finished?
-
-
385
@write_buffer.clear
-
385
error = error_type.new(request, request.response, read_timeout)
-
-
385
on_error(error, request)
-
end
-
-
26
def set_request_timeout(request, timeout, start_event, finish_events, &callback)
-
37534
request.once(start_event) do
-
36808
interval = @current_selector.after(timeout, callback)
-
-
36808
Array(finish_events).each do |event|
-
# clean up request timeouts if the connection errors out
-
55159
request.once(event) do
-
55007
if @intervals.include?(interval)
-
54463
interval.delete(callback)
-
54463
@intervals.delete(interval) if interval.no_callbacks?
-
end
-
end
-
end
-
-
36808
@intervals << interval
-
end
-
end
-
-
26
class << self
-
26
def parser_type(protocol)
-
6333
case protocol
-
2959
when "h2" then HTTP2
-
4191
when "http/1.1" then HTTP1
-
else
-
raise Error, "unsupported protocol (##{protocol})"
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "httpx/parser/http1"
-
-
26
module HTTPX
-
26
class Connection::HTTP1
-
26
include Callbacks
-
26
include Loggable
-
-
26
MAX_REQUESTS = 200
-
26
CRLF = "\r\n"
-
-
26
attr_reader :pending, :requests
-
-
26
attr_accessor :max_concurrent_requests
-
-
26
def initialize(buffer, options)
-
4191
@options = options
-
4191
@max_concurrent_requests = @options.max_concurrent_requests || MAX_REQUESTS
-
4191
@max_requests = @options.max_requests
-
4191
@parser = Parser::HTTP1.new(self)
-
4191
@buffer = buffer
-
4191
@version = [1, 1]
-
4191
@pending = []
-
4191
@requests = []
-
4191
@handshake_completed = false
-
end
-
-
26
def timeout
-
4074
@options.timeout[:operation_timeout]
-
end
-
-
26
def interests
-
# this means we're processing incoming response already
-
28909
return :r if @request
-
-
24217
return if @requests.empty?
-
-
24195
request = @requests.first
-
-
24195
return unless request
-
-
24195
return :w if request.interests == :w || !@buffer.empty?
-
-
21292
:r
-
end
-
-
26
def reset
-
3958
@max_requests = @options.max_requests || MAX_REQUESTS
-
3958
@parser.reset!
-
3958
@handshake_completed = false
-
3958
@pending.concat(@requests) unless @requests.empty?
-
end
-
-
26
def close
-
81
reset
-
81
emit(:close, true)
-
end
-
-
26
def exhausted?
-
520
!@max_requests.positive?
-
end
-
-
26
def empty?
-
# this means that for every request there's an available
-
# partial response, so there are no in-flight requests waiting.
-
3877
@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.
-
178
!@requests.first.response.nil? &&
-
(@requests.size == 1 || !@requests.last.response.nil?)
-
)
-
end
-
-
26
def <<(data)
-
6750
@parser << data
-
end
-
-
26
def send(request)
-
15272
unless @max_requests.positive?
-
@pending << request
-
return
-
end
-
-
15272
return if @requests.include?(request)
-
-
15272
@requests << request
-
15272
@pipelining = true if @requests.size > 1
-
end
-
-
26
def consume
-
15314
requests_limit = [@max_requests, @requests.size].min
-
15314
concurrent_requests_limit = [@max_concurrent_requests, requests_limit].min
-
15314
@requests.each_with_index do |request, idx|
-
17819
break if idx >= concurrent_requests_limit
-
15251
next if request.state == :done
-
-
5872
handle(request)
-
end
-
end
-
-
# HTTP Parser callbacks
-
#
-
# must be public methods, or else they won't be reachable
-
-
26
def on_start
-
4566
log(level: 2) { "parsing begins" }
-
end
-
-
26
def on_headers(h)
-
4542
@request = @requests.first
-
-
4542
return if @request.response
-
-
4566
log(level: 2) { "headers received" }
-
4542
headers = @request.options.headers_class.new(h)
-
4542
response = @request.options.response_class.new(@request,
-
@parser.status_code,
-
@parser.http_version.join("."),
-
headers)
-
4566
log(color: :yellow) { "-> HEADLINE: #{response.status} HTTP/#{@parser.http_version.join(".")}" }
-
4758
log(color: :yellow) { response.headers.each.map { |f, v| "-> HEADER: #{f}: #{v}" }.join("\n") }
-
-
4542
@request.response = response
-
4534
on_complete if response.finished?
-
end
-
-
26
def on_trailers(h)
-
8
return unless @request
-
-
8
response = @request.response
-
8
log(level: 2) { "trailer headers received" }
-
-
8
log(color: :yellow) { h.each.map { |f, v| "-> HEADER: #{f}: #{v.join(", ")}" }.join("\n") }
-
8
response.merge_headers(h)
-
end
-
-
26
def on_data(chunk)
-
5262
request = @request
-
-
5262
return unless request
-
-
5286
log(color: :green) { "-> DATA: #{chunk.bytesize} bytes..." }
-
5286
log(level: 2, color: :green) { "-> #{chunk.inspect}" }
-
5262
response = request.response
-
-
5262
response << chunk
-
rescue StandardError => e
-
14
error_response = ErrorResponse.new(request, e)
-
14
request.response = error_response
-
14
dispatch
-
end
-
-
26
def on_complete
-
4512
request = @request
-
-
4512
return unless request
-
-
4536
log(level: 2) { "parsing complete" }
-
4512
dispatch
-
end
-
-
26
def dispatch
-
4526
request = @request
-
-
4526
if request.expects?
-
72
@parser.reset!
-
63
return handle(request)
-
end
-
-
4454
@request = nil
-
4454
@requests.shift
-
4454
response = request.response
-
4454
response.finish! unless response.is_a?(ErrorResponse)
-
4454
emit(:response, request, response)
-
-
4397
if @parser.upgrade?
-
32
response << @parser.upgrade_data
-
32
throw(:called)
-
end
-
-
4365
@parser.reset!
-
3918
@max_requests -= 1
-
4365
if response.is_a?(ErrorResponse)
-
14
disable
-
else
-
4351
manage_connection(request, response)
-
end
-
-
520
if exhausted?
-
@pending.concat(@requests)
-
@requests.clear
-
-
emit(:exhausted)
-
else
-
520
send(@pending.shift) unless @pending.empty?
-
end
-
end
-
-
26
def handle_error(ex, request = nil)
-
219
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
-
16
catch(:called) { on_complete }
-
7
return
-
end
-
-
211
if @pipelining
-
catch(:called) { disable }
-
else
-
211
@requests.each do |req|
-
193
next if request && request == req
-
-
emit(:error, req, ex)
-
end
-
211
@pending.each do |req|
-
next if request && request == req
-
-
emit(:error, req, ex)
-
end
-
end
-
end
-
-
26
def ping
-
reset
-
emit(:reset)
-
emit(:exhausted)
-
end
-
-
26
private
-
-
26
def manage_connection(request, response)
-
4351
connection = response.headers["connection"]
-
3905
case connection
-
when /keep-alive/i
-
520
if @handshake_completed
-
if @max_requests.zero?
-
@pending.concat(@requests)
-
@requests.clear
-
emit(:exhausted)
-
end
-
return
-
end
-
-
520
keep_alive = response.headers["keep-alive"]
-
520
return unless keep_alive
-
-
108
parameters = Hash[keep_alive.split(/ *, */).map do |pair|
-
108
pair.split(/ *= */, 2)
-
end]
-
108
@max_requests = parameters["max"].to_i - 1 if parameters.key?("max")
-
-
108
if parameters.key?("timeout")
-
keep_alive_timeout = parameters["timeout"].to_i
-
emit(:timeout, keep_alive_timeout)
-
end
-
108
@handshake_completed = true
-
when /close/i
-
3831
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
-
-
26
def disable
-
3845
disable_pipelining
-
3845
reset
-
3845
emit(:reset)
-
3837
throw(:called)
-
end
-
-
26
def disable_pipelining
-
3845
return if @requests.empty?
-
# do not disable pipelining if already set to 1 request at a time
-
179
return if @max_concurrent_requests == 1
-
-
21
@requests.each do |r|
-
21
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.
-
21
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.
-
21
@max_concurrent_requests = 1
-
21
@pipelining = false
-
end
-
-
26
def set_protocol_headers(request)
-
4692
if !request.headers.key?("content-length") &&
-
request.body.bytesize == Float::INFINITY
-
32
request.body.chunk!
-
end
-
-
4692
extra_headers = {}
-
-
4692
unless request.headers.key?("connection")
-
4668
connection_value = if request.persistent?
-
# when in a persistent connection, the request can't be at
-
# the edge of a renegotiation
-
57
if @requests.index(request) + 1 < @max_requests
-
57
"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)
-
4611
requests_limit = [@max_requests, @requests.size].min
-
4611
if request == @requests[requests_limit - 1]
-
4054
"close"
-
else
-
557
"keep-alive"
-
end
-
end
-
-
4185
extra_headers["connection"] = connection_value
-
end
-
4692
extra_headers["host"] = request.authority unless request.headers.key?("host")
-
4692
extra_headers
-
end
-
-
26
def handle(request)
-
5944
catch(:buffer_full) do
-
5944
request.transition(:headers)
-
5936
join_headers(request) if request.state == :headers
-
5936
request.transition(:body)
-
5936
join_body(request) if request.state == :body
-
4868
request.transition(:trailers)
-
# HTTP/1.1 trailers should only work for chunked encoding
-
4868
join_trailers(request) if request.body.chunked? && request.state == :trailers
-
4868
request.transition(:done)
-
end
-
end
-
-
26
def join_headline(request)
-
4136
"#{request.verb} #{request.path} HTTP/#{@version.join(".")}"
-
end
-
-
26
def join_headers(request)
-
4692
headline = join_headline(request)
-
4692
@buffer << headline << CRLF
-
4716
log(color: :yellow) { "<- HEADLINE: #{headline.chomp.inspect}" }
-
4692
extra_headers = set_protocol_headers(request)
-
4692
join_headers2(request.headers.each(extra_headers))
-
4716
log { "<- " }
-
4692
@buffer << CRLF
-
end
-
-
26
def join_body(request)
-
5736
return if request.body.empty?
-
-
6421
while (chunk = request.drain_body)
-
3390
log(color: :green) { "<- DATA: #{chunk.bytesize} bytes..." }
-
3390
log(level: 2, color: :green) { "<- #{chunk.inspect}" }
-
3390
@buffer << chunk
-
3390
throw(:buffer_full, request) if @buffer.full?
-
end
-
-
1518
return unless (error = request.drain_error)
-
-
raise error
-
end
-
-
26
def join_trailers(request)
-
96
return unless request.trailers? && request.callbacks_for?(:trailers)
-
-
32
join_headers2(request.trailers)
-
32
log { "<- " }
-
32
@buffer << CRLF
-
end
-
-
26
def join_headers2(headers)
-
4724
headers.each do |field, value|
-
28314
buffer = "#{capitalized(field)}: #{value}#{CRLF}"
-
28434
log(color: :yellow) { "<- HEADER: #{buffer.chomp}" }
-
28314
@buffer << buffer
-
end
-
end
-
-
26
UPCASED = {
-
"www-authenticate" => "WWW-Authenticate",
-
"http2-settings" => "HTTP2-Settings",
-
"content-md5" => "Content-MD5",
-
}.freeze
-
-
26
def capitalized(field)
-
28314
UPCASED[field] || field.split("-").map(&:capitalize).join("-")
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "securerandom"
-
26
require "http/2"
-
-
26
module HTTPX
-
26
class Connection::HTTP2
-
26
include Callbacks
-
26
include Loggable
-
-
26
MAX_CONCURRENT_REQUESTS = ::HTTP2::DEFAULT_MAX_CONCURRENT_STREAMS
-
-
26
class Error < Error
-
26
def initialize(id, code)
-
34
super("stream #{id} closed with error: #{code}")
-
end
-
end
-
-
26
class GoawayError < Error
-
26
def initialize
-
15
super(0, :no_error)
-
end
-
end
-
-
26
attr_reader :streams, :pending
-
-
26
def initialize(buffer, options)
-
2983
@options = options
-
2983
@settings = @options.http2_settings
-
2983
@pending = []
-
2983
@streams = {}
-
2983
@drains = {}
-
2983
@pings = []
-
2983
@buffer = buffer
-
2983
@handshake_completed = false
-
2983
@wait_for_handshake = @settings.key?(:wait_for_handshake) ? @settings.delete(:wait_for_handshake) : true
-
2983
@max_concurrent_requests = @options.max_concurrent_requests || MAX_CONCURRENT_REQUESTS
-
2983
@max_requests = @options.max_requests
-
2983
init_connection
-
end
-
-
26
def timeout
-
5890
return @options.timeout[:operation_timeout] if @handshake_completed
-
-
2938
@options.timeout[:settings_timeout]
-
end
-
-
26
def interests
-
# waiting for WINDOW_UPDATE frames
-
2818039
return :r if @buffer.full?
-
-
2818039
if @connection.state == :closed
-
2707
return unless @handshake_completed
-
-
2359
return :w
-
end
-
-
2815332
unless @connection.state == :connected && @handshake_completed
-
11061
return @buffer.empty? ? :r : :rw
-
end
-
-
2802910
return :w if !@pending.empty? && can_buffer_more_requests?
-
-
2802910
return :w unless @drains.empty?
-
-
2802052
if @buffer.empty?
-
2802052
return if @streams.empty? && @pings.empty?
-
-
34979
return :r
-
end
-
-
:rw
-
end
-
-
26
def close
-
2517
unless @connection.state == :closed
-
2517
@connection.goaway
-
2517
emit(:timeout, @options.timeout[:close_handshake_timeout])
-
end
-
2517
emit(:close, true)
-
end
-
-
26
def empty?
-
2518
@connection.state == :closed || @streams.empty?
-
end
-
-
26
def exhausted?
-
2981
!@max_requests.positive?
-
end
-
-
26
def <<(data)
-
30462
@connection << data
-
end
-
-
26
def can_buffer_more_requests?
-
7004
(@handshake_completed || !@wait_for_handshake) &&
-
@streams.size < @max_concurrent_requests &&
-
@streams.size < @max_requests
-
end
-
-
26
def send(request, head = false)
-
6541
unless can_buffer_more_requests?
-
3174
head ? @pending.unshift(request) : @pending << request
-
3174
return false
-
end
-
3367
unless (stream = @streams[request])
-
3367
stream = @connection.new_stream
-
3367
handle_stream(stream, request)
-
2990
@streams[request] = stream
-
2990
@max_requests -= 1
-
end
-
3367
handle(request, stream)
-
3351
true
-
rescue ::HTTP2::Error::StreamLimitExceeded
-
@pending.unshift(request)
-
false
-
end
-
-
26
def consume
-
22587
@streams.each do |request, stream|
-
8613
next if request.state == :done
-
-
981
handle(request, stream)
-
end
-
end
-
-
26
def handle_error(ex, request = nil)
-
261
if ex.instance_of?(TimeoutError) && !@handshake_completed && @connection.state != :closed
-
8
@connection.goaway(:settings_timeout, "closing due to settings timeout")
-
8
emit(:close_handshake)
-
8
settings_ex = SettingsTimeoutError.new(ex.timeout, ex.message)
-
8
settings_ex.set_backtrace(ex.backtrace)
-
8
ex = settings_ex
-
end
-
261
@streams.each_key do |req|
-
216
next if request && request == req
-
-
14
emit(:error, req, ex)
-
end
-
491
while (req = @pending.shift)
-
31
next if request && request == req
-
-
31
emit(:error, req, ex)
-
end
-
end
-
-
26
def ping
-
8
ping = SecureRandom.gen_random(8)
-
8
@connection.ping(ping)
-
ensure
-
8
@pings << ping
-
end
-
-
26
private
-
-
26
def send_pending
-
7879
while (request = @pending.shift)
-
3054
break unless send(request, true)
-
end
-
end
-
-
26
def handle(request, stream)
-
4412
catch(:buffer_full) do
-
4412
request.transition(:headers)
-
4404
join_headers(stream, request) if request.state == :headers
-
4404
request.transition(:body)
-
4404
join_body(stream, request) if request.state == :body
-
3538
request.transition(:trailers)
-
3538
join_trailers(stream, request) if request.state == :trailers && !request.body.empty?
-
3538
request.transition(:done)
-
end
-
end
-
-
26
def init_connection
-
2983
@connection = ::HTTP2::Client.new(@settings)
-
2983
@connection.on(:frame, &method(:on_frame))
-
2983
@connection.on(:frame_sent, &method(:on_frame_sent))
-
2983
@connection.on(:frame_received, &method(:on_frame_received))
-
2983
@connection.on(:origin, &method(:on_origin))
-
2983
@connection.on(:promise, &method(:on_promise))
-
2983
@connection.on(:altsvc) { |frame| on_altsvc(frame[:origin], frame) }
-
2983
@connection.on(:settings_ack, &method(:on_settings))
-
2983
@connection.on(:ack, &method(:on_pong))
-
2983
@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.
-
#
-
2983
@connection.send_connection_preface
-
end
-
-
26
alias_method :reset, :init_connection
-
26
public :reset
-
-
26
def handle_stream(stream, request)
-
3383
request.on(:refuse, &method(:on_stream_refuse).curry(3)[stream, request])
-
3383
stream.on(:close, &method(:on_stream_close).curry(3)[stream, request])
-
3383
stream.on(:half_close) do
-
3361
log(level: 2) { "#{stream.id}: waiting for response..." }
-
end
-
3383
stream.on(:altsvc, &method(:on_altsvc).curry(2)[request.origin])
-
3383
stream.on(:headers, &method(:on_stream_headers).curry(3)[stream, request])
-
3383
stream.on(:data, &method(:on_stream_data).curry(3)[stream, request])
-
end
-
-
26
def set_protocol_headers(request)
-
376
{
-
2982
":scheme" => request.scheme,
-
":method" => request.verb,
-
":path" => request.path,
-
":authority" => request.authority,
-
}
-
end
-
-
26
def join_headers(stream, request)
-
3359
extra_headers = set_protocol_headers(request)
-
-
3359
if request.headers.key?("host")
-
8
log { "forbidden \"host\" header found (#{request.headers["host"]}), will use it as authority..." }
-
7
extra_headers[":authority"] = request.headers["host"]
-
end
-
-
3359
log(level: 1, color: :yellow) do
-
128
request.headers.merge(extra_headers).each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{v}" }.join("\n")
-
end
-
3359
stream.headers(request.headers.each(extra_headers), end_stream: request.body.empty?)
-
end
-
-
26
def join_trailers(stream, request)
-
1381
unless request.trailers?
-
1373
stream.data("", end_stream: true) if request.callbacks_for?(:trailers)
-
1227
return
-
end
-
-
8
log(level: 1, color: :yellow) do
-
15
request.trailers.each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{v}" }.join("\n")
-
end
-
8
stream.headers(request.trailers.each, end_stream: true)
-
end
-
-
26
def join_body(stream, request)
-
4225
return if request.body.empty?
-
-
2247
chunk = @drains.delete(request) || request.drain_body
-
2424
while chunk
-
2613
next_chunk = request.drain_body
-
2634
log(level: 1, color: :green) { "#{stream.id}: -> DATA: #{chunk.bytesize} bytes..." }
-
2634
log(level: 2, color: :green) { "#{stream.id}: -> #{chunk.inspect}" }
-
2613
stream.data(chunk, end_stream: !(next_chunk || request.trailers? || request.callbacks_for?(:trailers)))
-
2613
if next_chunk && (@buffer.full? || request.body.unbounded_body?)
-
762
@drains[request] = next_chunk
-
866
throw(:buffer_full)
-
end
-
1747
chunk = next_chunk
-
end
-
-
1381
return unless (error = request.drain_error)
-
-
12
on_stream_refuse(stream, request, error)
-
end
-
-
######
-
# HTTP/2 Callbacks
-
######
-
-
26
def on_stream_headers(stream, request, h)
-
3340
response = request.response
-
-
3340
if response.is_a?(Response) && response.version == "2.0"
-
114
on_stream_trailers(stream, response, h)
-
114
return
-
end
-
-
3226
log(color: :yellow) do
-
128
h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{v}" }.join("\n")
-
end
-
3226
_, status = h.shift
-
3226
headers = request.options.headers_class.new(h)
-
3226
response = request.options.response_class.new(request, status, "2.0", headers)
-
3226
request.response = response
-
2859
@streams[request] = stream
-
-
3218
handle(request, stream) if request.expects?
-
end
-
-
26
def on_stream_trailers(stream, response, h)
-
114
log(color: :yellow) do
-
h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{v}" }.join("\n")
-
end
-
114
response.merge_headers(h)
-
end
-
-
26
def on_stream_data(stream, request, data)
-
5832
log(level: 1, color: :green) { "#{stream.id}: <- DATA: #{data.bytesize} bytes..." }
-
5832
log(level: 2, color: :green) { "#{stream.id}: <- #{data.inspect}" }
-
5815
request.response << data
-
end
-
-
26
def on_stream_refuse(stream, request, error)
-
12
on_stream_close(stream, request, error)
-
12
stream.close
-
end
-
-
26
def on_stream_close(stream, request, error)
-
3140
return if error == :stream_closed && !@streams.key?(request)
-
-
3142
log(level: 2) { "#{stream.id}: closing stream" }
-
3128
@drains.delete(request)
-
3128
@streams.delete(request)
-
-
3128
if error
-
12
ex = Error.new(stream.id, error)
-
12
ex.set_backtrace(caller)
-
12
response = ErrorResponse.new(request, ex)
-
12
request.response = response
-
12
emit(:response, request, response)
-
else
-
3116
response = request.response
-
3116
if response && response.is_a?(Response) && response.status == 421
-
8
ex = MisdirectedRequestError.new(response)
-
8
ex.set_backtrace(caller)
-
8
emit(:error, request, ex)
-
else
-
3108
emit(:response, request, response)
-
end
-
end
-
3120
send(@pending.shift) unless @pending.empty?
-
-
3120
return unless @streams.empty? && exhausted?
-
-
8
if @pending.empty?
-
close
-
else
-
8
emit(:exhausted)
-
end
-
end
-
-
26
def on_frame(bytes)
-
18592
@buffer << bytes
-
end
-
-
26
def on_settings(*)
-
2952
@handshake_completed = true
-
2952
emit(:current_timeout)
-
2952
@max_concurrent_requests = [@max_concurrent_requests, @connection.remote_settings[:settings_max_concurrent_streams]].min
-
2952
send_pending
-
end
-
-
26
def on_close(_last_frame, error, _payload)
-
22
is_connection_closed = @connection.state == :closed
-
22
if error
-
22
@buffer.clear if is_connection_closed
-
22
if error == :no_error
-
15
ex = GoawayError.new
-
15
@pending.unshift(*@streams.keys)
-
15
@drains.clear
-
15
@streams.clear
-
else
-
7
ex = Error.new(0, error)
-
end
-
22
ex.set_backtrace(caller)
-
22
handle_error(ex)
-
end
-
22
return unless is_connection_closed && @streams.empty?
-
-
22
emit(:close, is_connection_closed)
-
end
-
-
26
def on_frame_sent(frame)
-
15684
log(level: 2) { "#{frame[:stream]}: frame was sent!" }
-
15600
log(level: 2, color: :blue) do
-
96
payload = frame
-
96
payload = payload.merge(payload: frame[:payload].bytesize) if frame[:type] == :data
-
84
"#{frame[:stream]}: #{payload}"
-
end
-
end
-
-
26
def on_frame_received(frame)
-
16439
log(level: 2) { "#{frame[:stream]}: frame was received!" }
-
16380
log(level: 2, color: :magenta) do
-
67
payload = frame
-
67
payload = payload.merge(payload: frame[:payload].bytesize) if frame[:type] == :data
-
59
"#{frame[:stream]}: #{payload}"
-
end
-
end
-
-
26
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
-
-
26
def on_promise(stream)
-
24
emit(:promise, @streams.key(stream.parent), stream)
-
end
-
-
26
def on_origin(origin)
-
emit(:origin, origin)
-
end
-
-
26
def on_pong(ping)
-
8
if @pings.delete(ping.to_s)
-
8
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.
-
-
26
require "ipaddr"
-
-
26
module HTTPX
-
# Represents a domain name ready for extracting its registered domain
-
# and TLD.
-
26
class DomainName
-
26
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.
-
26
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.
-
26
attr_reader :domain
-
-
26
class << self
-
26
def new(domain)
-
856
return domain if domain.is_a?(self)
-
-
792
super(domain)
-
end
-
-
# Normalizes a _domain_ using the Punycode algorithm as necessary.
-
# The result will be a downcased, ASCII-only string.
-
26
def normalize(domain)
-
760
unless domain.ascii_only?
-
domain = domain.chomp(".").unicode_normalize(:nfc)
-
domain = Punycode.encode_hostname(domain)
-
end
-
-
760
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.
-
26
def initialize(hostname)
-
792
hostname = String(hostname)
-
-
792
raise ArgumentError, "domain name must not start with a dot: #{hostname}" if hostname.start_with?(".")
-
-
98
begin
-
792
@ipaddr = IPAddr.new(hostname)
-
32
@hostname = @ipaddr.to_s
-
32
return
-
rescue IPAddr::Error
-
760
nil
-
end
-
-
760
@hostname = DomainName.normalize(hostname)
-
760
tld = if (last_dot = @hostname.rindex("."))
-
184
@hostname[(last_dot + 1)..-1]
-
else
-
576
@hostname
-
end
-
-
# unknown/local TLD
-
760
@domain = if last_dot
-
# fallback - accept cookies down to second level
-
# cf. http://www.dkim-reputation.org/regdom-libs/
-
184
if (penultimate_dot = @hostname.rindex(".", last_dot - 1))
-
48
@hostname[(penultimate_dot + 1)..-1]
-
else
-
136
@hostname
-
end
-
else
-
# no domain part - must be a local hostname
-
576
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.
-
26
def cookie_domain?(domain, host_only = false)
-
# RFC 6265 #5.3
-
# When the user agent "receives a cookie":
-
32
return self == @domain if host_only
-
-
32
domain = DomainName.new(domain)
-
-
# RFC 6265 #5.1.3
-
# Do not perform subdomain matching against IP addresses.
-
32
@hostname == domain.hostname if @ipaddr
-
-
# RFC 6265 #4.1.1
-
# Domain-value must be a subdomain.
-
32
@domain && self <= domain && domain <= @domain
-
end
-
-
26
def <=>(other)
-
48
other = DomainName.new(other)
-
48
othername = other.hostname
-
48
if othername == @hostname
-
16
0
-
31
elsif @hostname.end_with?(othername) && @hostname[-othername.size - 1, 1] == "."
-
# The other is higher
-
16
-1
-
else
-
# The other is lower
-
16
1
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
# the default exception class for exceptions raised by HTTPX.
-
26
class Error < StandardError; end
-
-
26
class UnsupportedSchemeError < Error; end
-
-
26
class ConnectionError < Error; end
-
-
# Error raised when there was a timeout. Its subclasses allow for finer-grained
-
# control of which timeout happened.
-
26
class TimeoutError < Error
-
# The timeout value which caused this error to be raised.
-
26
attr_reader :timeout
-
-
# initializes the timeout exception with the +timeout+ causing the error, and the
-
# error +message+ for it.
-
26
def initialize(timeout, message)
-
512
@timeout = timeout
-
512
super(message)
-
end
-
-
# clones this error into a HTTPX::ConnectionTimeoutError.
-
26
def to_connection_error
-
24
ex = ConnectTimeoutError.new(@timeout, message)
-
24
ex.set_backtrace(backtrace)
-
24
ex
-
end
-
end
-
-
# Raise when it can't acquire a connection for a given origin.
-
26
class PoolTimeoutError < TimeoutError
-
26
attr_reader :origin
-
-
# initializes the +origin+ it refers to, and the
-
# +timeout+ causing the error.
-
26
def initialize(origin, timeout)
-
8
@origin = origin
-
8
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.
-
26
class ConnectTimeoutError < TimeoutError; end
-
-
# Error raised when there was a timeout while sending a request, or receiving a response
-
# from the server.
-
26
class RequestTimeoutError < TimeoutError
-
# The HTTPX::Request request object this exception refers to.
-
26
attr_reader :request
-
-
# initializes the exception with the +request+ and +response+ it refers to, and the
-
# +timeout+ causing the error, and the
-
26
def initialize(request, response, timeout)
-
409
@request = request
-
409
@response = response
-
409
super(timeout, "Timed out after #{timeout} seconds")
-
end
-
-
26
def marshal_dump
-
[message]
-
end
-
end
-
-
# Error raised when there was a timeout while receiving a response from the server.
-
26
class ReadTimeoutError < RequestTimeoutError; end
-
-
# Error raised when there was a timeout while sending a request from the server.
-
26
class WriteTimeoutError < RequestTimeoutError; end
-
-
# Error raised when there was a timeout while waiting for the HTTP/2 settings frame from the server.
-
26
class SettingsTimeoutError < TimeoutError; end
-
-
# Error raised when there was a timeout while resolving a domain to an IP.
-
26
class ResolveTimeoutError < TimeoutError; end
-
-
# Error raised when there was an error while resolving a domain to an IP.
-
26
class ResolveError < Error; end
-
-
# Error raised when there was an error while resolving a domain to an IP
-
# using a HTTPX::Resolver::Native resolver.
-
26
class NativeResolveError < ResolveError
-
26
attr_reader :connection, :host
-
-
# initializes the exception with the +connection+ it refers to, the +host+ domain
-
# which failed to resolve, and the error +message+.
-
26
def initialize(connection, host, message = "Can't resolve #{host}")
-
120
@connection = connection
-
120
@host = host
-
120
super(message)
-
end
-
end
-
-
# The exception class for HTTP responses with 4xx or 5xx status.
-
26
class HTTPError < Error
-
# The HTTPX::Response response object this exception refers to.
-
26
attr_reader :response
-
-
# Creates the instance and assigns the HTTPX::Response +response+.
-
26
def initialize(response)
-
97
@response = response
-
97
super("HTTP Error: #{@response.status} #{@response.headers}\n#{@response.body}")
-
end
-
-
# The HTTP response status.
-
#
-
# error.status #=> 404
-
26
def status
-
16
@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.
-
26
class MisdirectedRequestError < HTTPError; end
-
end
-
# frozen_string_literal: true
-
-
26
require "uri"
-
-
26
module HTTPX
-
26
module ArrayExtensions
-
26
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
-
25
end unless Array.method_defined?(:filter_map)
-
end
-
-
26
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
-
25
end unless Array.method_defined?(:intersect?)
-
end
-
end
-
-
26
module URIExtensions
-
# uri 0.11 backport, ships with ruby 3.1
-
26
refine URI::Generic do
-
-
26
def non_ascii_hostname
-
434
@non_ascii_hostname
-
end
-
-
26
def non_ascii_hostname=(hostname)
-
32
@non_ascii_hostname = hostname
-
end
-
-
def authority
-
5339
return host if port == default_port
-
-
558
"#{host}:#{port}"
-
25
end unless URI::HTTP.method_defined?(:authority)
-
-
def origin
-
4344
"#{scheme}://#{authority}"
-
25
end unless URI::HTTP.method_defined?(:origin)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
26
class Headers
-
26
class << self
-
26
def new(headers = nil)
-
24523
return headers if headers.is_a?(self)
-
-
11260
super
-
end
-
end
-
-
26
def initialize(headers = nil)
-
11260
@headers = {}
-
11260
return unless headers
-
-
11075
headers.each do |field, value|
-
57400
array_value(value).each do |v|
-
57456
add(downcased(field), v)
-
end
-
end
-
end
-
-
# cloned initialization
-
26
def initialize_clone(orig)
-
8
super
-
8
@headers = orig.instance_variable_get(:@headers).clone
-
end
-
-
# dupped initialization
-
26
def initialize_dup(orig)
-
14170
super
-
14170
@headers = orig.instance_variable_get(:@headers).dup
-
end
-
-
# freezes the headers hash
-
26
def freeze
-
15798
@headers.freeze
-
15798
super
-
end
-
-
26
def same_headers?(headers)
-
32
@headers.empty? || begin
-
32
headers.each do |k, v|
-
72
next unless key?(k)
-
-
72
return false unless v == self[k]
-
end
-
16
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
-
#
-
26
def merge(other)
-
4422
headers = dup
-
4422
other.each do |field, value|
-
3389
headers[downcased(field)] = value
-
end
-
4422
headers
-
end
-
-
# returns the comma-separated values of the header field
-
# identified by +field+, or nil otherwise.
-
#
-
26
def [](field)
-
85815
a = @headers[downcased(field)] || return
-
25797
a.join(", ")
-
end
-
-
# sets +value+ (if not nil) as single value for the +field+ header.
-
#
-
26
def []=(field, value)
-
38210
return unless value
-
-
34256
@headers[downcased(field)] = array_value(value)
-
end
-
-
# deletes all values associated with +field+ header.
-
#
-
26
def delete(field)
-
257
canonical = downcased(field)
-
257
@headers.delete(canonical) if @headers.key?(canonical)
-
end
-
-
# adds additional +value+ to the existing, for header +field+.
-
#
-
26
def add(field, value)
-
57928
(@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"
-
#
-
26
alias_method :add_header, :add
-
-
# returns the enumerable headers store in pairs of header field + the values in
-
# the comma-separated string format
-
#
-
26
def each(extra_headers = nil)
-
62051
return enum_for(__method__, extra_headers) { @headers.size } unless block_given?
-
-
33099
@headers.each do |field, value|
-
41597
yield(field, value.join(", ")) unless value.empty?
-
end
-
-
5617
extra_headers.each do |field, value|
-
22883
yield(field, value) unless value.empty?
-
33082
end if extra_headers
-
end
-
-
26
def ==(other)
-
19372
other == to_hash
-
end
-
-
# the headers store in Hash format
-
26
def to_hash
-
20670
Hash[to_a]
-
end
-
26
alias_method :to_h, :to_hash
-
-
# the headers store in array of pairs format
-
26
def to_a
-
20693
Array(each)
-
end
-
-
# headers as string
-
26
def to_s
-
1901
@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!
-
#
-
26
def key?(downcased_key)
-
60065
@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.
-
#
-
26
def get(field)
-
287
@headers[field] || EMPTY
-
end
-
-
26
private
-
-
26
def array_value(value)
-
85343
case value
-
when Array
-
91870
value.map { |val| String(val).strip }
-
else
-
54415
[String(value).strip]
-
end
-
end
-
-
26
def downcased(field)
-
243401
String(field).downcase
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "socket"
-
26
require "httpx/io/udp"
-
26
require "httpx/io/tcp"
-
26
require "httpx/io/unix"
-
-
begin
-
26
require "httpx/io/ssl"
-
rescue LoadError
-
end
-
# frozen_string_literal: true
-
-
26
require "openssl"
-
-
26
module HTTPX
-
26
TLSError = OpenSSL::SSL::SSLError
-
-
26
class SSL < TCP
-
# rubocop:disable Style/MutableConstant
-
26
TLS_OPTIONS = { alpn_protocols: %w[h2 http/1.1].freeze }
-
# https://github.com/jruby/jruby-openssl/issues/284
-
26
TLS_OPTIONS[:verify_hostname] = true if RUBY_ENGINE == "jruby"
-
# rubocop:enable Style/MutableConstant
-
26
TLS_OPTIONS.freeze
-
-
26
attr_writer :ssl_session
-
-
26
def initialize(_, _, options)
-
2767
super
-
-
2767
ctx_options = TLS_OPTIONS.merge(options.ssl)
-
2767
@sni_hostname = ctx_options.delete(:hostname) || @hostname
-
-
2767
if @keep_open && @io.is_a?(OpenSSL::SSL::SSLSocket)
-
# externally initiated ssl socket
-
22
@ctx = @io.context
-
22
@state = :negotiated
-
else
-
2745
@ctx = OpenSSL::SSL::SSLContext.new
-
2745
@ctx.set_params(ctx_options) unless ctx_options.empty?
-
2745
unless @ctx.session_cache_mode.nil? # a dummy method on JRuby
-
2438
@ctx.session_cache_mode =
-
OpenSSL::SSL::SSLContext::SESSION_CACHE_CLIENT | OpenSSL::SSL::SSLContext::SESSION_CACHE_NO_INTERNAL_STORE
-
end
-
-
2745
yield(self) if block_given?
-
end
-
-
2767
@verify_hostname = @ctx.verify_hostname
-
end
-
-
26
if OpenSSL::SSL::SSLContext.method_defined?(:session_new_cb=)
-
25
def session_new_cb(&pr)
-
7040
@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
-
-
26
def protocol
-
2669
@io.alpn_protocol || super
-
rescue StandardError
-
7
super
-
end
-
-
26
if RUBY_ENGINE == "jruby"
-
# in jruby, alpn_protocol may return ""
-
# https://github.com/jruby/jruby-openssl/issues/287
-
1
def protocol
-
337
proto = @io.alpn_protocol
-
-
336
return super if proto.nil? || proto.empty?
-
-
335
proto
-
rescue StandardError
-
1
super
-
end
-
end
-
-
26
def can_verify_peer?
-
13
@ctx.verify_mode == OpenSSL::SSL::VERIFY_PEER
-
end
-
-
26
def verify_hostname(host)
-
15
return false if @ctx.verify_mode == OpenSSL::SSL::VERIFY_NONE
-
15
return false if !@io.respond_to?(:peer_cert) || @io.peer_cert.nil?
-
-
15
OpenSSL::SSL.verify_certificate_identity(@io.peer_cert, host)
-
end
-
-
26
def connected?
-
11206
@state == :negotiated
-
end
-
-
26
def expired?
-
super || ssl_session_expired?
-
end
-
-
26
def ssl_session_expired?
-
2966
@ssl_session.nil? || Process.clock_gettime(Process::CLOCK_REALTIME) >= (@ssl_session.time.to_f + @ssl_session.timeout)
-
end
-
-
26
def connect
-
11256
super
-
11230
return if @state == :negotiated ||
-
@state != :connected
-
-
7909
unless @io.is_a?(OpenSSL::SSL::SSLSocket)
-
2966
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
-
32
@sni_hostname = @ip.to_string
-
# IP addresses in SNI is not valid per RFC 6066, section 3.
-
32
@ctx.verify_hostname = false
-
end
-
-
2966
@io = OpenSSL::SSL::SSLSocket.new(@io, @ctx)
-
-
2966
@io.hostname = @sni_hostname unless hostname_is_ip
-
2966
@io.session = @ssl_session unless ssl_session_expired?
-
2966
@io.sync_close = true
-
end
-
7909
try_ssl_connect
-
end
-
-
26
def try_ssl_connect
-
7909
ret = @io.connect_nonblock(exception: false)
-
7927
log(level: 3, color: :cyan) { "TLS CONNECT: #{ret}..." }
-
7187
case ret
-
when :wait_readable
-
4967
@interests = :r
-
4967
return
-
when :wait_writable
-
@interests = :w
-
return
-
end
-
2919
@io.post_connection_check(@sni_hostname) if @ctx.verify_mode != OpenSSL::SSL::VERIFY_NONE && @verify_hostname
-
2918
transition(:negotiated)
-
2918
@interests = :w
-
end
-
-
26
private
-
-
26
def transition(nextstate)
-
10194
case nextstate
-
when :negotiated
-
2918
return unless @state == :connected
-
-
when :closed
-
2826
return unless @state == :negotiated ||
-
@state == :connected
-
end
-
11524
do_transition(nextstate)
-
end
-
-
26
def log_transition_state(nextstate)
-
70
return super unless nextstate == :negotiated
-
-
16
server_cert = @io.peer_cert
-
-
14
"#{super}\n\n" \
-
2
"SSL connection using #{@io.ssl_version} / #{Array(@io.cipher).first}\n" \
-
2
"ALPN, server accepted to use #{protocol}\n" \
-
"Server certificate:\n " \
-
2
"subject: #{server_cert.subject}\n " \
-
2
"start date: #{server_cert.not_before}\n " \
-
2
"expire date: #{server_cert.not_after}\n " \
-
2
"issuer: #{server_cert.issuer}\n " \
-
"SSL certificate verify ok."
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "resolv"
-
26
require "ipaddr"
-
-
26
module HTTPX
-
26
class TCP
-
26
include Loggable
-
-
26
using URIExtensions
-
-
26
attr_reader :ip, :port, :addresses, :state, :interests
-
-
26
alias_method :host, :ip
-
-
26
def initialize(origin, addresses, options)
-
6638
@state = :idle
-
6638
@addresses = []
-
6638
@hostname = origin.host
-
6638
@options = options
-
6638
@fallback_protocol = @options.fallback_protocol
-
6638
@port = origin.port
-
6638
@interests = :w
-
6638
if @options.io
-
52
@io = case @options.io
-
when Hash
-
16
@options.io[origin.authority]
-
else
-
36
@options.io
-
end
-
52
raise Error, "Given IO objects do not match the request authority" unless @io
-
-
52
_, _, _, @ip = @io.addr
-
52
@addresses << @ip
-
52
@keep_open = true
-
52
@state = :connected
-
else
-
6586
add_addresses(addresses)
-
end
-
6638
@ip_index = @addresses.size - 1
-
end
-
-
26
def socket
-
195
@io
-
end
-
-
26
def add_addresses(addrs)
-
6791
return if addrs.empty?
-
-
24480
addrs = addrs.map { |addr| addr.is_a?(IPAddr) ? addr : IPAddr.new(addr) }
-
-
6791
ip_index = @ip_index || (@addresses.size - 1)
-
6791
if addrs.first.ipv6?
-
# should be the next in line
-
215
@addresses = [*@addresses[0, ip_index], *addrs, *@addresses[ip_index..-1]]
-
else
-
6576
@addresses.unshift(*addrs)
-
6576
@ip_index += addrs.size if @ip_index
-
end
-
end
-
-
26
def to_io
-
20671
@io.to_io
-
end
-
-
26
def protocol
-
4217
@fallback_protocol
-
end
-
-
26
def connect
-
24612
return unless closed?
-
-
19453
if !@io || @io.closed?
-
7276
transition(:idle)
-
7276
@io = build_socket
-
end
-
19453
try_connect
-
rescue Errno::ECONNREFUSED,
-
Errno::EADDRNOTAVAIL,
-
Errno::EHOSTUNREACH,
-
SocketError,
-
IOError => e
-
505
raise e if @ip_index <= 0
-
-
449
log { "failed connecting to #{@ip} (#{e.message}), trying next..." }
-
430
@ip_index -= 1
-
437
@io = build_socket
-
437
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
-
-
26
def try_connect
-
19453
ret = @io.connect_nonblock(Socket.sockaddr_in(@port, @ip.to_s), exception: false)
-
15013
log(level: 3, color: :cyan) { "TCP CONNECT: #{ret}..." }
-
13248
case ret
-
when :wait_readable
-
@interests = :r
-
return
-
when :wait_writable
-
7701
@interests = :w
-
7701
return
-
end
-
7208
transition(:connected)
-
7208
@interests = :w
-
rescue Errno::EALREADY
-
4039
@interests = :w
-
end
-
26
private :try_connect
-
-
26
def read(size, buffer)
-
46812
ret = @io.read_nonblock(size, buffer, exception: false)
-
46812
if ret == :wait_readable
-
9248
buffer.clear
-
8495
return 0
-
end
-
37564
return if ret.nil?
-
-
37622
log { "READ: #{buffer.bytesize} bytes..." }
-
37546
buffer.bytesize
-
end
-
-
26
def write(buffer)
-
19859
siz = @io.write_nonblock(buffer, exception: false)
-
19826
return 0 if siz == :wait_writable
-
19802
return if siz.nil?
-
-
19889
log { "WRITE: #{siz} bytes..." }
-
-
19802
buffer.shift!(siz)
-
19802
siz
-
end
-
-
26
def close
-
7869
return if @keep_open || closed?
-
-
808
begin
-
7006
@io.close
-
ensure
-
7006
transition(:closed)
-
end
-
end
-
-
26
def connected?
-
12891
@state == :connected
-
end
-
-
26
def closed?
-
32468
@state == :idle || @state == :closed
-
end
-
-
26
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:
-
-
26
private
-
-
26
def build_socket
-
7713
@ip = @addresses[@ip_index]
-
7713
Socket.new(@ip.family, :STREAM, 0)
-
end
-
-
26
def transition(nextstate)
-
11427
case nextstate
-
# when :idle
-
when :connected
-
4345
return unless @state == :idle
-
when :closed
-
4180
return unless @state == :connected
-
end
-
12905
do_transition(nextstate)
-
end
-
-
26
def do_transition(nextstate)
-
24577
log(level: 1) { log_transition_state(nextstate) }
-
24429
@state = nextstate
-
end
-
-
26
def log_transition_state(nextstate)
-
131
case nextstate
-
when :connected
-
40
"Connected to #{host} (##{@io.fileno})"
-
else
-
96
"#{host} #{@state} -> #{nextstate}"
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "ipaddr"
-
-
26
module HTTPX
-
26
class UDP
-
26
include Loggable
-
-
26
def initialize(ip, port, options)
-
377
@host = ip
-
377
@port = port
-
377
@io = UDPSocket.new(IPAddr.new(ip).family)
-
377
@options = options
-
end
-
-
26
def to_io
-
1187
@io.to_io
-
end
-
-
26
def connect; end
-
-
26
def connected?
-
377
true
-
end
-
-
26
def close
-
383
@io.close
-
end
-
-
26
if RUBY_ENGINE == "jruby"
-
# In JRuby, sendmsg_nonblock is not implemented
-
1
def write(buffer)
-
55
siz = @io.send(buffer.to_s, 0, @host, @port)
-
55
log { "WRITE: #{siz} bytes..." }
-
55
buffer.shift!(siz)
-
55
siz
-
end
-
else
-
25
def write(buffer)
-
641
siz = @io.sendmsg_nonblock(buffer.to_s, 0, Socket.sockaddr_in(@port, @host.to_s), exception: false)
-
641
return 0 if siz == :wait_writable
-
641
return if siz.nil?
-
-
641
log { "WRITE: #{siz} bytes..." }
-
-
641
buffer.shift!(siz)
-
641
siz
-
end
-
end
-
-
26
def read(size, buffer)
-
943
ret = @io.recvfrom_nonblock(size, 0, buffer, exception: false)
-
943
return 0 if ret == :wait_readable
-
642
return if ret.nil?
-
-
642
log { "READ: #{buffer.bytesize} bytes..." }
-
-
642
buffer.bytesize
-
rescue IOError
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
26
class UNIX < TCP
-
26
using URIExtensions
-
-
26
attr_reader :path
-
-
26
alias_method :host, :path
-
-
26
def initialize(origin, path, options)
-
28
@addresses = []
-
28
@hostname = origin.host
-
28
@state = :idle
-
28
@options = options
-
28
@fallback_protocol = @options.fallback_protocol
-
28
if @options.io
-
14
@io = case @options.io
-
when Hash
-
7
@options.io[origin.authority]
-
else
-
7
@options.io
-
end
-
14
raise Error, "Given IO objects do not match the request authority" unless @io
-
-
14
@path = @io.path
-
14
@keep_open = true
-
14
@state = :connected
-
14
elsif path
-
14
@path = path
-
else
-
raise Error, "No path given where to store the socket"
-
end
-
28
@io ||= build_socket
-
end
-
-
26
def connect
-
21
return unless closed?
-
-
begin
-
21
if @io.closed?
-
7
transition(:idle)
-
7
@io = build_socket
-
end
-
21
@io.connect_nonblock(Socket.sockaddr_un(@path))
-
rescue Errno::EISCONN
-
end
-
14
transition(:connected)
-
rescue Errno::EINPROGRESS,
-
Errno::EALREADY,
-
::IO::WaitReadable
-
end
-
-
26
def expired?
-
false
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}(path: #{@path}): (state: #{@state})>"
-
skipped
end
-
skipped
# :nocov:
-
-
26
private
-
-
26
def build_socket
-
21
Socket.new(Socket::PF_UNIX, :STREAM, 0)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
26
module Loggable
-
26
COLORS = {
-
black: 30,
-
red: 31,
-
green: 32,
-
yellow: 33,
-
blue: 34,
-
magenta: 35,
-
cyan: 36,
-
white: 37,
-
}.freeze
-
-
26
USE_DEBUG_LOG = ENV.key?("HTTPX_DEBUG")
-
-
26
def log(level: @options.debug_level, color: nil, &msg)
-
368416
return unless @options.debug_level >= level
-
-
166191
debug_stream = @options.debug || ($stderr if USE_DEBUG_LOG)
-
-
166191
return unless debug_stream
-
-
1617
message = (+"" << msg.call << "\n")
-
1617
message = "\e[#{COLORS[color]}m#{message}\e[0m" if color && debug_stream.respond_to?(:isatty) && debug_stream.isatty
-
1617
debug_stream << message
-
end
-
-
26
def log_exception(ex, level: @options.debug_level, color: nil)
-
1169
log(level: level, color: color) { ex.full_message }
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "socket"
-
-
26
module HTTPX
-
# Contains a set of options which are passed and shared across from session to its requests or
-
# responses.
-
26
class Options
-
26
BUFFER_SIZE = 1 << 14
-
26
WINDOW_SIZE = 1 << 14 # 16K
-
26
MAX_BODY_THRESHOLD_SIZE = (1 << 10) * 112 # 112K
-
26
KEEP_ALIVE_TIMEOUT = 20
-
26
SETTINGS_TIMEOUT = 10
-
26
CLOSE_HANDSHAKE_TIMEOUT = 10
-
26
CONNECT_TIMEOUT = READ_TIMEOUT = WRITE_TIMEOUT = 60
-
26
REQUEST_TIMEOUT = OPERATION_TIMEOUT = nil
-
-
# https://github.com/ruby/resolv/blob/095f1c003f6073730500f02acbdbc55f83d70987/lib/resolv.rb#L408
-
2
ip_address_families = begin
-
26
list = Socket.ip_address_list
-
106
if list.any? { |a| a.ipv6? && !a.ipv6_loopback? && !a.ipv6_linklocal? && !a.ipv6_unique_local? }
-
[Socket::AF_INET6, Socket::AF_INET]
-
else
-
26
[Socket::AF_INET]
-
end
-
rescue NotImplementedError
-
[Socket::AF_INET]
-
end.freeze
-
-
2
DEFAULT_OPTIONS = {
-
24
:max_requests => Float::INFINITY,
-
:debug => nil,
-
26
: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,
-
26
:resolver_class => (ENV["HTTPX_RESOLVER"] || :native).to_sym,
-
:resolver_options => { cache: true }.freeze,
-
:pool_options => EMPTY_HASH,
-
:ip_families => ip_address_families,
-
}.freeze
-
-
26
class << self
-
26
def new(options = {})
-
# let enhanced options go through
-
11431
return options if self == Options && options.class < self
-
8859
return options if options.is_a?(self)
-
-
4459
super
-
end
-
-
26
def method_added(meth)
-
19302
super
-
-
19302
return unless meth =~ /^option_(.+)$/
-
-
8985
optname = Regexp.last_match(1).to_sym
-
-
8985
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.
-
26
def initialize(options = {})
-
4459
do_initialize(options)
-
4443
freeze
-
end
-
-
26
def freeze
-
11358
super
-
11358
@origin.freeze
-
11358
@base_path.freeze
-
11358
@timeout.freeze
-
11358
@headers.freeze
-
11358
@addresses.freeze
-
11358
@supported_compression_formats.freeze
-
end
-
-
26
def option_origin(value)
-
608
URI(value)
-
end
-
-
26
def option_base_path(value)
-
32
String(value)
-
end
-
-
26
def option_headers(value)
-
7836
headers_class.new(value)
-
end
-
-
26
def option_timeout(value)
-
8280
Hash[value]
-
end
-
-
26
def option_supported_compression_formats(value)
-
7244
Array(value).map(&:to_s)
-
end
-
-
26
def option_max_concurrent_requests(value)
-
963
raise TypeError, ":max_concurrent_requests must be positive" unless value.positive?
-
-
963
value
-
end
-
-
26
def option_max_requests(value)
-
7230
raise TypeError, ":max_requests must be positive" unless value.positive?
-
-
7230
value
-
end
-
-
26
def option_window_size(value)
-
7236
value = Integer(value)
-
-
7236
raise TypeError, ":window_size must be positive" unless value.positive?
-
-
7236
value
-
end
-
-
26
def option_buffer_size(value)
-
7236
value = Integer(value)
-
-
7236
raise TypeError, ":buffer_size must be positive" unless value.positive?
-
-
7236
value
-
end
-
-
26
def option_body_threshold_size(value)
-
7220
bytes = Integer(value)
-
7220
raise TypeError, ":body_threshold_size must be positive" unless bytes.positive?
-
-
7220
bytes
-
end
-
-
26
def option_transport(value)
-
49
transport = value.to_s
-
49
raise TypeError, "#{transport} is an unsupported transport type" unless %w[unix].include?(transport)
-
-
49
transport
-
end
-
-
26
def option_addresses(value)
-
43
Array(value)
-
end
-
-
26
def option_ip_families(value)
-
7220
Array(value)
-
end
-
-
26
%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|
-
520
class_eval(<<-OUT, __FILE__, __LINE__ + 1)
-
20
# sets +v+ as the value of #{method_name}
-
20
def option_#{method_name}(v); v; end # def option_smth(v); v; end
-
OUT
-
end
-
-
26
REQUEST_BODY_IVARS = %i[@headers].freeze
-
-
26
def ==(other)
-
1885
super || options_equals?(other)
-
end
-
-
26
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.
-
452
ivars = instance_variables - ignore_ivars
-
452
other_ivars = other.instance_variables - ignore_ivars
-
-
452
return false if ivars.size != other_ivars.size
-
-
435
return false if ivars.sort != other_ivars.sort
-
-
435
ivars.all? do |ivar|
-
10622
instance_variable_get(ivar) == other.instance_variable_get(ivar)
-
end
-
end
-
-
26
def merge(other)
-
33264
ivar_map = nil
-
33264
other_ivars = case other
-
when Hash
-
39846
ivar_map = other.keys.to_h { |k| [:"@#{k}", k] }
-
23043
ivar_map.keys
-
else
-
10221
other.instance_variables
-
end
-
-
33264
return self if other_ivars.empty?
-
-
273637
return self if other_ivars.all? { |ivar| instance_variable_get(ivar) == access_option(other, ivar, ivar_map) }
-
-
12212
opts = dup
-
-
12212
other_ivars.each do |ivar|
-
89835
v = access_option(other, ivar, ivar_map)
-
-
89835
unless v
-
3390
opts.instance_variable_set(ivar, v)
-
3390
next
-
end
-
-
86445
v = opts.__send__(:"option_#{ivar[1..-1]}", v)
-
-
86429
orig_v = instance_variable_get(ivar)
-
-
86429
v = orig_v.merge(v) if orig_v.respond_to?(:merge) && v.respond_to?(:merge)
-
-
86429
opts.instance_variable_set(ivar, v)
-
end
-
-
12196
opts
-
end
-
-
26
def to_hash
-
3310
instance_variables.each_with_object({}) do |ivar, hs|
-
77296
hs[ivar[1..-1].to_sym] = instance_variable_get(ivar)
-
end
-
end
-
-
26
def extend_with_plugin_classes(pl)
-
6873
if defined?(pl::RequestMethods) || defined?(pl::RequestClassMethods)
-
1945
@request_class = @request_class.dup
-
1945
@request_class.__send__(:include, pl::RequestMethods) if defined?(pl::RequestMethods)
-
1945
@request_class.extend(pl::RequestClassMethods) if defined?(pl::RequestClassMethods)
-
end
-
6873
if defined?(pl::ResponseMethods) || defined?(pl::ResponseClassMethods)
-
2137
@response_class = @response_class.dup
-
2137
@response_class.__send__(:include, pl::ResponseMethods) if defined?(pl::ResponseMethods)
-
2137
@response_class.extend(pl::ResponseClassMethods) if defined?(pl::ResponseClassMethods)
-
end
-
6873
if defined?(pl::HeadersMethods) || defined?(pl::HeadersClassMethods)
-
152
@headers_class = @headers_class.dup
-
152
@headers_class.__send__(:include, pl::HeadersMethods) if defined?(pl::HeadersMethods)
-
152
@headers_class.extend(pl::HeadersClassMethods) if defined?(pl::HeadersClassMethods)
-
end
-
6873
if defined?(pl::RequestBodyMethods) || defined?(pl::RequestBodyClassMethods)
-
314
@request_body_class = @request_body_class.dup
-
314
@request_body_class.__send__(:include, pl::RequestBodyMethods) if defined?(pl::RequestBodyMethods)
-
314
@request_body_class.extend(pl::RequestBodyClassMethods) if defined?(pl::RequestBodyClassMethods)
-
end
-
6873
if defined?(pl::ResponseBodyMethods) || defined?(pl::ResponseBodyClassMethods)
-
760
@response_body_class = @response_body_class.dup
-
760
@response_body_class.__send__(:include, pl::ResponseBodyMethods) if defined?(pl::ResponseBodyMethods)
-
760
@response_body_class.extend(pl::ResponseBodyClassMethods) if defined?(pl::ResponseBodyClassMethods)
-
end
-
6873
if defined?(pl::PoolMethods)
-
546
@pool_class = @pool_class.dup
-
546
@pool_class.__send__(:include, pl::PoolMethods)
-
end
-
6873
if defined?(pl::ConnectionMethods)
-
2890
@connection_class = @connection_class.dup
-
2890
@connection_class.__send__(:include, pl::ConnectionMethods)
-
end
-
6873
return unless defined?(pl::OptionsMethods)
-
-
2845
@options_class = @options_class.dup
-
2845
@options_class.__send__(:include, pl::OptionsMethods)
-
end
-
-
26
private
-
-
26
def do_initialize(options = {})
-
4459
defaults = DEFAULT_OPTIONS.merge(options)
-
4459
defaults.each do |k, v|
-
130207
next if v.nil?
-
-
116830
option_method_name = :"option_#{k}"
-
116830
raise Error, "unknown option: #{k}" unless respond_to?(option_method_name)
-
-
116822
value = __send__(option_method_name, v)
-
116814
instance_variable_set(:"@#{k}", value)
-
end
-
end
-
-
26
def access_option(obj, k, ivar_map)
-
307800
case obj
-
when Hash
-
26878
obj[ivar_map[k]]
-
else
-
316208
obj.instance_variable_get(k)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
26
module Parser
-
26
class Error < Error; end
-
-
26
class HTTP1
-
26
VERSIONS = %w[1.0 1.1].freeze
-
-
26
attr_reader :status_code, :http_version, :headers
-
-
26
def initialize(observer)
-
4391
@observer = observer
-
4391
@state = :idle
-
4391
@buffer = "".b
-
4391
@headers = {}
-
end
-
-
26
def <<(chunk)
-
6950
@buffer << chunk
-
6950
parse
-
end
-
-
26
def reset!
-
8971
@state = :idle
-
8971
@headers.clear
-
8971
@content_length = nil
-
8971
@_has_trailers = nil
-
end
-
-
26
def upgrade?
-
4397
@upgrade
-
end
-
-
26
def upgrade_data
-
32
@buffer
-
end
-
-
26
private
-
-
26
def parse
-
6950
loop do
-
14863
state = @state
-
13293
case @state
-
when :idle
-
4742
parse_headline
-
when :headers, :trailers
-
4830
parse_headers
-
when :data
-
5289
parse_data
-
end
-
10881
return if @buffer.empty? || state == @state
-
end
-
end
-
-
26
def parse_headline
-
4742
idx = @buffer.index("\n")
-
4742
return unless idx
-
-
4742
(m = %r{\AHTTP(?:/(\d+\.\d+))?\s+(\d\d\d)(?:\s+(.*))?}in.match(@buffer)) ||
-
raise(Error, "wrong head line format")
-
4734
version, code, _ = m.captures
-
4734
raise(Error, "unsupported HTTP version (HTTP/#{version})") unless version && VERSIONS.include?(version)
-
-
4726
@http_version = version.split(".").map(&:to_i)
-
4726
@status_code = code.to_i
-
4726
raise(Error, "wrong status code (#{@status_code})") unless (100..599).cover?(@status_code)
-
-
4718
@buffer = @buffer.byteslice((idx + 1)..-1)
-
4718
nextstate(:headers)
-
end
-
-
26
def parse_headers
-
4832
headers = @headers
-
4832
buffer = @buffer
-
-
37300
while (idx = buffer.index("\n"))
-
# @type var line: String
-
36743
line = buffer.byteslice(0..idx)
-
36743
raise Error, "wrong header format" if line.start_with?("\s", "\t")
-
-
36735
line.lstrip!
-
36735
buffer = @buffer = buffer.byteslice((idx + 1)..-1)
-
36735
if line.empty?
-
4228
case @state
-
when :headers
-
4702
prepare_data(headers)
-
4702
@observer.on_headers(headers)
-
4079
return unless @state == :headers
-
-
# state might have been reset
-
# in the :headers callback
-
4007
nextstate(:data)
-
4007
headers.clear
-
when :trailers
-
16
@observer.on_trailers(headers)
-
16
headers.clear
-
16
nextstate(:complete)
-
end
-
4015
return
-
end
-
32017
separator_index = line.index(":")
-
32017
raise Error, "wrong header format" unless separator_index
-
-
# @type var key: String
-
32009
key = line.byteslice(0..(separator_index - 1))
-
-
32009
key.rstrip! # was lstripped previously!
-
# @type var value: String
-
32009
value = line.byteslice((separator_index + 1)..-1)
-
32009
value.strip!
-
32009
raise Error, "wrong header format" if value.nil?
-
-
32009
(headers[key.downcase] ||= []) << value
-
end
-
end
-
-
26
def parse_data
-
5289
if @buffer.respond_to?(:each)
-
197
@buffer.each do |chunk|
-
234
@observer.on_data(chunk)
-
end
-
5091
elsif @content_length
-
# @type var data: String
-
5060
data = @buffer.byteslice(0, @content_length)
-
5060
@buffer = @buffer.byteslice(@content_length..-1) || "".b
-
4516
@content_length -= data.bytesize
-
5060
@observer.on_data(data)
-
5046
data.clear
-
else
-
32
@observer.on_data(@buffer)
-
32
@buffer.clear
-
end
-
5267
return unless no_more_data?
-
-
3873
@buffer = @buffer.to_s
-
3873
if @_has_trailers
-
16
nextstate(:trailers)
-
else
-
3857
nextstate(:complete)
-
end
-
end
-
-
26
def prepare_data(headers)
-
4702
@upgrade = headers.key?("upgrade")
-
-
4702
@_has_trailers = headers.key?("trailer")
-
-
4702
if (tr_encodings = headers["transfer-encoding"])
-
114
tr_encodings.reverse_each do |tr_encoding|
-
114
tr_encoding.split(/ *, */).each do |encoding|
-
100
case encoding
-
when "chunked"
-
114
@buffer = Transcoder::Chunker::Decoder.new(@buffer, @_has_trailers)
-
end
-
end
-
end
-
else
-
4588
@content_length = headers["content-length"][0].to_i if headers.key?("content-length")
-
end
-
end
-
-
26
def no_more_data?
-
5267
if @content_length
-
5046
@content_length <= 0
-
220
elsif @buffer.respond_to?(:finished?)
-
189
@buffer.finished?
-
else
-
32
false
-
end
-
end
-
-
26
def nextstate(state)
-
12614
@state = state
-
11310
case state
-
when :headers
-
4718
@observer.on_start
-
when :complete
-
3873
@observer.on_complete
-
576
reset!
-
576
nextstate(:idle) unless @buffer.empty?
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
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
-
#
-
8
module Auth
-
8
module InstanceMethods
-
8
def authorization(token)
-
144
with(headers: { "authorization" => token })
-
end
-
-
8
def bearer_auth(token)
-
16
authorization("Bearer #{token}")
-
end
-
end
-
end
-
8
register_plugin :auth, Auth
-
end
-
end
-
# frozen_string_literal: true
-
-
9
require "httpx/base64"
-
-
9
module HTTPX
-
9
module Plugins
-
9
module Authentication
-
9
class Basic
-
9
def initialize(user, password, **)
-
274
@user = user
-
274
@password = password
-
end
-
-
9
def authenticate(*)
-
255
"Basic #{Base64.strict_encode64("#{@user}:#{@password}")}"
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
8
require "time"
-
8
require "securerandom"
-
8
require "digest"
-
-
8
module HTTPX
-
8
module Plugins
-
8
module Authentication
-
8
class Digest
-
8
def initialize(user, password, hashed: false, **)
-
176
@user = user
-
176
@password = password
-
176
@nonce = 0
-
176
@hashed = hashed
-
end
-
-
8
def can_authenticate?(authenticate)
-
160
authenticate && /Digest .*/.match?(authenticate)
-
end
-
-
8
def authenticate(request, authenticate)
-
160
"Digest #{generate_header(request.verb, request.path, authenticate)}"
-
end
-
-
8
private
-
-
8
def generate_header(meth, uri, authenticate)
-
# discard first token, it's Digest
-
160
auth_info = authenticate[/^(\w+) (.*)/, 2]
-
-
160
params = auth_info.split(/ *, */)
-
832
.to_h { |val| val.split("=", 2) }
-
832
.transform_values { |v| v.delete("\"") }
-
160
nonce = params["nonce"]
-
160
nc = next_nonce
-
-
# verify qop
-
160
qop = params["qop"]
-
-
160
if params["algorithm"] =~ /(.*?)(-sess)?$/
-
144
alg = Regexp.last_match(1)
-
144
algorithm = ::Digest.const_get(alg)
-
144
raise DigestError, "unknown algorithm \"#{alg}\"" unless algorithm
-
-
144
sess = Regexp.last_match(2)
-
else
-
16
algorithm = ::Digest::MD5
-
end
-
-
160
if qop || sess
-
160
cnonce = make_cnonce
-
160
nc = format("%<nonce>08x", nonce: nc)
-
end
-
-
160
a1 = if sess
-
4
[
-
32
(@hashed ? @password : algorithm.hexdigest("#{@user}:#{params["realm"]}:#{@password}")),
-
nonce,
-
cnonce,
-
3
].join ":"
-
else
-
128
@hashed ? @password : "#{@user}:#{params["realm"]}:#{@password}"
-
end
-
-
160
ha1 = algorithm.hexdigest(a1)
-
160
ha2 = algorithm.hexdigest("#{meth}:#{uri}")
-
160
request_digest = [ha1, nonce]
-
160
request_digest.push(nc, cnonce, qop) if qop
-
160
request_digest << ha2
-
160
request_digest = request_digest.join(":")
-
-
40
header = [
-
140
%(username="#{@user}"),
-
20
%(nonce="#{nonce}"),
-
20
%(uri="#{uri}"),
-
20
%(response="#{algorithm.hexdigest(request_digest)}"),
-
]
-
160
header << %(realm="#{params["realm"]}") if params.key?("realm")
-
160
header << %(algorithm=#{params["algorithm"]}) if params.key?("algorithm")
-
160
header << %(cnonce="#{cnonce}") if cnonce
-
160
header << %(nc=#{nc})
-
160
header << %(qop=#{qop}) if qop
-
160
header << %(opaque="#{params["opaque"]}") if params.key?("opaque")
-
160
header.join ", "
-
end
-
-
8
def make_cnonce
-
180
::Digest::MD5.hexdigest [
-
Time.now.to_i,
-
Process.pid,
-
SecureRandom.random_number(2**32),
-
].join ":"
-
end
-
-
8
def next_nonce
-
140
@nonce += 1
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
require "httpx/base64"
-
6
require "ntlm"
-
-
6
module HTTPX
-
6
module Plugins
-
6
module Authentication
-
6
class Ntlm
-
6
def initialize(user, password, domain: nil)
-
4
@user = user
-
4
@password = password
-
4
@domain = domain
-
end
-
-
6
def can_authenticate?(authenticate)
-
2
authenticate && /NTLM .*/.match?(authenticate)
-
end
-
-
6
def negotiate
-
4
"NTLM #{NTLM.negotiate(domain: @domain).to_base64}"
-
end
-
-
6
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
-
-
10
module HTTPX
-
10
module Plugins
-
10
module Authentication
-
10
class Socks5
-
10
def initialize(user, password, **)
-
48
@user = user
-
48
@password = password
-
end
-
-
10
def can_authenticate?(*)
-
48
@user && @password
-
end
-
-
10
def authenticate(*)
-
48
[0x01, @user.bytesize, @user, @password.bytesize, @password].pack("CCA*CA*")
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
module Plugins
-
#
-
# This plugin applies AWS Sigv4 to requests, using the AWS SDK credentials and configuration.
-
#
-
# It requires the "aws-sdk-core" gem.
-
#
-
8
module AwsSdkAuthentication
-
# Mock configuration, to be used only when resolving credentials
-
8
class Configuration
-
8
attr_reader :profile
-
-
8
def initialize(profile)
-
32
@profile = profile
-
end
-
-
8
def respond_to_missing?(*)
-
16
true
-
end
-
-
8
def method_missing(*); end
-
end
-
-
#
-
# encapsulates access to an AWS SDK credentials store.
-
#
-
8
class Credentials
-
8
def initialize(aws_credentials)
-
16
@aws_credentials = aws_credentials
-
end
-
-
8
def username
-
16
@aws_credentials.access_key_id
-
end
-
-
8
def password
-
16
@aws_credentials.secret_access_key
-
end
-
-
8
def security_token
-
16
@aws_credentials.session_token
-
end
-
end
-
-
8
class << self
-
8
def load_dependencies(_klass)
-
16
require "aws-sdk-core"
-
end
-
-
8
def configure(klass)
-
16
klass.plugin(:aws_sigv4)
-
end
-
-
8
def extra_options(options)
-
16
options.merge(max_concurrent_requests: 1)
-
end
-
-
8
def credentials(profile)
-
16
mock_configuration = Configuration.new(profile)
-
16
Credentials.new(Aws::CredentialProviderChain.new(mock_configuration).resolve)
-
end
-
-
8
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
-
16
keys = %w[AWS_REGION AMAZON_REGION AWS_DEFAULT_REGION]
-
16
env_region = ENV.values_at(*keys).compact.first
-
16
env_region = nil if env_region == ""
-
16
cfg_region = Aws.shared_config.region(profile: profile)
-
16
env_region || cfg_region
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :aws_profile :: AWS account profile to retrieve credentials from.
-
8
module OptionsMethods
-
8
def option_aws_profile(value)
-
80
String(value)
-
end
-
end
-
-
8
module InstanceMethods
-
#
-
# aws_authentication
-
# aws_authentication(credentials: Aws::Credentials.new('akid', 'secret'))
-
# aws_authentication()
-
#
-
8
def aws_sdk_authentication(
-
credentials: AwsSdkAuthentication.credentials(@options.aws_profile),
-
region: AwsSdkAuthentication.region(@options.aws_profile),
-
**options
-
)
-
-
16
aws_sigv4_authentication(
-
credentials: credentials,
-
region: region,
-
provider_prefix: "aws",
-
header_provider_field: "amz",
-
**options
-
)
-
end
-
8
alias_method :aws_auth, :aws_sdk_authentication
-
end
-
end
-
8
register_plugin :aws_sdk_authentication, AwsSdkAuthentication
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
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
-
#
-
8
module AWSSigV4
-
8
Credentials = Struct.new(:username, :password, :security_token)
-
-
# Signs requests using the AWS sigv4 signing.
-
8
class Signer
-
8
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"
-
)
-
152
@credentials = credentials || Credentials.new(username, password, security_token)
-
152
@service = service
-
152
@region = region
-
-
152
@unsigned_headers = Set.new(unsigned_headers.map(&:downcase))
-
152
@unsigned_headers << "authorization"
-
152
@unsigned_headers << "x-amzn-trace-id"
-
152
@unsigned_headers << "expect"
-
-
152
@apply_checksum_header = apply_checksum_header
-
152
@provider_prefix = provider_prefix
-
152
@header_provider_field = header_provider_field
-
-
152
@algorithm = algorithm
-
end
-
-
8
def sign!(request)
-
152
lower_provider_prefix = "#{@provider_prefix}4"
-
152
upper_provider_prefix = lower_provider_prefix.upcase
-
-
152
downcased_algorithm = @algorithm.downcase
-
-
152
datetime = (request.headers["x-#{@header_provider_field}-date"] ||= Time.now.utc.strftime("%Y%m%dT%H%M%SZ"))
-
152
date = datetime[0, 8]
-
-
152
content_hashed = request.headers["x-#{@header_provider_field}-content-#{downcased_algorithm}"] || hexdigest(request.body)
-
-
144
request.headers["x-#{@header_provider_field}-content-#{downcased_algorithm}"] ||= content_hashed if @apply_checksum_header
-
144
request.headers["x-#{@header_provider_field}-security-token"] ||= @credentials.security_token if @credentials.security_token
-
-
144
signature_headers = request.headers.each.reject do |k, _|
-
984
@unsigned_headers.include?(k)
-
end
-
# aws sigv4 needs to declare the host, regardless of protocol version
-
144
signature_headers << ["host", request.authority] unless request.headers.key?("host")
-
144
signature_headers.sort_by!(&:first)
-
-
144
signed_headers = signature_headers.map(&:first).join(";")
-
-
144
canonical_headers = signature_headers.map do |k, v|
-
# eliminate whitespace between value fields, unless it's a quoted value
-
847
"#{k}:#{v.start_with?("\"") && v.end_with?("\"") ? v : v.gsub(/\s+/, " ").strip}\n"
-
end.join
-
-
# canonical request
-
144
creq = "#{request.verb}" \
-
18
"\n#{request.canonical_path}" \
-
18
"\n#{request.canonical_query}" \
-
18
"\n#{canonical_headers}" \
-
18
"\n#{signed_headers}" \
-
18
"\n#{content_hashed}"
-
-
144
credential_scope = "#{date}" \
-
18
"/#{@region}" \
-
18
"/#{@service}" \
-
18
"/#{lower_provider_prefix}_request"
-
-
144
algo_line = "#{upper_provider_prefix}-HMAC-#{@algorithm}"
-
# string to sign
-
144
sts = "#{algo_line}" \
-
18
"\n#{datetime}" \
-
18
"\n#{credential_scope}" \
-
18
"\n#{OpenSSL::Digest.new(@algorithm).hexdigest(creq)}"
-
-
# signature
-
144
k_date = hmac("#{upper_provider_prefix}#{@credentials.password}", date)
-
144
k_region = hmac(k_date, @region)
-
144
k_service = hmac(k_region, @service)
-
144
k_credentials = hmac(k_service, "#{lower_provider_prefix}_request")
-
144
sig = hexhmac(k_credentials, sts)
-
-
144
credential = "#{@credentials.username}/#{credential_scope}"
-
# apply signature
-
126
request.headers["authorization"] =
-
18
"#{algo_line} " \
-
18
"Credential=#{credential}, " \
-
18
"SignedHeaders=#{signed_headers}, " \
-
18
"Signature=#{sig}"
-
end
-
-
8
private
-
-
8
def hexdigest(value)
-
144
digest = OpenSSL::Digest.new(@algorithm)
-
-
144
if value.respond_to?(:read)
-
32
if value.respond_to?(:to_path)
-
# files, pathnames
-
8
digest.file(value.to_path).hexdigest
-
else
-
# gzipped request bodies
-
24
raise Error, "request body must be rewindable" unless value.respond_to?(:rewind)
-
-
24
buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
2
begin
-
24
IO.copy_stream(value, buffer)
-
24
buffer.flush
-
-
24
digest.file(buffer.to_path).hexdigest
-
ensure
-
24
value.rewind
-
24
buffer.close
-
24
buffer.unlink
-
end
-
end
-
else
-
# error on endless generators
-
112
raise Error, "hexdigest for endless enumerators is not supported" if value.unbounded_body?
-
-
104
mb_buffer = value.each.with_object("".b) do |chunk, b|
-
56
b << chunk
-
56
break if b.bytesize >= 1024 * 1024
-
end
-
-
104
digest.hexdigest(mb_buffer)
-
end
-
end
-
-
8
def hmac(key, value)
-
576
OpenSSL::HMAC.digest(OpenSSL::Digest.new(@algorithm), key, value)
-
end
-
-
8
def hexhmac(key, value)
-
144
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new(@algorithm), key, value)
-
end
-
end
-
-
8
class << self
-
8
def load_dependencies(*)
-
152
require "set"
-
152
require "digest/sha2"
-
end
-
-
8
def configure(klass)
-
152
klass.plugin(:expect)
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :sigv4_signer :: instance of HTTPX::Plugins::AWSSigV4 used to sign requests.
-
8
module OptionsMethods
-
8
def option_sigv4_signer(value)
-
320
value.is_a?(Signer) ? value : Signer.new(value)
-
end
-
end
-
-
8
module InstanceMethods
-
8
def aws_sigv4_authentication(**options)
-
152
with(sigv4_signer: Signer.new(**options))
-
end
-
-
8
def build_request(*)
-
152
request = super
-
-
152
return request if request.headers.key?("authorization")
-
-
152
signer = request.options.sigv4_signer
-
-
152
return request unless signer
-
-
152
signer.sign!(request)
-
-
144
request
-
end
-
end
-
-
8
module RequestMethods
-
8
def canonical_path
-
144
path = uri.path.dup
-
144
path << "/" if path.empty?
-
176
path.gsub(%r{[^/]+}) { |part| CGI.escape(part.encode("UTF-8")).gsub("+", "%20").gsub("%7E", "~") }
-
end
-
-
8
def canonical_query
-
176
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
-
176
params.each.with_index.sort do |a, b|
-
64
a, a_offset = a
-
64
b, b_offset = b
-
64
a_name, a_value = a.split("=", 2)
-
64
b_name, b_value = b.split("=", 2)
-
64
if a_name == b_name
-
32
if a_value == b_value
-
16
a_offset <=> b_offset
-
else
-
16
a_value <=> b_value
-
end
-
else
-
32
a_name <=> b_name
-
end
-
end.map(&:first).join("&")
-
end
-
end
-
end
-
8
register_plugin :aws_sigv4, AWSSigV4
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
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
-
#
-
8
module BasicAuth
-
8
class << self
-
8
def load_dependencies(_klass)
-
112
require_relative "auth/basic"
-
end
-
-
8
def configure(klass)
-
112
klass.plugin(:auth)
-
end
-
end
-
-
8
module InstanceMethods
-
8
def basic_auth(user, password)
-
128
authorization(Authentication::Basic.new(user, password).authenticate)
-
end
-
end
-
end
-
8
register_plugin :basic_auth, BasicAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
6
module Brotli
-
6
class Deflater < Transcoder::Deflater
-
6
def deflate(chunk)
-
24
return unless chunk
-
-
12
::Brotli.deflate(chunk)
-
end
-
end
-
-
6
module RequestBodyClassMethods
-
6
def initialize_deflater_body(body, encoding)
-
24
return Brotli.encode(body) if encoding == "br"
-
-
12
super
-
end
-
end
-
-
6
module ResponseBodyClassMethods
-
6
def initialize_inflater_by_encoding(encoding, response, **kwargs)
-
24
return Brotli.decode(response, **kwargs) if encoding == "br"
-
-
12
super
-
end
-
end
-
-
6
module_function
-
-
6
def load_dependencies(*)
-
24
require "brotli"
-
end
-
-
6
def self.extra_options(options)
-
24
options.merge(supported_compression_formats: %w[br] + options.supported_compression_formats)
-
end
-
-
6
def encode(body)
-
12
Deflater.new(body)
-
end
-
-
6
def decode(_response, **)
-
12
::Brotli.method(:inflate)
-
end
-
end
-
6
register_plugin :brotli, Brotli
-
end
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
26
module Plugins
-
#
-
# This plugin adds suppoort for callbacks around the request/response lifecycle.
-
#
-
# https://gitlab.com/os85/httpx/-/wikis/Events
-
#
-
26
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.
-
26
class CallbackError < Exception; end # rubocop:disable Lint/InheritException
-
-
26
module InstanceMethods
-
26
include HTTPX::Callbacks
-
-
26
%i[
-
connection_opened connection_closed
-
request_error
-
request_started request_body_chunk request_completed
-
response_started response_body_chunk response_completed
-
].each do |meth|
-
234
class_eval(<<-MOD, __FILE__, __LINE__ + 1)
-
9
def on_#{meth}(&blk) # def on_connection_opened(&blk)
-
9
on(:#{meth}, &blk) # on(:connection_opened, &blk)
-
end # end
-
MOD
-
end
-
-
26
private
-
-
26
def do_init_connection(connection, selector)
-
209
super
-
209
connection.on(:open) do
-
195
next unless connection.current_session == self
-
-
195
emit_or_callback_error(:connection_opened, connection.origin, connection.io.socket)
-
end
-
209
connection.on(:close) do
-
186
next unless connection.current_session == self
-
-
186
emit_or_callback_error(:connection_closed, connection.origin) if connection.used?
-
end
-
-
209
connection
-
end
-
-
26
def set_request_callbacks(request)
-
211
super
-
-
211
request.on(:headers) do
-
179
emit_or_callback_error(:request_started, request)
-
end
-
211
request.on(:body_chunk) do |chunk|
-
16
emit_or_callback_error(:request_body_chunk, request, chunk)
-
end
-
211
request.on(:done) do
-
163
emit_or_callback_error(:request_completed, request)
-
end
-
-
211
request.on(:response_started) do |res|
-
163
if res.is_a?(Response)
-
147
emit_or_callback_error(:response_started, request, res)
-
131
res.on(:chunk_received) do |chunk|
-
152
emit_or_callback_error(:response_body_chunk, request, res, chunk)
-
end
-
else
-
16
emit_or_callback_error(:request_error, request, res.error)
-
end
-
end
-
211
request.on(:response) do |res|
-
131
emit_or_callback_error(:response_completed, request, res)
-
end
-
end
-
-
26
def emit_or_callback_error(*args)
-
1169
emit(*args)
-
rescue StandardError => e
-
112
ex = CallbackError.new(e.message)
-
112
ex.set_backtrace(e.backtrace)
-
112
raise ex
-
end
-
-
26
def receive_requests(*)
-
211
super
-
rescue CallbackError => e
-
104
raise e.cause
-
end
-
-
26
def close(*)
-
209
super
-
rescue CallbackError => e
-
8
raise e.cause
-
end
-
end
-
end
-
26
register_plugin :callbacks, Callbacks
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
module Plugins
-
#
-
# This plugin implements a circuit breaker around connection errors.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Circuit-Breaker
-
#
-
8
module CircuitBreaker
-
8
using URIExtensions
-
-
8
def self.load_dependencies(*)
-
56
require_relative "circuit_breaker/circuit"
-
56
require_relative "circuit_breaker/circuit_store"
-
end
-
-
8
def self.extra_options(options)
-
56
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
-
-
8
module InstanceMethods
-
8
include HTTPX::Callbacks
-
-
8
def initialize(*)
-
56
super
-
56
@circuit_store = CircuitStore.new(@options)
-
end
-
-
8
%i[circuit_open].each do |meth|
-
8
class_eval(<<-MOD, __FILE__, __LINE__ + 1)
-
1
def on_#{meth}(&blk) # def on_circuit_open(&blk)
-
1
on(:#{meth}, &blk) # on(:circuit_open, &blk)
-
end # end
-
MOD
-
end
-
-
8
private
-
-
8
def send_requests(*requests)
-
# @type var short_circuit_responses: Array[response]
-
224
short_circuit_responses = []
-
-
# run all requests through the circuit breaker, see if the circuit is
-
# open for any of them.
-
224
real_requests = requests.each_with_index.with_object([]) do |(req, idx), real_reqs|
-
224
short_circuit_response = @circuit_store.try_respond(req)
-
224
if short_circuit_response.nil?
-
176
real_reqs << req
-
176
next
-
end
-
42
short_circuit_responses[idx] = short_circuit_response
-
end
-
-
# run requests for the remainder
-
224
unless real_requests.empty?
-
176
responses = super(*real_requests)
-
-
176
real_requests.each_with_index do |request, idx|
-
154
short_circuit_responses[requests.index(request)] = responses[idx]
-
end
-
end
-
-
224
short_circuit_responses
-
end
-
-
8
def on_response(request, response)
-
176
emit(:circuit_open, request) if try_circuit_open(request, response)
-
-
176
super
-
end
-
-
8
def try_circuit_open(request, response)
-
176
if response.is_a?(ErrorResponse)
-
112
case response.error
-
when RequestTimeoutError
-
80
@circuit_store.try_open(request.uri, response)
-
else
-
48
@circuit_store.try_open(request.origin, response)
-
end
-
48
elsif (break_on = request.options.circuit_breaker_break_on) && break_on.call(response)
-
16
@circuit_store.try_open(request.uri, response)
-
else
-
32
@circuit_store.try_close(request.uri)
-
12
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>).
-
8
module OptionsMethods
-
8
def option_circuit_breaker_max_attempts(value)
-
112
attempts = Integer(value)
-
112
raise TypeError, ":circuit_breaker_max_attempts must be positive" unless attempts.positive?
-
-
112
attempts
-
end
-
-
8
def option_circuit_breaker_reset_attempts_in(value)
-
64
timeout = Float(value)
-
64
raise TypeError, ":circuit_breaker_reset_attempts_in must be positive" unless timeout.positive?
-
-
64
timeout
-
end
-
-
8
def option_circuit_breaker_break_in(value)
-
88
timeout = Float(value)
-
88
raise TypeError, ":circuit_breaker_break_in must be positive" unless timeout.positive?
-
-
88
timeout
-
end
-
-
8
def option_circuit_breaker_half_open_drip_rate(value)
-
88
ratio = Float(value)
-
88
raise TypeError, ":circuit_breaker_half_open_drip_rate must be a number between 0 and 1" unless (0..1).cover?(ratio)
-
-
88
ratio
-
end
-
-
8
def option_circuit_breaker_break_on(value)
-
16
raise TypeError, ":circuit_breaker_break_on must be called with the response" unless value.respond_to?(:call)
-
-
16
value
-
end
-
end
-
end
-
8
register_plugin :circuit_breaker, CircuitBreaker
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
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.
-
#
-
8
class Circuit
-
8
def initialize(max_attempts, reset_attempts_in, break_in, circuit_breaker_half_open_drip_rate)
-
56
@max_attempts = max_attempts
-
56
@reset_attempts_in = reset_attempts_in
-
56
@break_in = break_in
-
56
@circuit_breaker_half_open_drip_rate = circuit_breaker_half_open_drip_rate
-
56
@attempts = 0
-
-
56
total_real_attempts = @max_attempts * @circuit_breaker_half_open_drip_rate
-
56
@drip_factor = (@max_attempts / total_real_attempts).round
-
56
@state = :closed
-
end
-
-
8
def respond
-
224
try_close
-
-
196
case @state
-
when :closed
-
51
nil
-
when :half_open
-
49
@attempts += 1
-
-
# do real requests while drip rate valid
-
56
if (@real_attempts % @drip_factor).zero?
-
35
@real_attempts += 1
-
35
return
-
end
-
-
16
@response
-
when :open
-
-
32
@response
-
end
-
end
-
-
8
def try_open(response)
-
126
case @state
-
when :closed
-
120
now = Utils.now
-
-
120
if @attempts.positive?
-
# reset if error happened long ago
-
48
@attempts = 0 if now - @attempted_at > @reset_attempts_in
-
else
-
72
@attempted_at = now
-
end
-
-
105
@attempts += 1
-
-
120
return unless @attempts >= @max_attempts
-
-
64
@state = :open
-
64
@opened_at = now
-
64
@response = response
-
when :half_open
-
# open immediately
-
-
24
@state = :open
-
24
@attempted_at = @opened_at = Utils.now
-
24
@response = response
-
end
-
end
-
-
8
def try_close
-
224
case @state
-
when :closed
-
51
nil
-
when :half_open
-
-
# do not close circuit unless attempts exhausted
-
48
return unless @attempts >= @max_attempts
-
-
# reset!
-
16
@attempts = 0
-
16
@opened_at = @attempted_at = @response = nil
-
16
@state = :closed
-
-
when :open
-
72
if Utils.elapsed_time(@opened_at) > @break_in
-
40
@state = :half_open
-
40
@attempts = 0
-
40
@real_attempts = 0
-
end
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX::Plugins::CircuitBreaker
-
8
using HTTPX::URIExtensions
-
-
8
class CircuitStore
-
8
def initialize(options)
-
56
@circuits = Hash.new do |h, k|
-
49
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
-
56
@circuits_mutex = Thread::Mutex.new
-
end
-
-
8
def try_open(uri, response)
-
288
circuit = @circuits_mutex.synchronize { get_circuit_for_uri(uri) }
-
-
144
circuit.try_open(response)
-
end
-
-
8
def try_close(uri)
-
32
circuit = @circuits_mutex.synchronize do
-
32
return unless @circuits.key?(uri.origin) || @circuits.key?(uri.to_s)
-
-
32
get_circuit_for_uri(uri)
-
end
-
-
32
circuit.try_close
-
end
-
-
# if circuit is open, it'll respond with the stored response.
-
# if not, nil.
-
8
def try_respond(request)
-
448
circuit = @circuits_mutex.synchronize { get_circuit_for_uri(request.uri) }
-
-
224
circuit.respond
-
end
-
-
8
private
-
-
8
def get_circuit_for_uri(uri)
-
400
if uri.respond_to?(:origin) && @circuits.key?(uri.origin)
-
288
@circuits[uri.origin]
-
else
-
112
@circuits[uri.to_s]
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
module Plugins
-
#
-
# This plugin adds `Content-Digest` headers to requests
-
# and can validate these headers on responses
-
#
-
# https://datatracker.ietf.org/doc/html/rfc9530
-
#
-
8
module ContentDigest
-
8
class Error < HTTPX::Error; end
-
-
# Error raised on response "content-digest" header validation.
-
8
class ValidationError < Error
-
8
attr_reader :response
-
-
8
def initialize(message, response)
-
48
super(message)
-
48
@response = response
-
end
-
end
-
-
8
class MissingContentDigestError < ValidationError; end
-
8
class InvalidContentDigestError < ValidationError; end
-
-
2
SUPPORTED_ALGORITHMS = {
-
6
"sha-256" => OpenSSL::Digest::SHA256,
-
"sha-512" => OpenSSL::Digest::SHA512,
-
}.freeze
-
-
8
class << self
-
8
def extra_options(options)
-
208
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>)
-
8
module OptionsMethods
-
8
def option_content_digest_algorithm(value)
-
216
raise TypeError, ":content_digest_algorithm must be one of 'sha-256', 'sha-512'" unless SUPPORTED_ALGORITHMS.key?(value)
-
-
216
value
-
end
-
-
8
def option_encode_content_digest(value)
-
208
value
-
end
-
-
8
def option_validate_content_digest(value)
-
144
value
-
end
-
end
-
-
8
module ResponseBodyMethods
-
8
attr_reader :content_digest_buffer
-
-
8
def initialize(response, options)
-
176
super
-
-
176
return unless response.headers.key?("content-digest")
-
-
128
should_validate = options.validate_content_digest
-
128
should_validate = should_validate.call(response) if should_validate.respond_to?(:call)
-
-
128
return unless should_validate
-
-
112
@content_digest_buffer = Response::Buffer.new(
-
threshold_size: @options.body_threshold_size,
-
bytesize: @length,
-
encoding: @encoding
-
)
-
end
-
-
8
def write(chunk)
-
289
@content_digest_buffer.write(chunk) if @content_digest_buffer
-
289
super
-
end
-
-
8
def close
-
112
if @content_digest_buffer
-
112
@content_digest_buffer.close
-
112
@content_digest_buffer = nil
-
end
-
112
super
-
end
-
end
-
-
8
module InstanceMethods
-
8
def build_request(*)
-
224
request = super
-
-
224
return request if request.empty?
-
-
48
return request if request.headers.key?("content-digest")
-
-
48
perform_encoding = @options.encode_content_digest
-
48
perform_encoding = perform_encoding.call(request) if perform_encoding.respond_to?(:call)
-
-
48
return request unless perform_encoding
-
-
40
digest = base64digest(request.body)
-
40
request.headers.add("content-digest", "#{@options.content_digest_algorithm}=:#{digest}:")
-
-
40
request
-
end
-
-
8
private
-
-
8
def fetch_response(request, _, _)
-
576
response = super
-
576
return response unless response.is_a?(Response)
-
-
176
perform_validation = @options.validate_content_digest
-
176
perform_validation = perform_validation.call(response) if perform_validation.respond_to?(:call)
-
-
176
validate_content_digest(response) if perform_validation
-
-
128
response
-
rescue ValidationError => e
-
48
ErrorResponse.new(request, e)
-
end
-
-
8
def validate_content_digest(response)
-
128
content_digest_header = response.headers["content-digest"]
-
-
128
raise MissingContentDigestError.new("response is missing a `content-digest` header", response) unless content_digest_header
-
-
112
digests = extract_content_digests(content_digest_header)
-
-
112
included_algorithms = SUPPORTED_ALGORITHMS.keys & digests.keys
-
-
112
raise MissingContentDigestError.new("unsupported algorithms: #{digests.keys.join(", ")}", response) if included_algorithms.empty?
-
-
112
content_buffer = response.body.content_digest_buffer
-
-
112
included_algorithms.each do |algorithm|
-
112
digest = SUPPORTED_ALGORITHMS.fetch(algorithm).new
-
112
digest_received = digests[algorithm]
-
14
digest_computed =
-
111
if content_buffer.respond_to?(:to_path)
-
16
content_buffer.flush
-
16
digest.file(content_buffer.to_path).base64digest
-
else
-
96
digest.base64digest(content_buffer.to_s)
-
end
-
-
4
raise InvalidContentDigestError.new("#{algorithm} digest does not match content",
-
111
response) unless digest_received == digest_computed
-
end
-
end
-
-
8
def extract_content_digests(header)
-
112
header.split(",").to_h do |entry|
-
128
algorithm, digest = entry.split("=", 2)
-
128
raise Error, "#{entry} is an invalid digest format" unless algorithm && digest
-
-
128
[algorithm, digest.byteslice(1..-2)]
-
end
-
end
-
-
8
def base64digest(body)
-
40
digest = SUPPORTED_ALGORITHMS.fetch(@options.content_digest_algorithm).new
-
-
40
if body.respond_to?(:read)
-
32
if body.respond_to?(:to_path)
-
8
digest.file(body.to_path).base64digest
-
else
-
24
raise ContentDigestError, "request body must be rewindable" unless body.respond_to?(:rewind)
-
-
24
buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
2
begin
-
23
IO.copy_stream(body, buffer)
-
24
buffer.flush
-
-
24
digest.file(buffer.to_path).base64digest
-
ensure
-
24
body.rewind
-
24
buffer.close
-
24
buffer.unlink
-
end
-
end
-
else
-
8
raise ContentDigestError, "base64digest for endless enumerators is not supported" if body.unbounded_body?
-
-
8
buffer = "".b
-
16
body.each { |chunk| buffer << chunk }
-
-
8
digest.base64digest(buffer)
-
end
-
end
-
end
-
end
-
8
register_plugin :content_digest, ContentDigest
-
end
-
end
-
# frozen_string_literal: true
-
-
8
require "forwardable"
-
-
8
module HTTPX
-
8
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
-
#
-
8
module Cookies
-
8
def self.load_dependencies(*)
-
144
require "httpx/plugins/cookies/jar"
-
144
require "httpx/plugins/cookies/cookie"
-
144
require "httpx/plugins/cookies/set_cookie_parser"
-
end
-
-
8
module InstanceMethods
-
8
extend Forwardable
-
-
8
def_delegator :@options, :cookies
-
-
8
def initialize(options = {}, &blk)
-
288
super({ cookies: Jar.new }.merge(options), &blk)
-
end
-
-
8
def wrap
-
16
return super unless block_given?
-
-
16
super do |session|
-
16
old_cookies_jar = @options.cookies.dup
-
1
begin
-
16
yield session
-
ensure
-
16
@options = @options.merge(cookies: old_cookies_jar)
-
end
-
end
-
end
-
-
8
def build_request(*)
-
320
request = super
-
320
request.headers.set_cookie(request.options.cookies[request.uri])
-
320
request
-
end
-
-
8
private
-
-
8
def on_response(_request, response)
-
320
if response && response.respond_to?(:headers) && (set_cookie = response.headers["set-cookie"])
-
-
64
log { "cookies: set-cookie is over #{Cookie::MAX_LENGTH}" } if set_cookie.bytesize > Cookie::MAX_LENGTH
-
-
64
@options.cookies.parse(set_cookie)
-
end
-
-
320
super
-
end
-
end
-
-
8
module HeadersMethods
-
8
def set_cookie(cookies)
-
320
return if cookies.empty?
-
-
272
header_value = cookies.sort.join("; ")
-
-
272
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)
-
8
module OptionsMethods
-
8
def option_headers(*)
-
320
value = super
-
-
320
merge_cookie_in_jar(value.delete("cookie"), @cookies) if defined?(@cookies) && value.key?("cookie")
-
-
320
value
-
end
-
-
8
def option_cookies(value)
-
480
jar = value.is_a?(Jar) ? value : Jar.new(value)
-
-
480
merge_cookie_in_jar(@headers.delete("cookie"), jar) if defined?(@headers) && @headers.key?("cookie")
-
-
480
jar
-
end
-
-
8
private
-
-
8
def merge_cookie_in_jar(cookies, jar)
-
16
cookies.each do |ck|
-
16
ck.split(/ *; */).each do |cookie|
-
32
name, value = cookie.split("=", 2)
-
32
jar.add(Cookie.new(name, value))
-
end
-
end
-
end
-
end
-
end
-
8
register_plugin :cookies, Cookies
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
module Plugins::Cookies
-
# The HTTP Cookie.
-
#
-
# Contains the single cookie info: name, value and attributes.
-
8
class Cookie
-
8
include Comparable
-
# Maximum number of bytes per cookie (RFC 6265 6.1 requires 4096 at
-
# least)
-
8
MAX_LENGTH = 4096
-
-
8
attr_reader :domain, :path, :name, :value, :created_at
-
-
8
def path=(path)
-
184
path = String(path)
-
184
@path = path.start_with?("/") ? path : "/"
-
end
-
-
# See #domain.
-
8
def domain=(domain)
-
40
domain = String(domain)
-
-
40
if domain.start_with?(".")
-
16
@for_domain = true
-
16
domain = domain[1..-1]
-
end
-
-
40
return if domain.empty?
-
-
40
@domain_name = DomainName.new(domain)
-
# RFC 6265 5.3 5.
-
40
@for_domain = false if @domain_name.domain.nil? # a public suffix or IP address
-
-
40
@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.
-
8
def <=>(other)
-
# RFC 6265 5.4
-
# Precedence: 1. longer path 2. older creation
-
695
(@name <=> other.name).nonzero? ||
-
60
(other.path.length <=> @path.length).nonzero? ||
-
35
(@created_at <=> other.created_at).nonzero? || 0
-
end
-
-
8
class << self
-
8
def new(cookie, *args)
-
504
return cookie if cookie.is_a?(self)
-
-
504
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
-
8
def path_match?(base_path, target_path)
-
1352
base_path.start_with?("/") || (return false)
-
# RFC 6265 5.1.4
-
1352
bsize = base_path.size
-
1352
tsize = target_path.size
-
1352
return bsize == 1 if tsize.zero? # treat empty target_path as "/"
-
1352
return false unless target_path.start_with?(base_path)
-
1344
return true if bsize == tsize || base_path.end_with?("/")
-
-
16
target_path[bsize] == "/"
-
end
-
end
-
-
8
def initialize(arg, *attrs)
-
504
@created_at = Time.now
-
-
504
if attrs.empty?
-
24
attr_hash = Hash.try_convert(arg)
-
else
-
480
@name = arg
-
480
@value, attr_hash = attrs
-
480
attr_hash = Hash.try_convert(attr_hash)
-
end
-
-
33
attr_hash.each do |key, val|
-
312
key = key.downcase.tr("-", "_").to_sym unless key.is_a?(Symbol)
-
-
273
case key
-
when :domain, :path
-
201
__send__(:"#{key}=", val)
-
else
-
88
instance_variable_set(:"@#{key}", val)
-
end
-
503
end if attr_hash
-
-
504
@path ||= "/"
-
504
raise ArgumentError, "name must be specified" if @name.nil?
-
-
504
@name = @name.to_s
-
end
-
-
8
def expires
-
760
@expires || (@created_at && @max_age ? @created_at + @max_age : nil)
-
end
-
-
8
def expired?(time = Time.now)
-
728
return false unless expires
-
-
32
expires <= time
-
end
-
-
# Returns a string for use in the Cookie header, i.e. `name=value`
-
# or `name="value"`.
-
8
def cookie_value
-
483
"#{@name}=#{Scanner.quote(@value.to_s)}"
-
end
-
8
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.
-
8
def valid_for_uri?(uri)
-
712
uri = URI(uri)
-
# RFC 6265 5.4
-
-
712
return false if @secure && uri.scheme != "https"
-
-
704
acceptable_from_uri?(uri) && Cookie.path_match?(@path, uri.path)
-
end
-
-
8
private
-
-
# Tests if it is OK to accept this cookie if it is sent from a given
-
# URI/URL, `uri`.
-
8
def acceptable_from_uri?(uri)
-
736
uri = URI(uri)
-
-
736
host = DomainName.new(uri.host)
-
-
# RFC 6265 5.3
-
736
if host.hostname == @domain
-
16
true
-
719
elsif @for_domain # !host-only-flag
-
32
host.cookie_domain?(@domain_name)
-
else
-
688
@domain.nil?
-
end
-
end
-
-
8
module Scanner
-
8
RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/.freeze
-
-
8
module_function
-
-
8
def quote(s)
-
552
return s unless s.match(RE_BAD_CHAR)
-
-
8
"\"#{s.gsub(/([\\"])/, "\\\\\\1")}\""
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
module Plugins::Cookies
-
# The Cookie Jar
-
#
-
# It holds a bunch of cookies.
-
8
class Jar
-
8
using URIExtensions
-
-
8
include Enumerable
-
-
8
def initialize_dup(orig)
-
216
super
-
216
@cookies = orig.instance_variable_get(:@cookies).dup
-
end
-
-
8
def initialize(cookies = nil)
-
536
@cookies = []
-
-
120
cookies.each do |elem|
-
176
cookie = case elem
-
when Cookie
-
16
elem
-
when Array
-
144
Cookie.new(*elem)
-
else
-
16
Cookie.new(elem)
-
end
-
-
176
@cookies << cookie
-
535
end if cookies
-
end
-
-
8
def parse(set_cookie)
-
144
SetCookieParser.call(set_cookie) do |name, value, attrs|
-
208
add(Cookie.new(name, value, attrs))
-
end
-
end
-
-
8
def add(cookie, path = nil)
-
456
c = cookie.dup
-
-
456
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.
-
864
@cookies.delete_if { |ck| ck.name == c.name && ck.domain == c.domain && ck.path == c.path }
-
-
456
@cookies << c
-
end
-
-
8
def [](uri)
-
472
each(uri).sort
-
end
-
-
8
def each(uri = nil, &blk)
-
1184
return enum_for(__method__, uri) unless blk
-
-
680
return @cookies.each(&blk) unless uri
-
-
472
uri = URI(uri)
-
-
472
now = Time.now
-
472
tpath = uri.path
-
-
472
@cookies.delete_if do |cookie|
-
728
if cookie.expired?(now)
-
16
true
-
else
-
712
yield cookie if cookie.valid_for_uri?(uri) && Cookie.path_match?(cookie.path, tpath)
-
712
false
-
end
-
end
-
end
-
-
8
def merge(other)
-
200
cookies_dup = dup
-
-
200
other.each do |elem|
-
216
cookie = case elem
-
when Cookie
-
200
elem
-
when Array
-
8
Cookie.new(*elem)
-
else
-
8
Cookie.new(elem)
-
end
-
-
216
cookies_dup.add(cookie)
-
end
-
-
200
cookies_dup
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
8
require "strscan"
-
8
require "time"
-
-
8
module HTTPX
-
8
module Plugins::Cookies
-
8
module SetCookieParser
-
# Whitespace.
-
8
RE_WSP = /[ \t]+/.freeze
-
-
# A pattern that matches a cookie name or attribute name which may
-
# be empty, capturing trailing whitespace.
-
8
RE_NAME = /(?!#{RE_WSP})[^,;\\"=]*/.freeze
-
-
8
RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/.freeze
-
-
# A pattern that matches the comma in a (typically date) value.
-
8
RE_COOKIE_COMMA = /,(?=#{RE_WSP}?#{RE_NAME}=)/.freeze
-
-
8
module_function
-
-
8
def scan_dquoted(scanner)
-
16
s = +""
-
-
22
until scanner.eos?
-
64
break if scanner.skip(/"/)
-
-
48
if scanner.skip(/\\/)
-
16
s << scanner.getch
-
31
elsif scanner.scan(/[^"\\]+/)
-
32
s << scanner.matched
-
end
-
end
-
-
16
s
-
end
-
-
8
def scan_value(scanner, comma_as_separator = false)
-
440
value = +""
-
-
498
until scanner.eos?
-
760
if scanner.scan(/[^,;"]+/)
-
432
value << scanner.matched
-
327
elsif scanner.skip(/"/)
-
# RFC 6265 2.2
-
# A cookie-value may be DQUOTE'd.
-
16
value << scan_dquoted(scanner)
-
311
elsif scanner.check(/;/)
-
232
break
-
79
elsif comma_as_separator && scanner.check(RE_COOKIE_COMMA)
-
64
break
-
else
-
16
value << scanner.getch
-
end
-
end
-
-
440
value.rstrip!
-
440
value
-
end
-
-
8
def scan_name_value(scanner, comma_as_separator = false)
-
440
name = scanner.scan(RE_NAME)
-
440
name.rstrip! if name
-
-
440
if scanner.skip(/=/)
-
432
value = scan_value(scanner, comma_as_separator)
-
else
-
8
scan_value(scanner, comma_as_separator)
-
8
value = nil
-
end
-
440
[name, value]
-
end
-
-
8
def call(set_cookie)
-
144
scanner = StringScanner.new(set_cookie)
-
-
# RFC 6265 4.1.1 & 5.2
-
170
until scanner.eos?
-
208
start = scanner.pos
-
208
len = nil
-
-
208
scanner.skip(RE_WSP)
-
-
208
name, value = scan_name_value(scanner, true)
-
208
value = nil if name.empty?
-
-
208
attrs = {}
-
-
237
until scanner.eos?
-
296
if scanner.skip(/,/)
-
# The comma is used as separator for concatenating multiple
-
# values of a header.
-
64
len = (scanner.pos - 1) - start
-
64
break
-
231
elsif scanner.skip(/;/)
-
232
scanner.skip(RE_WSP)
-
-
232
aname, avalue = scan_name_value(scanner, true)
-
-
232
next if aname.empty? || value.nil?
-
-
232
aname.downcase!
-
-
203
case aname
-
when "expires"
-
# RFC 6265 5.2.1
-
16
(avalue &&= Time.parse(avalue)) || next
-
when "max-age"
-
# RFC 6265 5.2.2
-
8
next unless /\A-?\d+\z/.match?(avalue)
-
-
8
avalue = Integer(avalue)
-
when "domain"
-
# RFC 6265 5.2.3
-
# An empty value SHOULD be ignored.
-
24
next if avalue.nil? || avalue.empty?
-
when "path"
-
# RFC 6265 5.2.4
-
# A relative path must be ignored rather than normalizing it
-
# to "/".
-
176
next unless avalue.start_with?("/")
-
when "secure", "httponly"
-
# RFC 6265 5.2.5, 5.2.6
-
7
avalue = true
-
end
-
203
attrs[aname] = avalue
-
end
-
end
-
-
208
len ||= scanner.pos - start
-
-
208
next if len > Cookie::MAX_LENGTH
-
-
208
yield(name, value, attrs) if name && !name.empty? && value
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
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
-
#
-
8
module DigestAuth
-
8
DigestError = Class.new(Error)
-
-
8
class << self
-
8
def extra_options(options)
-
160
options.merge(max_concurrent_requests: 1)
-
end
-
-
8
def load_dependencies(*)
-
160
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.
-
8
module OptionsMethods
-
8
def option_digest(value)
-
320
raise TypeError, ":digest must be a #{Authentication::Digest}" unless value.is_a?(Authentication::Digest)
-
-
320
value
-
end
-
end
-
-
8
module InstanceMethods
-
8
def digest_auth(user, password, hashed: false)
-
160
with(digest: Authentication::Digest.new(user, password, hashed: hashed))
-
end
-
-
8
private
-
-
8
def send_requests(*requests)
-
192
requests.flat_map do |request|
-
192
digest = request.options.digest
-
-
192
next super(request) unless digest
-
-
320
probe_response = wrap { super(request).first }
-
-
160
return probe_response unless probe_response.is_a?(Response)
-
-
160
if probe_response.status == 401 && digest.can_authenticate?(probe_response.headers["www-authenticate"])
-
144
request.transition(:idle)
-
126
request.headers["authorization"] = digest.authenticate(request, probe_response.headers["www-authenticate"])
-
144
super(request)
-
else
-
16
probe_response
-
end
-
end
-
end
-
end
-
end
-
-
8
register_plugin :digest_auth, DigestAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
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
-
#
-
8
module Expect
-
8
EXPECT_TIMEOUT = 2
-
-
8
class << self
-
8
def no_expect_store
-
176
@no_expect_store ||= []
-
end
-
-
8
def extra_options(options)
-
216
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.
-
8
module OptionsMethods
-
8
def option_expect_timeout(value)
-
384
seconds = Float(value)
-
384
raise TypeError, ":expect_timeout must be positive" unless seconds.positive?
-
-
384
seconds
-
end
-
-
8
def option_expect_threshold_size(value)
-
16
bytes = Integer(value)
-
16
raise TypeError, ":expect_threshold_size must be positive" unless bytes.positive?
-
-
16
bytes
-
end
-
end
-
-
8
module RequestMethods
-
8
def initialize(*)
-
248
super
-
248
return if @body.empty?
-
-
168
threshold = @options.expect_threshold_size
-
168
return if threshold && !@body.unbounded_body? && @body.bytesize < threshold
-
-
152
return if Expect.no_expect_store.include?(origin)
-
-
126
@headers["expect"] = "100-continue"
-
end
-
-
8
def response=(response)
-
184
if response.is_a?(Response) &&
-
response.status == 100 &&
-
!@headers.key?("expect") &&
-
3
(@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"
-
8
@informational_status = 100
-
8
Expect.no_expect_store.delete(origin)
-
end
-
184
super
-
end
-
end
-
-
8
module ConnectionMethods
-
8
def send_request_to_parser(request)
-
112
super
-
-
112
return unless request.headers["expect"] == "100-continue"
-
-
80
expect_timeout = request.options.expect_timeout
-
-
80
return if expect_timeout.nil? || expect_timeout.infinite?
-
-
80
set_request_timeout(request, expect_timeout, :expect, %i[body response]) do
-
# expect timeout expired
-
16
if request.state == :expect && !request.expects?
-
16
Expect.no_expect_store << request.origin
-
16
request.headers.delete("expect")
-
16
consume
-
end
-
end
-
end
-
end
-
-
8
module InstanceMethods
-
8
def fetch_response(request, selector, options)
-
411
response = super
-
-
411
return unless response
-
-
112
if response.is_a?(Response) && response.status == 417 && request.headers.key?("expect")
-
16
response.close
-
16
request.headers.delete("expect")
-
16
request.transition(:idle)
-
16
send_request(request, selector, options)
-
14
return
-
end
-
-
96
response
-
end
-
end
-
end
-
8
register_plugin :expect, Expect
-
end
-
end
-
# frozen_string_literal: true
-
-
15
module HTTPX
-
15
InsecureRedirectError = Class.new(Error)
-
15
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
-
#
-
15
module FollowRedirects
-
15
MAX_REDIRECTS = 3
-
15
REDIRECT_STATUS = (300..399).freeze
-
15
REQUEST_BODY_HEADERS = %w[transfer-encoding content-encoding content-type content-length content-language content-md5 trailer].freeze
-
-
15
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>.
-
15
module OptionsMethods
-
15
def option_max_redirects(value)
-
461
num = Integer(value)
-
461
raise TypeError, ":max_redirects must be positive" if num.negative?
-
-
461
num
-
end
-
-
15
def option_follow_insecure_redirects(value)
-
24
value
-
end
-
-
15
def option_allow_auth_to_other_origins(value)
-
24
value
-
end
-
-
15
def option_redirect_on(value)
-
48
raise TypeError, ":redirect_on must be callable" unless value.respond_to?(:call)
-
-
48
value
-
end
-
end
-
-
15
module InstanceMethods
-
# returns a session with the *max_redirects* option set to +n+
-
15
def max_redirects(n)
-
48
with(max_redirects: n.to_i)
-
end
-
-
15
private
-
-
15
def fetch_response(request, selector, options)
-
1368510
redirect_request = request.redirect_request
-
1368510
response = super(redirect_request, selector, options)
-
1368510
return unless response
-
-
567
max_redirects = redirect_request.max_redirects
-
-
567
return response unless response.is_a?(Response)
-
551
return response unless REDIRECT_STATUS.include?(response.status) && response.headers.key?("location")
-
360
return response unless max_redirects.positive?
-
-
328
redirect_uri = __get_location_from_response(response)
-
-
328
if options.redirect_on
-
32
redirect_allowed = options.redirect_on.call(redirect_uri)
-
32
return response unless redirect_allowed
-
end
-
-
# build redirect request
-
312
request_body = redirect_request.body
-
312
redirect_method = "GET"
-
312
redirect_params = {}
-
-
312
if response.status == 305 && options.respond_to?(:proxy)
-
8
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.
-
8
redirect_options = options.merge(headers: redirect_request.headers,
-
proxy: { uri: redirect_uri },
-
max_redirects: max_redirects - 1)
-
-
7
redirect_params[:body] = request_body
-
8
redirect_uri = redirect_request.uri
-
8
options = redirect_options
-
else
-
304
redirect_headers = redirect_request_headers(redirect_request.uri, redirect_uri, request.headers, options)
-
304
redirect_opts = Hash[options]
-
268
redirect_params[:max_redirects] = max_redirects - 1
-
-
304
unless request_body.empty?
-
24
if response.status == 307
-
# The method and the body of the original request are reused to perform the redirected request.
-
8
redirect_method = redirect_request.verb
-
8
request_body.rewind
-
7
redirect_params[:body] = request_body
-
else
-
# redirects are **ALWAYS** GET, so remove body-related headers
-
16
REQUEST_BODY_HEADERS.each do |h|
-
112
redirect_headers.delete(h)
-
end
-
14
redirect_params[:body] = nil
-
end
-
end
-
-
304
options = options.class.new(redirect_opts.merge(headers: redirect_headers.to_h))
-
end
-
-
312
redirect_uri = Utils.to_uri(redirect_uri)
-
-
312
if !options.follow_insecure_redirects &&
-
response.uri.scheme == "https" &&
-
redirect_uri.scheme == "http"
-
8
error = InsecureRedirectError.new(redirect_uri.to_s)
-
8
error.set_backtrace(caller)
-
7
return ErrorResponse.new(request, error)
-
end
-
-
304
retry_request = build_request(redirect_method, redirect_uri, redirect_params, options)
-
-
304
request.redirect_request = retry_request
-
-
304
redirect_after = response.headers["retry-after"]
-
-
304
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.
-
#
-
30
redirect_after = Utils.parse_retry_after(redirect_after)
-
-
30
retry_start = Utils.now
-
30
log { "redirecting after #{redirect_after} secs..." }
-
30
selector.after(redirect_after) do
-
30
if request.response
-
# request has terminated abruptly meanwhile
-
14
retry_request.emit(:response, request.response)
-
else
-
16
log { "redirecting (elapsed time: #{Utils.elapsed_time(retry_start)})!!" }
-
16
send_request(retry_request, selector, options)
-
end
-
end
-
else
-
274
send_request(retry_request, selector, options)
-
end
-
115
nil
-
end
-
-
# :nodoc:
-
15
def redirect_request_headers(original_uri, redirect_uri, headers, options)
-
304
headers = headers.dup
-
-
304
return headers if options.allow_auth_to_other_origins
-
-
296
return headers unless headers.key?("authorization")
-
-
8
return headers if original_uri.origin == redirect_uri.origin
-
-
8
headers.delete("authorization")
-
-
8
headers
-
end
-
-
# :nodoc:
-
15
def __get_location_from_response(response)
-
# @type var location_uri: http_uri
-
328
location_uri = URI(response.headers["location"])
-
328
location_uri = response.uri.merge(location_uri) if location_uri.relative?
-
328
location_uri
-
end
-
end
-
-
15
module RequestMethods
-
# returns the top-most original HTTPX::Request from the redirect chain
-
15
attr_accessor :root_request
-
-
# returns the follow-up redirect request, or itself
-
15
def redirect_request
-
1368510
@redirect_request || self
-
end
-
-
# sets the follow-up redirect request
-
15
def redirect_request=(req)
-
304
@redirect_request = req
-
304
req.root_request = @root_request || self
-
304
@response = nil
-
end
-
-
15
def response
-
1837
return super unless @redirect_request && @response.nil?
-
-
70
@redirect_request.response
-
end
-
-
15
def max_redirects
-
567
@options.max_redirects || MAX_REDIRECTS
-
end
-
end
-
-
15
module ConnectionMethods
-
15
private
-
-
15
def set_request_request_timeout(request)
-
541
return unless request.root_request.nil?
-
-
257
super
-
end
-
end
-
end
-
15
register_plugin :follow_redirects, FollowRedirects
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
GRPCError = Class.new(Error) do
-
6
attr_reader :status, :details, :metadata
-
-
6
def initialize(status, details, metadata)
-
24
@status = status
-
24
@details = details
-
24
@metadata = metadata
-
24
super("GRPC error, code=#{status}, details=#{details}, metadata=#{metadata}")
-
end
-
end
-
-
6
module Plugins
-
#
-
# This plugin adds DSL to build GRPC interfaces.
-
#
-
# https://gitlab.com/os85/httpx/wikis/GRPC
-
#
-
6
module GRPC
-
6
unless String.method_defined?(:underscore)
-
6
module StringExtensions
-
6
refine String do
-
6
def underscore
-
312
s = dup # Avoid mutating the argument, as it might be frozen.
-
312
s.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
-
312
s.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
-
312
s.tr!("-", "_")
-
312
s.downcase!
-
312
s
-
end
-
end
-
end
-
6
using StringExtensions
-
end
-
-
6
DEADLINE = 60
-
6
MARSHAL_METHOD = :encode
-
6
UNMARSHAL_METHOD = :decode
-
6
HEADERS = {
-
"content-type" => "application/grpc",
-
"te" => "trailers",
-
"accept" => "application/grpc",
-
# metadata fits here
-
# ex "foo-bin" => base64("bar")
-
}.freeze
-
-
6
class << self
-
6
def load_dependencies(*)
-
138
require "stringio"
-
138
require "httpx/plugins/grpc/grpc_encoding"
-
138
require "httpx/plugins/grpc/message"
-
138
require "httpx/plugins/grpc/call"
-
end
-
-
6
def configure(klass)
-
138
klass.plugin(:persistent)
-
138
klass.plugin(:stream)
-
end
-
-
6
def extra_options(options)
-
138
options.merge(
-
fallback_protocol: "h2",
-
grpc_rpcs: {}.freeze,
-
grpc_compression: false,
-
grpc_deadline: DEADLINE
-
)
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_grpc_service(value)
-
120
String(value)
-
end
-
-
6
def option_grpc_compression(value)
-
162
case value
-
when true, false
-
138
value
-
else
-
24
value.to_s
-
end
-
end
-
-
6
def option_grpc_rpcs(value)
-
1116
Hash[value]
-
end
-
-
6
def option_grpc_deadline(value)
-
804
raise TypeError, ":grpc_deadline must be positive" unless value.positive?
-
-
804
value
-
end
-
-
6
def option_call_credentials(value)
-
18
raise TypeError, ":call_credentials must respond to #call" unless value.respond_to?(:call)
-
-
18
value
-
end
-
end
-
-
6
module ResponseMethods
-
6
attr_reader :trailing_metadata
-
-
6
def merge_headers(trailers)
-
114
@trailing_metadata = Hash[trailers]
-
114
super
-
end
-
end
-
-
6
module RequestBodyMethods
-
6
def initialize(*, **)
-
126
super
-
-
126
if (compression = @headers["grpc-encoding"])
-
12
deflater_body = self.class.initialize_deflater_body(@body, compression)
-
12
@body = Transcoder::GRPCEncoding.encode(deflater_body || @body, compressed: !deflater_body.nil?)
-
else
-
114
@body = Transcoder::GRPCEncoding.encode(@body, compressed: false)
-
end
-
end
-
end
-
-
6
module InstanceMethods
-
6
def with_channel_credentials(ca_path, key = nil, cert = nil, **ssl_opts)
-
# @type var ssl_params: ::Hash[::Symbol, untyped]
-
72
ssl_params = {
-
**ssl_opts,
-
ca_file: ca_path,
-
}
-
72
if key
-
72
key = File.read(key) if File.file?(key)
-
72
ssl_params[:key] = OpenSSL::PKey.read(key)
-
end
-
-
72
if cert
-
72
cert = File.read(cert) if File.file?(cert)
-
72
ssl_params[:cert] = OpenSSL::X509::Certificate.new(cert)
-
end
-
-
72
with(ssl: ssl_params)
-
end
-
-
6
def rpc(rpc_name, input, output, **opts)
-
312
rpc_name = rpc_name.to_s
-
312
raise Error, "rpc #{rpc_name} already defined" if @options.grpc_rpcs.key?(rpc_name)
-
-
rpc_opts = {
-
312
deadline: @options.grpc_deadline,
-
}.merge(opts)
-
-
312
local_rpc_name = rpc_name.underscore
-
-
312
session_class = Class.new(self.class) do
-
# define rpc method with ruby style name
-
312
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
-
312
unless local_rpc_name == rpc_name
-
12
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
-
-
312
session_class.new(@options.merge(
-
grpc_rpcs: @options.grpc_rpcs.merge(
-
local_rpc_name => [rpc_name, input, output, rpc_opts]
-
).freeze
-
))
-
end
-
-
6
def build_stub(origin, service: nil, compression: false)
-
138
scheme = @options.ssl.empty? ? "http" : "https"
-
-
138
origin = URI.parse("#{scheme}://#{origin}")
-
-
138
session = self
-
-
138
if service && service.respond_to?(:rpc_descs)
-
# it's a grpc generic service
-
60
service.rpc_descs.each do |rpc_name, rpc_desc|
-
rpc_opts = {
-
300
marshal_method: rpc_desc.marshal_method,
-
unmarshal_method: rpc_desc.unmarshal_method,
-
}
-
-
300
input = rpc_desc.input
-
300
input = input.type if input.respond_to?(:type)
-
-
300
output = rpc_desc.output
-
300
if output.respond_to?(:type)
-
120
rpc_opts[:stream] = true
-
120
output = output.type
-
end
-
-
300
session = session.rpc(rpc_name, input, output, **rpc_opts)
-
end
-
-
60
service = service.service_name
-
end
-
-
138
session.with(origin: origin, grpc_service: service, grpc_compression: compression)
-
end
-
-
6
def execute(rpc_method, input,
-
deadline: DEADLINE,
-
metadata: nil,
-
**opts)
-
126
grpc_request = build_grpc_request(rpc_method, input, deadline: deadline, metadata: metadata, **opts)
-
126
response = request(grpc_request, **opts)
-
126
response.raise_for_status unless opts[:stream]
-
114
GRPC::Call.new(response)
-
end
-
-
6
private
-
-
6
def rpc_execute(rpc_name, input, **opts)
-
60
rpc_name, input_enc, output_enc, rpc_opts = @options.grpc_rpcs[rpc_name]
-
-
60
exec_opts = rpc_opts.merge(opts)
-
-
60
marshal_method ||= exec_opts.delete(:marshal_method) || MARSHAL_METHOD
-
60
unmarshal_method ||= exec_opts.delete(:unmarshal_method) || UNMARSHAL_METHOD
-
-
60
messages = if input.respond_to?(:each)
-
24
Enumerator.new do |y|
-
24
input.each do |message|
-
48
y << input_enc.__send__(marshal_method, message)
-
end
-
end
-
else
-
36
input_enc.__send__(marshal_method, input)
-
end
-
-
60
call = execute(rpc_name, messages, **exec_opts)
-
-
60
call.decoder = output_enc.method(unmarshal_method)
-
-
60
call
-
end
-
-
6
def build_grpc_request(rpc_method, input, deadline:, metadata: nil, **)
-
126
uri = @options.origin.dup
-
126
rpc_method = "/#{rpc_method}" unless rpc_method.start_with?("/")
-
126
rpc_method = "/#{@options.grpc_service}#{rpc_method}" if @options.grpc_service
-
126
uri.path = rpc_method
-
-
126
headers = HEADERS.merge(
-
"grpc-accept-encoding" => ["identity", *@options.supported_compression_formats]
-
)
-
126
unless deadline == Float::INFINITY
-
# convert to milliseconds
-
126
deadline = (deadline * 1000.0).to_i
-
126
headers["grpc-timeout"] = "#{deadline}m"
-
end
-
-
126
headers = headers.merge(metadata.transform_keys(&:to_s)) if metadata
-
-
# prepare compressor
-
126
compression = @options.grpc_compression == true ? "gzip" : @options.grpc_compression
-
-
126
headers["grpc-encoding"] = compression if compression
-
-
126
headers.merge!(@options.call_credentials.call.transform_keys(&:to_s)) if @options.call_credentials
-
-
126
build_request("POST", uri, headers: headers, body: input)
-
end
-
end
-
end
-
6
register_plugin :grpc, GRPC
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
6
module GRPC
-
# Encapsulates call information
-
6
class Call
-
6
attr_writer :decoder
-
-
6
def initialize(response)
-
114
@response = response
-
156
@decoder = ->(z) { z }
-
114
@consumed = false
-
114
@grpc_response = nil
-
end
-
-
6
def inspect
-
"#GRPC::Call(#{grpc_response})"
-
end
-
-
6
def to_s
-
66
grpc_response.to_s
-
end
-
-
6
def metadata
-
response.headers
-
end
-
-
6
def trailing_metadata
-
72
return unless @consumed
-
-
48
@response.trailing_metadata
-
end
-
-
6
private
-
-
6
def grpc_response
-
186
@grpc_response ||= if @response.respond_to?(:each)
-
24
Enumerator.new do |y|
-
24
Message.stream(@response).each do |message|
-
48
y << @decoder.call(message)
-
end
-
24
@consumed = true
-
end
-
else
-
90
@consumed = true
-
90
@decoder.call(Message.unary(@response))
-
end
-
end
-
-
6
def respond_to_missing?(meth, *args, &blk)
-
24
grpc_response.respond_to?(meth, *args) || super
-
end
-
-
6
def method_missing(meth, *args, &blk)
-
48
return grpc_response.__send__(meth, *args, &blk) if grpc_response.respond_to?(meth)
-
-
super
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Transcoder
-
6
module GRPCEncoding
-
6
class Deflater
-
6
extend Forwardable
-
-
6
attr_reader :content_type
-
-
6
def initialize(body, compressed:)
-
126
@content_type = body.content_type
-
126
@body = BodyReader.new(body)
-
126
@compressed = compressed
-
end
-
-
6
def bytesize
-
402
return @body.bytesize if @body.respond_to?(:bytesize)
-
-
Float::INFINITY
-
end
-
-
6
def read(length = nil, outbuf = nil)
-
264
buf = @body.read(length, outbuf)
-
-
252
return unless buf
-
-
138
compressed_flag = @compressed ? 1 : 0
-
-
138
buf = outbuf if outbuf
-
-
138
buf.prepend([compressed_flag, buf.bytesize].pack("CL>"))
-
138
buf
-
end
-
end
-
-
6
class Inflater
-
6
def initialize(response)
-
90
@response = response
-
90
@grpc_encodings = nil
-
end
-
-
6
def call(message, &blk)
-
114
data = "".b
-
-
114
until message.empty?
-
114
compressed, size = message.unpack("CL>")
-
-
114
encoded_data = message.byteslice(5..size + 5 - 1)
-
-
114
if compressed == 1
-
12
grpc_encodings.reverse_each do |encoding|
-
12
decoder = @response.body.class.initialize_inflater_by_encoding(encoding, @response, bytesize: encoded_data.bytesize)
-
12
encoded_data = decoder.call(encoded_data)
-
-
12
blk.call(encoded_data) if blk
-
-
12
data << encoded_data
-
end
-
else
-
102
blk.call(encoded_data) if blk
-
-
102
data << encoded_data
-
end
-
-
114
message = message.byteslice((size + 5)..-1)
-
end
-
-
114
data
-
end
-
-
6
private
-
-
6
def grpc_encodings
-
12
@grpc_encodings ||= @response.headers.get("grpc-encoding")
-
end
-
end
-
-
6
def self.encode(*args, **kwargs)
-
126
Deflater.new(*args, **kwargs)
-
end
-
-
6
def self.decode(response)
-
90
Inflater.new(response)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
6
module GRPC
-
# Encoding module for GRPC responses
-
#
-
# Can encode and decode grpc messages.
-
6
module Message
-
6
module_function
-
-
# decodes a unary grpc response
-
6
def unary(response)
-
90
verify_status(response)
-
-
66
decoder = Transcoder::GRPCEncoding.decode(response)
-
-
66
decoder.call(response.to_s)
-
end
-
-
# lazy decodes a grpc stream response
-
6
def stream(response, &block)
-
48
return enum_for(__method__, response) unless block
-
-
24
decoder = Transcoder::GRPCEncoding.decode(response)
-
-
24
response.each do |frame|
-
48
decoder.call(frame, &block)
-
end
-
-
24
verify_status(response)
-
end
-
-
6
def cancel(request)
-
request.emit(:refuse, :client_cancellation)
-
end
-
-
# interprets the grpc call trailing metadata, and raises an
-
# exception in case of error code
-
6
def verify_status(response)
-
# return standard errors if need be
-
114
response.raise_for_status
-
-
114
status = Integer(response.headers["grpc-status"])
-
114
message = response.headers["grpc-message"]
-
-
114
return if status.zero?
-
-
24
response.close
-
24
raise GRPCError.new(status, message, response.trailing_metadata)
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
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
-
#
-
8
module H2C
-
8
VALID_H2C_VERBS = %w[GET OPTIONS HEAD].freeze
-
-
8
class << self
-
8
def load_dependencies(klass)
-
16
klass.plugin(:upgrade)
-
end
-
-
8
def call(connection, request, response)
-
16
connection.upgrade_to_h2c(request, response)
-
end
-
-
8
def extra_options(options)
-
16
options.merge(max_concurrent_requests: 1, upgrade_handlers: options.upgrade_handlers.merge("h2c" => self))
-
end
-
end
-
-
8
class H2CParser < Connection::HTTP2
-
8
def upgrade(request, response)
-
# skip checks, it is assumed that this is the first
-
# request in the connection
-
16
stream = @connection.upgrade
-
-
# on_settings
-
16
handle_stream(stream, request)
-
14
@streams[request] = stream
-
-
# clean up data left behind in the buffer, if the server started
-
# sending frames
-
16
data = response.read
-
16
@connection << data
-
end
-
end
-
-
8
module ConnectionMethods
-
8
using URIExtensions
-
-
8
def initialize(*)
-
16
super
-
16
@h2c_handshake = false
-
end
-
-
8
def send(request)
-
56
return super if @h2c_handshake
-
-
16
return super unless VALID_H2C_VERBS.include?(request.verb) && request.scheme == "http"
-
-
16
return super if @upgrade_protocol == "h2c"
-
-
16
@h2c_handshake = true
-
-
# build upgrade request
-
16
request.headers.add("connection", "upgrade")
-
16
request.headers.add("connection", "http2-settings")
-
14
request.headers["upgrade"] = "h2c"
-
14
request.headers["http2-settings"] = ::HTTP2::Client.settings_header(request.options.http2_settings)
-
-
16
super
-
end
-
-
8
def upgrade_to_h2c(request, response)
-
16
prev_parser = @parser
-
-
16
if prev_parser
-
16
prev_parser.reset
-
14
@inflight -= prev_parser.requests.size
-
end
-
-
16
@parser = H2CParser.new(@write_buffer, @options)
-
16
set_parser_callbacks(@parser)
-
14
@inflight += 1
-
16
@parser.upgrade(request, response)
-
16
@upgrade_protocol = "h2c"
-
-
16
prev_parser.requests.each do |req|
-
16
req.transition(:idle)
-
16
send(req)
-
end
-
end
-
-
8
private
-
-
8
def send_request_to_parser(request)
-
56
super
-
-
56
return unless request.headers["upgrade"] == "h2c" && parser.is_a?(Connection::HTTP1)
-
-
16
max_concurrent_requests = parser.max_concurrent_requests
-
-
16
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
-
8
register_plugin(:h2c, H2C)
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# https://gitlab.com/os85/httpx/wikis/Auth#ntlm-auth
-
#
-
6
module NTLMAuth
-
6
class << self
-
6
def load_dependencies(_klass)
-
2
require_relative "auth/ntlm"
-
end
-
-
6
def extra_options(options)
-
2
options.merge(max_concurrent_requests: 1)
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_ntlm(value)
-
8
raise TypeError, ":ntlm must be a #{Authentication::Ntlm}" unless value.is_a?(Authentication::Ntlm)
-
-
8
value
-
end
-
end
-
-
6
module InstanceMethods
-
6
def ntlm_auth(user, password, domain = nil)
-
4
with(ntlm: Authentication::Ntlm.new(user, password, domain: domain))
-
end
-
-
6
private
-
-
6
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
-
6
register_plugin :ntlm_auth, NTLMAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
module Plugins
-
#
-
# https://gitlab.com/os85/httpx/wikis/OAuth
-
#
-
8
module OAuth
-
8
class << self
-
8
def load_dependencies(_klass)
-
144
require_relative "auth/basic"
-
end
-
end
-
-
8
SUPPORTED_GRANT_TYPES = %w[client_credentials refresh_token].freeze
-
8
SUPPORTED_AUTH_METHODS = %w[client_secret_basic client_secret_post].freeze
-
-
8
class OAuthSession
-
8
attr_reader :grant_type, :client_id, :client_secret, :access_token, :refresh_token, :scope
-
-
8
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
-
)
-
128
@issuer = URI(issuer)
-
128
@client_id = client_id
-
128
@client_secret = client_secret
-
128
@token_endpoint = URI(token_endpoint) if token_endpoint
-
128
@response_type = response_type
-
128
@scope = case scope
-
when String
-
48
scope.split
-
when Array
-
32
scope
-
end
-
128
@access_token = access_token
-
128
@refresh_token = refresh_token
-
128
@token_endpoint_auth_method = String(token_endpoint_auth_method) if token_endpoint_auth_method
-
128
@grant_type = grant_type || (@refresh_token ? "refresh_token" : "client_credentials")
-
-
128
unless @token_endpoint_auth_method.nil? || SUPPORTED_AUTH_METHODS.include?(@token_endpoint_auth_method)
-
16
raise Error, "#{@token_endpoint_auth_method} is not a supported auth method"
-
end
-
-
112
return if SUPPORTED_GRANT_TYPES.include?(@grant_type)
-
-
16
raise Error, "#{@grant_type} is not a supported grant type"
-
end
-
-
8
def token_endpoint
-
112
@token_endpoint || "#{@issuer}/token"
-
end
-
-
8
def token_endpoint_auth_method
-
160
@token_endpoint_auth_method || "client_secret_basic"
-
end
-
-
8
def load(http)
-
48
return if @grant_type && @scope
-
-
16
metadata = http.get("#{@issuer}/.well-known/oauth-authorization-server").raise_for_status.json
-
-
16
@token_endpoint = metadata["token_endpoint"]
-
16
@scope = metadata["scopes_supported"]
-
64
@grant_type = Array(metadata["grant_types_supported"]).find { |gr| SUPPORTED_GRANT_TYPES.include?(gr) }
-
16
@token_endpoint_auth_method = Array(metadata["token_endpoint_auth_methods_supported"]).find do |am|
-
16
SUPPORTED_AUTH_METHODS.include?(am)
-
end
-
6
nil
-
end
-
-
8
def merge(other)
-
96
obj = dup
-
-
84
case other
-
when OAuthSession
-
48
other.instance_variables.each do |ivar|
-
432
val = other.instance_variable_get(ivar)
-
432
next unless val
-
-
336
obj.instance_variable_set(ivar, val)
-
end
-
when Hash
-
48
other.each do |k, v|
-
96
obj.instance_variable_set(:"@#{k}", v) if obj.instance_variable_defined?(:"@#{k}")
-
end
-
end
-
96
obj
-
end
-
end
-
-
8
module OptionsMethods
-
8
def option_oauth_session(value)
-
266
case value
-
when Hash
-
16
OAuthSession.new(**value)
-
when OAuthSession
-
272
value
-
else
-
16
raise TypeError, ":oauth_session must be a #{OAuthSession}"
-
end
-
end
-
end
-
-
8
module InstanceMethods
-
8
def oauth_auth(**args)
-
112
with(oauth_session: OAuthSession.new(**args))
-
end
-
-
8
def with_access_token
-
48
oauth_session = @options.oauth_session
-
-
48
oauth_session.load(self)
-
-
48
grant_type = oauth_session.grant_type
-
-
48
headers = {}
-
48
form_post = { "grant_type" => grant_type, "scope" => Array(oauth_session.scope).join(" ") }.compact
-
-
# auth
-
42
case oauth_session.token_endpoint_auth_method
-
when "client_secret_post"
-
14
form_post["client_id"] = oauth_session.client_id
-
14
form_post["client_secret"] = oauth_session.client_secret
-
when "client_secret_basic"
-
28
headers["authorization"] = Authentication::Basic.new(oauth_session.client_id, oauth_session.client_secret).authenticate
-
end
-
-
42
case grant_type
-
when "client_credentials"
-
# do nothing
-
when "refresh_token"
-
14
form_post["refresh_token"] = oauth_session.refresh_token
-
end
-
-
48
token_request = build_request("POST", oauth_session.token_endpoint, headers: headers, form: form_post)
-
48
token_request.headers.delete("authorization") unless oauth_session.token_endpoint_auth_method == "client_secret_basic"
-
-
48
token_response = request(token_request)
-
48
token_response.raise_for_status
-
-
48
payload = token_response.json
-
-
48
access_token = payload["access_token"]
-
48
refresh_token = payload["refresh_token"]
-
-
48
with(oauth_session: oauth_session.merge(access_token: access_token, refresh_token: refresh_token))
-
end
-
-
8
def build_request(*)
-
128
request = super
-
-
128
return request if request.headers.key?("authorization")
-
-
96
oauth_session = @options.oauth_session
-
-
96
return request unless oauth_session && oauth_session.access_token
-
-
56
request.headers["authorization"] = "Bearer #{oauth_session.access_token}"
-
-
64
request
-
end
-
end
-
end
-
8
register_plugin :oauth, OAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
10
module HTTPX
-
10
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
-
#
-
10
module Persistent
-
10
def self.load_dependencies(klass)
-
403
max_retries = if klass.default_options.respond_to?(:max_retries)
-
8
[klass.default_options.max_retries, 1].max
-
else
-
395
1
-
end
-
403
klass.plugin(:retries, max_retries: max_retries, retry_change_requests: true)
-
end
-
-
10
def self.extra_options(options)
-
403
options.merge(persistent: true)
-
end
-
-
10
module InstanceMethods
-
10
private
-
-
10
def get_current_selector
-
383
super(&nil) || begin
-
375
return unless block_given?
-
-
375
default = yield
-
-
375
set_current_selector(default)
-
-
375
default
-
end
-
end
-
end
-
end
-
10
register_plugin :persistent, Persistent
-
end
-
end
-
# frozen_string_literal: true
-
-
10
module HTTPX
-
10
class HTTPProxyError < ConnectionError; end
-
-
10
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
-
#
-
10
module Proxy
-
10
Error = HTTPProxyError
-
10
PROXY_ERRORS = [TimeoutError, IOError, SystemCallError, Error].freeze
-
-
10
class << self
-
10
def configure(klass)
-
337
klass.plugin(:"proxy/http")
-
337
klass.plugin(:"proxy/socks4")
-
337
klass.plugin(:"proxy/socks5")
-
end
-
-
10
def extra_options(options)
-
337
options.merge(supported_proxy_protocols: [])
-
end
-
end
-
-
10
class Parameters
-
10
attr_reader :uri, :username, :password, :scheme, :no_proxy
-
-
10
def initialize(uri: nil, scheme: nil, username: nil, password: nil, no_proxy: nil, **extra)
-
371
@no_proxy = Array(no_proxy) if no_proxy
-
371
@uris = Array(uri)
-
371
uri = @uris.first
-
-
371
@username = username
-
371
@password = password
-
-
371
@ns = 0
-
-
371
if uri
-
331
@uri = uri.is_a?(URI::Generic) ? uri : URI(uri)
-
331
@username ||= @uri.user
-
331
@password ||= @uri.password
-
end
-
-
371
@scheme = scheme
-
-
371
return unless @uri && @username && @password
-
-
210
@authenticator = nil
-
210
@scheme ||= infer_default_auth_scheme(@uri)
-
-
210
return unless @scheme
-
-
162
@authenticator = load_authenticator(@scheme, @username, @password, **extra)
-
end
-
-
10
def shift
-
# TODO: this operation must be synchronized
-
105
@ns += 1
-
120
@uri = @uris[@ns]
-
-
120
return unless @uri
-
-
16
@uri = URI(@uri) unless @uri.is_a?(URI::Generic)
-
-
16
scheme = infer_default_auth_scheme(@uri)
-
-
16
return unless scheme != @scheme
-
-
16
@scheme = scheme
-
16
@username = username || @uri.user
-
16
@password = password || @uri.password
-
16
@authenticator = load_authenticator(scheme, @username, @password)
-
end
-
-
10
def can_authenticate?(*args)
-
184
return false unless @authenticator
-
-
64
@authenticator.can_authenticate?(*args)
-
end
-
-
10
def authenticate(*args)
-
159
return unless @authenticator
-
-
159
@authenticator.authenticate(*args)
-
end
-
-
10
def ==(other)
-
384
case other
-
when Parameters
-
396
@uri == other.uri &&
-
@username == other.username &&
-
@password == other.password &&
-
@scheme == other.scheme
-
when URI::Generic, String
-
24
proxy_uri = @uri.dup
-
24
proxy_uri.user = @username
-
24
proxy_uri.password = @password
-
24
other_uri = other.is_a?(URI::Generic) ? other : URI.parse(other)
-
24
proxy_uri == other_uri
-
else
-
16
super
-
end
-
end
-
-
10
private
-
-
10
def infer_default_auth_scheme(uri)
-
185
case uri.scheme
-
when "socks5"
-
48
uri.scheme
-
when "http", "https"
-
101
"basic"
-
end
-
end
-
-
10
def load_authenticator(scheme, username, password, **extra)
-
178
auth_scheme = scheme.to_s.capitalize
-
-
178
require_relative "auth/#{scheme}" unless defined?(Authentication) && Authentication.const_defined?(auth_scheme, false)
-
-
178
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>)
-
10
module OptionsMethods
-
10
def option_proxy(value)
-
672
value.is_a?(Parameters) ? value : Parameters.new(**Hash[value])
-
end
-
-
10
def option_supported_proxy_protocols(value)
-
1699
raise TypeError, ":supported_proxy_protocols must be an Array" unless value.is_a?(Array)
-
-
1699
value.map(&:to_s)
-
end
-
end
-
-
10
module InstanceMethods
-
10
def find_connection(request_uri, selector, options)
-
417
return super unless options.respond_to?(:proxy)
-
-
417
if (next_proxy = request_uri.find_proxy)
-
4
return super(request_uri, selector, options.merge(proxy: Parameters.new(uri: next_proxy)))
-
end
-
-
413
proxy = options.proxy
-
-
413
return super unless proxy
-
-
403
next_proxy = proxy.uri
-
-
403
raise Error, "Failed to connect to proxy" unless next_proxy
-
-
1
raise Error,
-
387
"#{next_proxy.scheme}: unsupported proxy protocol" unless options.supported_proxy_protocols.include?(next_proxy.scheme)
-
-
379
if (no_proxy = proxy.no_proxy)
-
16
no_proxy = no_proxy.join(",") if no_proxy.is_a?(Array)
-
-
# TODO: setting proxy to nil leaks the connection object in the pool
-
16
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
-
-
371
super(request_uri, selector, options.merge(proxy: proxy))
-
end
-
-
10
private
-
-
10
def fetch_response(request, selector, options)
-
1507
response = super
-
-
1507
if response.is_a?(ErrorResponse) && proxy_error?(request, response, options)
-
120
options.proxy.shift
-
-
# return last error response if no more proxies to try
-
120
return response if options.proxy.uri.nil?
-
-
16
log { "failed connecting to proxy, trying next..." }
-
16
request.transition(:idle)
-
16
send_request(request, selector, options)
-
14
return
-
end
-
1387
response
-
end
-
-
10
def proxy_error?(_request, response, options)
-
169
return false unless options.proxy
-
-
168
error = response.error
-
147
case error
-
when NativeResolveError
-
16
proxy_uri = URI(options.proxy.uri)
-
-
16
peer = error.connection.peer
-
-
# failed resolving proxy domain
-
16
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
-
152
true
-
else
-
false
-
end
-
end
-
end
-
-
10
module ConnectionMethods
-
10
using URIExtensions
-
-
10
def initialize(*)
-
384
super
-
384
return unless @options.proxy
-
-
# redefining the connection origin as the proxy's URI,
-
# as this will be used as the tcp peer ip.
-
366
@proxy_uri = URI(@options.proxy.uri)
-
end
-
-
10
def peer
-
1053
@proxy_uri || super
-
end
-
-
10
def connecting?
-
4506
return super unless @options.proxy
-
-
4350
super || @state == :connecting || @state == :connected
-
end
-
-
10
def call
-
1028
super
-
-
1028
return unless @options.proxy
-
-
893
case @state
-
when :connecting
-
196
consume
-
end
-
end
-
-
10
def reset
-
400
return super unless @options.proxy
-
-
383
@state = :open
-
-
383
super
-
# emit(:close)
-
end
-
-
10
private
-
-
10
def initialize_type(uri, options)
-
384
return super unless options.proxy
-
-
366
"tcp"
-
end
-
-
10
def connect
-
1046
return super unless @options.proxy
-
-
894
case @state
-
when :idle
-
712
transition(:connecting)
-
when :connected
-
300
transition(:open)
-
end
-
end
-
-
10
def handle_transition(nextstate)
-
2153
return super unless @options.proxy
-
-
1822
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
-
391
@state = :open if @state == :connecting
-
end
-
2066
super
-
end
-
end
-
end
-
10
register_plugin :proxy, Proxy
-
end
-
-
10
class ProxySSL < SSL
-
10
def initialize(tcp, request_uri, options)
-
89
@io = tcp.to_io
-
89
super(request_uri, tcp.addresses, options)
-
89
@hostname = request_uri.host
-
89
@state = :connected
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
10
module HTTPX
-
10
module Plugins
-
10
module Proxy
-
10
module HTTP
-
10
class << self
-
10
def extra_options(options)
-
337
options.merge(supported_proxy_protocols: options.supported_proxy_protocols + %w[http])
-
end
-
end
-
-
10
module InstanceMethods
-
10
def with_proxy_basic_auth(opts)
-
8
with(proxy: opts.merge(scheme: "basic"))
-
end
-
-
10
def with_proxy_digest_auth(opts)
-
24
with(proxy: opts.merge(scheme: "digest"))
-
end
-
-
10
def with_proxy_ntlm_auth(opts)
-
8
with(proxy: opts.merge(scheme: "ntlm"))
-
end
-
-
10
def fetch_response(request, selector, options)
-
1507
response = super
-
-
1507
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"])
-
8
request.transition(:idle)
-
7
request.headers["proxy-authorization"] =
-
options.proxy.authenticate(request, response.headers["proxy-authenticate"])
-
8
send_request(request, selector, options)
-
7
return
-
end
-
-
1499
response
-
end
-
end
-
-
10
module ConnectionMethods
-
10
def connecting?
-
4506
super || @state == :connecting || @state == :connected
-
end
-
-
10
private
-
-
10
def handle_transition(nextstate)
-
2392
return super unless @options.proxy && @options.proxy.uri.scheme == "http"
-
-
1048
case nextstate
-
when :connecting
-
304
return unless @state == :idle
-
-
304
@io.connect
-
304
return unless @io.connected?
-
-
152
@parser || begin
-
144
@parser = self.class.parser_type(@io.protocol).new(@write_buffer, @options.merge(max_concurrent_requests: 1))
-
144
parser = @parser
-
144
parser.extend(ProxyParser)
-
144
parser.on(:response, &method(:__http_on_connect))
-
144
parser.on(:close) do |force|
-
57
next unless @parser
-
-
8
if force
-
8
reset
-
8
emit(:terminate)
-
end
-
end
-
144
parser.on(:reset) do
-
16
if parser.empty?
-
8
reset
-
else
-
8
transition(:closing)
-
8
transition(:closed)
-
-
8
parser.reset if @parser
-
8
transition(:idle)
-
8
transition(:connecting)
-
end
-
end
-
144
__http_proxy_connect(parser)
-
end
-
152
return if @state == :connected
-
when :connected
-
136
return unless @state == :idle || @state == :connecting
-
-
121
case @state
-
when :connecting
-
49
parser = @parser
-
49
@parser = nil
-
49
parser.close
-
when :idle
-
87
@parser.callbacks.clear
-
87
set_parser_callbacks(@parser)
-
end
-
end
-
939
super
-
end
-
-
10
def __http_proxy_connect(parser)
-
144
req = @pending.first
-
144
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.
-
#
-
57
connect_request = ConnectRequest.new(req.uri, @options)
-
51
@inflight += 1
-
57
parser.send(connect_request)
-
else
-
87
handle_transition(:connected)
-
end
-
end
-
-
10
def __http_on_connect(request, response)
-
58
@inflight -= 1
-
65
if response.is_a?(Response) && response.status == 200
-
49
req = @pending.first
-
49
request_uri = req.uri
-
49
@io = ProxySSL.new(@io, request_uri, @options)
-
49
transition(:connected)
-
49
throw(:called)
-
15
elsif response.is_a?(Response) &&
-
response.status == 407 &&
-
!request.headers.key?("proxy-authorization") &&
-
@options.proxy.can_authenticate?(response.headers["proxy-authenticate"])
-
-
8
request.transition(:idle)
-
7
request.headers["proxy-authorization"] = @options.proxy.authenticate(request, response.headers["proxy-authenticate"])
-
8
@parser.send(request)
-
7
@inflight += 1
-
else
-
8
pending = @pending + @parser.pending
-
21
while (req = pending.shift)
-
8
req.emit(:response, response)
-
end
-
8
reset
-
end
-
end
-
end
-
-
10
module ProxyParser
-
10
def join_headline(request)
-
144
return super if request.verb == "CONNECT"
-
-
70
"#{request.verb} #{request.uri} HTTP/#{@version.join(".")}"
-
end
-
-
10
def set_protocol_headers(request)
-
152
extra_headers = super
-
-
152
proxy_params = @options.proxy
-
152
if proxy_params.scheme == "basic"
-
# opt for basic auth
-
85
extra_headers["proxy-authorization"] = proxy_params.authenticate(extra_headers)
-
end
-
152
extra_headers["proxy-connection"] = extra_headers.delete("connection") if extra_headers.key?("connection")
-
152
extra_headers
-
end
-
end
-
-
10
class ConnectRequest < Request
-
10
def initialize(uri, options)
-
57
super("CONNECT", uri, options)
-
57
@headers.delete("accept")
-
end
-
-
10
def path
-
65
"#{@uri.hostname}:#{@uri.port}"
-
end
-
end
-
end
-
end
-
10
register_plugin :"proxy/http", Proxy::HTTP
-
end
-
end
-
# frozen_string_literal: true
-
-
10
require "resolv"
-
10
require "ipaddr"
-
-
10
module HTTPX
-
10
class Socks4Error < HTTPProxyError; end
-
-
10
module Plugins
-
10
module Proxy
-
10
module Socks4
-
10
VERSION = 4
-
10
CONNECT = 1
-
10
GRANTED = 0x5A
-
10
PROTOCOLS = %w[socks4 socks4a].freeze
-
-
10
Error = Socks4Error
-
-
10
class << self
-
10
def extra_options(options)
-
337
options.merge(supported_proxy_protocols: options.supported_proxy_protocols + PROTOCOLS)
-
end
-
end
-
-
10
module ConnectionMethods
-
10
def interests
-
3813
if @state == :connecting
-
return @write_buffer.empty? ? :r : :w
-
end
-
-
3813
super
-
end
-
-
10
private
-
-
10
def handle_transition(nextstate)
-
2456
return super unless @options.proxy && PROTOCOLS.include?(@options.proxy.uri.scheme)
-
-
384
case nextstate
-
when :connecting
-
128
return unless @state == :idle
-
-
128
@io.connect
-
128
return unless @io.connected?
-
-
64
req = @pending.first
-
64
return unless req
-
-
64
request_uri = req.uri
-
64
@write_buffer << Packet.connect(@options.proxy, request_uri)
-
64
__socks4_proxy_connect
-
when :connected
-
48
return unless @state == :connecting
-
-
48
@parser = nil
-
end
-
375
log(level: 1) { "SOCKS4: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
-
375
super
-
end
-
-
10
def __socks4_proxy_connect
-
64
@parser = SocksParser.new(@write_buffer, @options)
-
64
@parser.once(:packet, &method(:__socks4_on_packet))
-
end
-
-
10
def __socks4_on_packet(packet)
-
64
_version, status, _port, _ip = packet.unpack("CCnN")
-
64
if status == GRANTED
-
48
req = @pending.first
-
48
request_uri = req.uri
-
48
@io = ProxySSL.new(@io, request_uri, @options) if request_uri.scheme == "https"
-
48
transition(:connected)
-
48
throw(:called)
-
else
-
16
on_socks4_error("socks error: #{status}")
-
end
-
end
-
-
10
def on_socks4_error(message)
-
16
ex = Error.new(message)
-
16
ex.set_backtrace(caller)
-
16
on_error(ex)
-
16
throw(:called)
-
end
-
end
-
-
10
class SocksParser
-
10
include HTTPX::Callbacks
-
-
10
def initialize(buffer, options)
-
64
@buffer = buffer
-
64
@options = options
-
end
-
-
10
def close; end
-
-
10
def consume(*); end
-
-
10
def empty?
-
true
-
end
-
-
10
def <<(packet)
-
64
emit(:packet, packet)
-
end
-
end
-
-
10
module Packet
-
10
module_function
-
-
10
def connect(parameters, uri)
-
64
packet = [VERSION, CONNECT, uri.port].pack("CCn")
-
-
56
case parameters.uri.scheme
-
when "socks4"
-
48
socks_host = uri.host
-
5
begin
-
96
ip = IPAddr.new(socks_host)
-
48
packet << ip.hton
-
rescue IPAddr::InvalidAddressError
-
48
socks_host = Resolv.getaddress(socks_host)
-
48
retry
-
end
-
48
packet << [parameters.username].pack("Z*")
-
when "socks4a"
-
16
packet << "\x0\x0\x0\x1" << [parameters.username].pack("Z*") << uri.host << "\x0"
-
end
-
64
packet
-
end
-
end
-
end
-
end
-
10
register_plugin :"proxy/socks4", Proxy::Socks4
-
end
-
end
-
# frozen_string_literal: true
-
-
10
module HTTPX
-
10
class Socks5Error < HTTPProxyError; end
-
-
10
module Plugins
-
10
module Proxy
-
10
module Socks5
-
10
VERSION = 5
-
10
NOAUTH = 0
-
10
PASSWD = 2
-
10
NONE = 0xff
-
10
CONNECT = 1
-
10
IPV4 = 1
-
10
DOMAIN = 3
-
10
IPV6 = 4
-
10
SUCCESS = 0
-
-
10
Error = Socks5Error
-
-
10
class << self
-
10
def load_dependencies(*)
-
337
require_relative "../auth/socks5"
-
end
-
-
10
def extra_options(options)
-
337
options.merge(supported_proxy_protocols: options.supported_proxy_protocols + %w[socks5])
-
end
-
end
-
-
10
module ConnectionMethods
-
10
def call
-
1028
super
-
-
1028
return unless @options.proxy && @options.proxy.uri.scheme == "socks5"
-
-
274
case @state
-
when :connecting,
-
:negotiating,
-
:authenticating
-
95
consume
-
end
-
end
-
-
10
def connecting?
-
4506
super || @state == :authenticating || @state == :negotiating
-
end
-
-
10
def interests
-
5968
if @state == :connecting || @state == :authenticating || @state == :negotiating
-
1954
return @write_buffer.empty? ? :r : :w
-
end
-
-
3813
super
-
end
-
-
10
private
-
-
10
def handle_transition(nextstate)
-
2744
return super unless @options.proxy && @options.proxy.uri.scheme == "socks5"
-
-
910
case nextstate
-
when :connecting
-
288
return unless @state == :idle
-
-
288
@io.connect
-
288
return unless @io.connected?
-
-
144
@write_buffer << Packet.negotiate(@options.proxy)
-
144
__socks5_proxy_connect
-
when :authenticating
-
48
return unless @state == :connecting
-
-
48
@write_buffer << Packet.authenticate(@options.proxy)
-
when :negotiating
-
192
return unless @state == :connecting || @state == :authenticating
-
-
48
req = @pending.first
-
48
request_uri = req.uri
-
48
@write_buffer << Packet.connect(request_uri)
-
when :connected
-
32
return unless @state == :negotiating
-
-
32
@parser = nil
-
end
-
752
log(level: 1) { "SOCKS5: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
-
752
super
-
end
-
-
10
def __socks5_proxy_connect
-
144
@parser = SocksParser.new(@write_buffer, @options)
-
144
@parser.on(:packet, &method(:__socks5_on_packet))
-
144
transition(:negotiating)
-
end
-
-
10
def __socks5_on_packet(packet)
-
210
case @state
-
when :connecting
-
144
version, method = packet.unpack("CC")
-
144
__socks5_check_version(version)
-
126
case method
-
when PASSWD
-
48
transition(:authenticating)
-
18
nil
-
when NONE
-
80
__on_socks5_error("no supported authorization methods")
-
else
-
16
transition(:negotiating)
-
end
-
when :authenticating
-
48
_, status = packet.unpack("CC")
-
48
return transition(:negotiating) if status == SUCCESS
-
-
16
__on_socks5_error("socks authentication error: #{status}")
-
when :negotiating
-
48
version, reply, = packet.unpack("CC")
-
48
__socks5_check_version(version)
-
48
__on_socks5_error("socks5 negotiation error: #{reply}") unless reply == SUCCESS
-
32
req = @pending.first
-
32
request_uri = req.uri
-
32
@io = ProxySSL.new(@io, request_uri, @options) if request_uri.scheme == "https"
-
32
transition(:connected)
-
32
throw(:called)
-
end
-
end
-
-
10
def __socks5_check_version(version)
-
192
__on_socks5_error("invalid SOCKS version (#{version})") if version != 5
-
end
-
-
10
def __on_socks5_error(message)
-
112
ex = Error.new(message)
-
112
ex.set_backtrace(caller)
-
112
on_error(ex)
-
112
throw(:called)
-
end
-
end
-
-
10
class SocksParser
-
10
include HTTPX::Callbacks
-
-
10
def initialize(buffer, options)
-
144
@buffer = buffer
-
144
@options = options
-
end
-
-
10
def close; end
-
-
10
def consume(*); end
-
-
10
def empty?
-
true
-
end
-
-
10
def <<(packet)
-
240
emit(:packet, packet)
-
end
-
end
-
-
10
module Packet
-
10
module_function
-
-
10
def negotiate(parameters)
-
144
methods = [NOAUTH]
-
144
methods << PASSWD if parameters.can_authenticate?
-
144
methods.unshift(methods.size)
-
144
methods.unshift(VERSION)
-
144
methods.pack("C*")
-
end
-
-
10
def authenticate(parameters)
-
48
parameters.authenticate
-
end
-
-
10
def connect(uri)
-
48
packet = [VERSION, CONNECT, 0].pack("C*")
-
5
begin
-
48
ip = IPAddr.new(uri.host)
-
-
16
ipcode = ip.ipv6? ? IPV6 : IPV4
-
-
16
packet << [ipcode].pack("C") << ip.hton
-
rescue IPAddr::InvalidAddressError
-
32
packet << [DOMAIN, uri.host.bytesize, uri.host].pack("CCA*")
-
end
-
48
packet << [uri.port].pack("n")
-
48
packet
-
end
-
end
-
end
-
end
-
10
register_plugin :"proxy/socks5", Proxy::Socks5
-
end
-
end
-
# frozen_string_literal: true
-
-
6
require "httpx/plugins/proxy"
-
-
6
module HTTPX
-
6
module Plugins
-
6
module Proxy
-
6
module SSH
-
6
class << self
-
6
def load_dependencies(*)
-
12
require "net/ssh/gateway"
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_proxy(value)
-
24
Hash[value]
-
end
-
end
-
-
6
module InstanceMethods
-
6
def request(*args, **options)
-
12
raise ArgumentError, "must perform at least one request" if args.empty?
-
-
12
requests = args.first.is_a?(Request) ? args : build_requests(*args, options)
-
-
12
request = requests.first or return super
-
-
12
request_options = request.options
-
-
12
return super unless request_options.proxy
-
-
12
ssh_options = request_options.proxy
-
12
ssh_uris = ssh_options.delete(:uri)
-
12
ssh_uri = URI.parse(ssh_uris.shift)
-
-
12
return super unless ssh_uri.scheme == "ssh"
-
-
12
ssh_username = ssh_options.delete(:username)
-
12
ssh_options[:port] ||= ssh_uri.port || 22
-
12
if request_options.debug
-
ssh_options[:verbose] = request_options.debug_level == 2 ? :debug : :info
-
end
-
-
12
request_uri = URI(requests.first.uri)
-
12
@_gateway = Net::SSH::Gateway.new(ssh_uri.host, ssh_username, ssh_options)
-
begin
-
12
@_gateway.open(request_uri.host, request_uri.port) do |local_port|
-
12
io = build_gateway_socket(local_port, request_uri, request_options)
-
12
super(*args, **options.merge(io: io))
-
end
-
ensure
-
12
@_gateway.shutdown!
-
end
-
end
-
-
6
private
-
-
6
def build_gateway_socket(port, request_uri, options)
-
12
case request_uri.scheme
-
when "https"
-
6
ctx = OpenSSL::SSL::SSLContext.new
-
6
ctx_options = SSL::TLS_OPTIONS.merge(options.ssl)
-
6
ctx.set_params(ctx_options) unless ctx_options.empty?
-
6
sock = TCPSocket.open("localhost", port)
-
6
io = OpenSSL::SSL::SSLSocket.new(sock, ctx)
-
6
io.hostname = request_uri.host
-
6
io.sync_close = true
-
6
io.connect
-
6
io.post_connection_check(request_uri.host) if ctx.verify_mode != OpenSSL::SSL::VERIFY_NONE
-
6
io
-
when "http"
-
6
TCPSocket.open("localhost", port)
-
else
-
raise TypeError, "unexpected scheme: #{request_uri.scheme}"
-
end
-
end
-
end
-
-
6
module ConnectionMethods
-
# should not coalesce connections here, as the IP is the IP of the proxy
-
6
def coalescable?(*)
-
return super unless @options.proxy
-
-
false
-
end
-
end
-
end
-
end
-
6
register_plugin :"proxy/ssh", Proxy::SSH
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
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
-
#
-
8
module PushPromise
-
8
def self.extra_options(options)
-
16
options.merge(http2_settings: { settings_enable_push: 1 },
-
max_concurrent_requests: 1)
-
end
-
-
8
module ResponseMethods
-
8
def pushed?
-
16
@__pushed
-
end
-
-
8
def mark_as_pushed!
-
8
@__pushed = true
-
end
-
end
-
-
8
module InstanceMethods
-
8
private
-
-
8
def promise_headers
-
16
@promise_headers ||= {}
-
end
-
-
8
def on_promise(parser, stream)
-
16
stream.on(:promise_headers) do |h|
-
16
__on_promise_request(parser, stream, h)
-
end
-
16
stream.on(:headers) do |h|
-
8
__on_promise_response(parser, stream, h)
-
end
-
end
-
-
8
def __on_promise_request(parser, stream, h)
-
16
log(level: 1, color: :yellow) do
-
skipped
# :nocov:
-
skipped
h.map { |k, v| "#{stream.id}: -> PROMISE HEADER: #{k}: #{v}" }.join("\n")
-
skipped
# :nocov:
-
end
-
16
headers = @options.headers_class.new(h)
-
16
path = headers[":path"]
-
16
authority = headers[":authority"]
-
-
24
request = parser.pending.find { |r| r.authority == authority && r.path == path }
-
16
if request
-
8
request.merge_headers(headers)
-
7
promise_headers[stream] = request
-
8
parser.pending.delete(request)
-
7
parser.streams[request] = stream
-
8
request.transition(:done)
-
else
-
8
stream.refuse
-
end
-
end
-
-
8
def __on_promise_response(parser, stream, h)
-
8
request = promise_headers.delete(stream)
-
8
return unless request
-
-
8
parser.__send__(:on_stream_headers, stream, request, h)
-
8
response = request.response
-
8
response.mark_as_pushed!
-
8
stream.on(:data, &parser.method(:on_stream_data).curry(3)[stream, request])
-
8
stream.on(:close, &parser.method(:on_stream_close).curry(3)[stream, request])
-
end
-
end
-
end
-
8
register_plugin(:push_promise, PushPromise)
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
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
-
#
-
8
module RateLimiter
-
8
class << self
-
8
RATE_LIMIT_CODES = [429, 503].freeze
-
-
8
def configure(klass)
-
64
klass.plugin(:retries,
-
retry_change_requests: true,
-
7
retry_on: method(:retry_on_rate_limited_response),
-
retry_after: method(:retry_after_rate_limit))
-
end
-
-
8
def retry_on_rate_limited_response(response)
-
128
return false unless response.is_a?(Response)
-
-
128
status = response.status
-
-
128
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.
-
#
-
8
def retry_after_rate_limit(_, response)
-
64
return unless response.is_a?(Response)
-
-
64
retry_after = response.headers["retry-after"]
-
-
64
return unless retry_after
-
-
32
Utils.parse_retry_after(retry_after)
-
end
-
end
-
end
-
-
8
register_plugin :rate_limiter, RateLimiter
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
module Plugins
-
#
-
# This plugin adds support for retrying requests when certain errors happen.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Response-Cache
-
#
-
8
module ResponseCache
-
8
CACHEABLE_VERBS = %w[GET HEAD].freeze
-
8
CACHEABLE_STATUS_CODES = [200, 203, 206, 300, 301, 410].freeze
-
8
private_constant :CACHEABLE_VERBS
-
8
private_constant :CACHEABLE_STATUS_CODES
-
-
8
class << self
-
8
def load_dependencies(*)
-
176
require_relative "response_cache/store"
-
end
-
-
8
def cacheable_request?(request)
-
248
CACHEABLE_VERBS.include?(request.verb) &&
-
(
-
248
!request.headers.key?("cache-control") || !request.headers.get("cache-control").include?("no-store")
-
)
-
end
-
-
8
def cacheable_response?(response)
-
168
response.is_a?(Response) &&
-
(
-
168
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 && (
-
133
response.headers.key?("etag") || response.headers.key?("last-modified") || response.fresh?
-
)
-
end
-
-
8
def cached_response?(response)
-
80
response.is_a?(Response) && response.status == 304
-
end
-
-
8
def extra_options(options)
-
176
options.merge(response_cache_store: Store.new)
-
end
-
end
-
-
8
module OptionsMethods
-
8
def option_response_cache_store(value)
-
176
raise TypeError, "must be an instance of #{Store}" unless value.is_a?(Store)
-
-
176
value
-
end
-
end
-
-
8
module InstanceMethods
-
8
def clear_response_cache
-
16
@options.response_cache_store.clear
-
end
-
-
8
def build_request(*)
-
80
request = super
-
80
return request unless ResponseCache.cacheable_request?(request) && @options.response_cache_store.cached?(request)
-
-
32
@options.response_cache_store.prepare(request)
-
-
32
request
-
end
-
-
8
def fetch_response(request, *)
-
277
response = super
-
-
277
return unless response
-
-
80
if ResponseCache.cached_response?(response)
-
32
log { "returning cached response for #{request.uri}" }
-
32
cached_response = @options.response_cache_store.lookup(request)
-
-
32
response.copy_from_cached(cached_response)
-
-
else
-
48
@options.response_cache_store.cache(request, response)
-
end
-
-
80
response
-
end
-
end
-
-
8
module RequestMethods
-
8
def response_cache_key
-
512
@response_cache_key ||= Digest::SHA1.hexdigest("httpx-response-cache-#{@verb}-#{@uri}")
-
end
-
end
-
-
8
module ResponseMethods
-
8
def copy_from_cached(other)
-
# 304 responses do not have content-type, which are needed for decoding.
-
32
@headers = @headers.class.new(other.headers.merge(@headers))
-
-
32
@body = other.body.dup
-
-
32
@body.rewind
-
end
-
-
# A response is fresh if its age has not yet exceeded its freshness lifetime.
-
8
def fresh?
-
256
if cache_control
-
40
return false if cache_control.include?("no-cache")
-
-
# check age: max-age
-
48
max_age = cache_control.find { |directive| directive.start_with?("s-maxage") }
-
-
48
max_age ||= cache_control.find { |directive| directive.start_with?("max-age") }
-
-
24
max_age = max_age[/age=(\d+)/, 1] if max_age
-
-
24
max_age = max_age.to_i if max_age
-
-
24
return max_age > age if max_age
-
end
-
-
# check age: expires
-
216
if @headers.key?("expires")
-
2
begin
-
24
expires = Time.httpdate(@headers["expires"])
-
rescue ArgumentError
-
8
return true
-
end
-
-
14
return (expires - Time.now).to_i.positive?
-
end
-
-
192
true
-
end
-
-
8
def cache_control
-
552
return @cache_control if defined?(@cache_control)
-
-
48
@cache_control = begin
-
384
return unless @headers.key?("cache-control")
-
-
40
@headers["cache-control"].split(/ *, */)
-
end
-
end
-
-
8
def vary
-
280
return @vary if defined?(@vary)
-
-
28
@vary = begin
-
224
return unless @headers.key?("vary")
-
-
16
@headers["vary"].split(/ *, */)
-
end
-
end
-
-
8
private
-
-
8
def age
-
24
return @headers["age"].to_i if @headers.key?("age")
-
-
24
(Time.now - date).to_i
-
end
-
-
8
def date
-
24
@date ||= Time.httpdate(@headers["date"])
-
rescue NoMethodError, ArgumentError
-
8
Time.now
-
end
-
end
-
end
-
8
register_plugin :response_cache, ResponseCache
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX::Plugins
-
8
module ResponseCache
-
8
class Store
-
8
def initialize
-
248
@store = {}
-
248
@store_mutex = Thread::Mutex.new
-
end
-
-
8
def clear
-
32
@store_mutex.synchronize { @store.clear }
-
end
-
-
8
def lookup(request)
-
312
responses = _get(request)
-
-
312
return unless responses
-
-
240
responses.find(&method(:match_by_vary?).curry(2)[request])
-
end
-
-
8
def cached?(request)
-
112
lookup(request)
-
end
-
-
8
def cache(request, response)
-
168
return unless ResponseCache.cacheable_request?(request) && ResponseCache.cacheable_response?(response)
-
-
152
_set(request, response)
-
end
-
-
8
def prepare(request)
-
80
cached_response = lookup(request)
-
-
80
return unless cached_response
-
-
56
return unless match_by_vary?(request, cached_response)
-
-
56
if !request.headers.key?("if-modified-since") && (last_modified = cached_response.headers["last-modified"])
-
32
request.headers.add("if-modified-since", last_modified)
-
end
-
-
56
if !request.headers.key?("if-none-match") && (etag = cached_response.headers["etag"]) # rubocop:disable Style/GuardClause
-
56
request.headers.add("if-none-match", etag)
-
end
-
end
-
-
8
private
-
-
8
def match_by_vary?(request, response)
-
280
vary = response.vary
-
-
280
return true unless vary
-
-
72
original_request = response.instance_variable_get(:@request)
-
-
72
return request.headers.same_headers?(original_request.headers) if vary == %w[*]
-
-
40
vary.all? do |cache_field|
-
40
cache_field.downcase!
-
40
!original_request.headers.key?(cache_field) || request.headers[cache_field] == original_request.headers[cache_field]
-
end
-
end
-
-
8
def _get(request)
-
312
@store_mutex.synchronize do
-
312
responses = @store[request.response_cache_key]
-
-
312
return unless responses
-
-
240
responses.select! do |res|
-
240
!res.body.closed? && res.fresh?
-
end
-
-
240
responses
-
end
-
end
-
-
8
def _set(request, response)
-
152
@store_mutex.synchronize do
-
152
responses = (@store[request.response_cache_key] ||= [])
-
-
152
responses.reject! do |res|
-
16
res.body.closed? || !res.fresh? || match_by_vary?(request, res)
-
end
-
-
152
responses << response
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
16
module HTTPX
-
16
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
-
#
-
16
module Retries
-
16
MAX_RETRIES = 3
-
# TODO: pass max_retries in a configure/load block
-
-
16
IDEMPOTENT_METHODS = %w[GET OPTIONS HEAD PUT DELETE].freeze
-
2
RETRYABLE_ERRORS = [
-
14
IOError,
-
EOFError,
-
Errno::ECONNRESET,
-
Errno::ECONNABORTED,
-
Errno::EPIPE,
-
Errno::EINVAL,
-
Errno::ETIMEDOUT,
-
Parser::Error,
-
TLSError,
-
TimeoutError,
-
ConnectionError,
-
Connection::HTTP2::GoawayError,
-
].freeze
-
16
DEFAULT_JITTER = ->(interval) { interval * ((rand + 1) * 0.5) }
-
-
16
if ENV.key?("HTTPX_NO_JITTER")
-
16
def self.extra_options(options)
-
671
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>).
-
16
module OptionsMethods
-
16
def option_retry_after(value)
-
# return early if callable
-
208
unless value.respond_to?(:call)
-
96
value = Float(value)
-
96
raise TypeError, ":retry_after must be positive" unless value.positive?
-
end
-
-
208
value
-
end
-
-
16
def option_retry_jitter(value)
-
# return early if callable
-
48
raise TypeError, ":retry_jitter must be callable" unless value.respond_to?(:call)
-
-
48
value
-
end
-
-
16
def option_max_retries(value)
-
2079
num = Integer(value)
-
2079
raise TypeError, ":max_retries must be positive" unless num >= 0
-
-
2079
num
-
end
-
-
16
def option_retry_change_requests(v)
-
1114
v
-
end
-
-
16
def option_retry_on(value)
-
230
raise TypeError, ":retry_on must be called with the response" unless value.respond_to?(:call)
-
-
230
value
-
end
-
end
-
-
16
module InstanceMethods
-
16
def max_retries(n)
-
96
with(max_retries: n)
-
end
-
-
16
private
-
-
16
def fetch_response(request, selector, options)
-
1395896
response = super
-
-
1395896
if response &&
-
request.retries.positive? &&
-
__repeatable_request?(request, options) &&
-
(
-
95
(
-
340
response.is_a?(ErrorResponse) && __retryable_error?(response.error)
-
) ||
-
(
-
246
options.retry_on && options.retry_on.call(response)
-
)
-
)
-
455
__try_partial_retry(request, response)
-
455
log { "failed to get response, #{request.retries} tries to go..." }
-
455
request.retries -= 1
-
455
request.transition(:idle)
-
-
455
retry_after = options.retry_after
-
455
retry_after = retry_after.call(request, response) if retry_after.respond_to?(:call)
-
-
455
if retry_after
-
# apply jitter
-
96
if (jitter = request.options.retry_jitter)
-
16
retry_after = jitter.call(retry_after)
-
end
-
-
96
retry_start = Utils.now
-
96
log { "retrying after #{retry_after} secs..." }
-
96
selector.after(retry_after) do
-
96
if request.response
-
# request has terminated abruptly meanwhile
-
request.emit(:response, request.response)
-
else
-
96
log { "retrying (elapsed time: #{Utils.elapsed_time(retry_start)})!!" }
-
96
send_request(request, selector, options)
-
end
-
end
-
else
-
359
send_request(request, selector, options)
-
end
-
-
401
return
-
end
-
1395441
response
-
end
-
-
16
def __repeatable_request?(request, options)
-
933
IDEMPOTENT_METHODS.include?(request.verb) || options.retry_change_requests
-
end
-
-
16
def __retryable_error?(ex)
-
3302
RETRYABLE_ERRORS.any? { |klass| ex.is_a?(klass) }
-
end
-
-
16
def proxy_error?(request, response, _)
-
64
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.
-
#
-
16
def __try_partial_retry(request, response)
-
455
response = response.response if response.is_a?(ErrorResponse)
-
-
455
return unless response
-
-
203
unless response.headers.key?("accept-ranges") &&
-
response.headers["accept-ranges"] == "bytes" && # there's nothing else supported though...
-
16
(original_body = response.body)
-
187
response.close if response.respond_to?(:close)
-
165
return
-
end
-
-
16
request.partial_response = response
-
-
16
size = original_body.bytesize
-
-
14
request.headers["range"] = "bytes=#{size}-"
-
end
-
end
-
-
16
module RequestMethods
-
16
attr_accessor :retries
-
-
16
attr_writer :partial_response
-
-
16
def initialize(*args)
-
691
super
-
691
@retries = @options.max_retries
-
end
-
-
16
def response=(response)
-
1162
if @partial_response
-
16
if response.is_a?(Response) && response.status == 206
-
16
response.from_partial_response(@partial_response)
-
else
-
@partial_response.close
-
end
-
16
@partial_response = nil
-
end
-
-
1162
super
-
end
-
end
-
-
16
module ResponseMethods
-
16
def from_partial_response(response)
-
16
@status = response.status
-
16
@headers = response.headers
-
16
@body = response.body
-
end
-
end
-
end
-
16
register_plugin :retries, Retries
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
class ServerSideRequestForgeryError < Error; end
-
-
8
module Plugins
-
#
-
# This plugin adds support for preventing Server-Side Request Forgery attacks.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Server-Side-Request-Forgery-Filter
-
#
-
8
module SsrfFilter
-
8
module IPAddrExtensions
-
8
refine IPAddr do
-
8
def prefixlen
-
128
mask_addr = @mask_addr
-
128
raise "Invalid mask" if mask_addr.zero?
-
-
387
mask_addr >>= 1 while (mask_addr & 0x1).zero?
-
-
128
length = 0
-
381
while mask_addr & 0x1 == 0x1
-
1771
length += 1
-
1771
mask_addr >>= 1
-
end
-
-
128
length
-
end
-
end
-
end
-
-
8
using IPAddrExtensions
-
-
# https://en.wikipedia.org/wiki/Reserved_IP_addresses
-
2
IPV4_BLACKLIST = [
-
6
IPAddr.new("0.0.0.0/8"), # Current network (only valid as source address)
-
IPAddr.new("10.0.0.0/8"), # Private network
-
IPAddr.new("100.64.0.0/10"), # Shared Address Space
-
IPAddr.new("127.0.0.0/8"), # Loopback
-
IPAddr.new("169.254.0.0/16"), # Link-local
-
IPAddr.new("172.16.0.0/12"), # Private network
-
IPAddr.new("192.0.0.0/24"), # IETF Protocol Assignments
-
IPAddr.new("192.0.2.0/24"), # TEST-NET-1, documentation and examples
-
IPAddr.new("192.88.99.0/24"), # IPv6 to IPv4 relay (includes 2002::/16)
-
IPAddr.new("192.168.0.0/16"), # Private network
-
IPAddr.new("198.18.0.0/15"), # Network benchmark tests
-
IPAddr.new("198.51.100.0/24"), # TEST-NET-2, documentation and examples
-
IPAddr.new("203.0.113.0/24"), # TEST-NET-3, documentation and examples
-
IPAddr.new("224.0.0.0/4"), # IP multicast (former Class D network)
-
IPAddr.new("240.0.0.0/4"), # Reserved (former Class E network)
-
IPAddr.new("255.255.255.255"), # Broadcast
-
].freeze
-
-
3
IPV6_BLACKLIST = ([
-
6
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|
-
128
prefixlen = ipaddr.prefixlen
-
-
128
ipv4_compatible = ipaddr.ipv4_compat.mask(96 + prefixlen)
-
128
ipv4_mapped = ipaddr.ipv4_mapped.mask(80 + prefixlen)
-
-
128
[ipv4_compatible, ipv4_mapped]
-
end).freeze
-
-
8
class << self
-
8
def extra_options(options)
-
70
options.merge(allowed_schemes: %w[https http])
-
end
-
-
8
def unsafe_ip_address?(ipaddr)
-
94
range = ipaddr.to_range
-
94
return true if range.first != range.last
-
-
110
return IPV6_BLACKLIST.any? { |r| r.include?(ipaddr) } if ipaddr.ipv6?
-
-
944
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>)
-
8
module OptionsMethods
-
8
def option_allowed_schemes(value)
-
78
Array(value)
-
end
-
end
-
-
8
module InstanceMethods
-
8
def send_requests(*requests)
-
86
responses = requests.map do |request|
-
86
next if @options.allowed_schemes.include?(request.uri.scheme)
-
-
8
error = ServerSideRequestForgeryError.new("#{request.uri} URI scheme not allowed")
-
8
error.set_backtrace(caller)
-
8
response = ErrorResponse.new(request, error)
-
8
request.emit(:response, response)
-
8
response
-
end
-
172
allowed_requests = requests.select { |req| responses[requests.index(req)].nil? }
-
86
allowed_responses = super(*allowed_requests)
-
86
allowed_responses.each_with_index do |res, idx|
-
78
req = allowed_requests[idx]
-
68
responses[requests.index(req)] = res
-
end
-
-
86
responses
-
end
-
end
-
-
8
module ConnectionMethods
-
8
def initialize(*)
-
begin
-
78
super
-
8
rescue ServerSideRequestForgeryError => e
-
# may raise when IPs are passed as options via :addresses
-
16
throw(:resolve_error, e)
-
end
-
end
-
-
8
def addresses=(addrs)
-
172
addrs = addrs.map { |addr| addr.is_a?(IPAddr) ? addr : IPAddr.new(addr) }
-
-
78
addrs.reject!(&SsrfFilter.method(:unsafe_ip_address?))
-
-
78
raise ServerSideRequestForgeryError, "#{@origin.host} has no public IP addresses" if addrs.empty?
-
-
16
super
-
end
-
end
-
end
-
-
8
register_plugin :ssrf_filter, SsrfFilter
-
end
-
end
-
# frozen_string_literal: true
-
-
14
module HTTPX
-
14
class StreamResponse
-
14
def initialize(request, session)
-
170
@request = request
-
170
@session = session
-
170
@response = nil
-
end
-
-
14
def each(&block)
-
218
return enum_for(__method__) unless block
-
-
154
@request.stream = self
-
-
13
begin
-
154
@on_chunk = block
-
-
154
if @request.response
-
# if we've already started collecting the payload, yield it first
-
# before proceeding.
-
16
body = @request.response.body
-
-
16
body.each do |chunk|
-
16
on_chunk(chunk)
-
end
-
end
-
-
154
response.raise_for_status
-
ensure
-
154
@on_chunk = nil
-
end
-
end
-
-
14
def each_line
-
108
return enum_for(__method__) unless block_given?
-
-
54
line = "".b
-
-
54
each do |chunk|
-
41
line << chunk
-
-
122
while (idx = line.index("\n"))
-
54
yield line.byteslice(0..idx - 1)
-
-
54
line = line.byteslice(idx + 1..-1)
-
end
-
end
-
-
22
yield line unless line.empty?
-
end
-
-
# This is a ghost method. It's to be used ONLY internally, when processing streams
-
14
def on_chunk(chunk)
-
213
raise NoMethodError unless @on_chunk
-
-
213
@on_chunk.call(chunk)
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<StreamResponse:#{object_id}>"
-
skipped
end
-
skipped
# :nocov:
-
-
14
def to_s
-
16
response.to_s
-
end
-
-
14
private
-
-
14
def response
-
542
return @response if @response
-
-
206
@request.response || begin
-
170
@response = @session.request(@request)
-
end
-
end
-
-
14
def respond_to_missing?(meth, *args)
-
16
response.respond_to?(meth, *args) || super
-
end
-
-
14
def method_missing(meth, *args, &block)
-
178
return super unless response.respond_to?(meth)
-
-
178
response.__send__(meth, *args, &block)
-
end
-
end
-
-
14
module Plugins
-
#
-
# This plugin adds support for stream response (text/event-stream).
-
#
-
# https://gitlab.com/os85/httpx/wikis/Stream
-
#
-
14
module Stream
-
14
def self.extra_options(options)
-
300
options.merge(timeout: { read_timeout: Float::INFINITY, operation_timeout: 60 })
-
end
-
-
14
module InstanceMethods
-
14
def request(*args, stream: false, **options)
-
474
return super(*args, **options) unless stream
-
-
186
requests = args.first.is_a?(Request) ? args : build_requests(*args, options)
-
186
raise Error, "only 1 response at a time is supported for streaming requests" unless requests.size == 1
-
-
170
request = requests.first
-
-
170
StreamResponse.new(request, self)
-
end
-
end
-
-
14
module RequestMethods
-
14
attr_accessor :stream
-
end
-
-
14
module ResponseMethods
-
14
def stream
-
282
request = @request.root_request if @request.respond_to?(:root_request)
-
282
request ||= @request
-
-
282
request.stream
-
end
-
end
-
-
14
module ResponseBodyMethods
-
14
def initialize(*)
-
282
super
-
282
@stream = @response.stream
-
end
-
-
14
def write(chunk)
-
366
return super unless @stream
-
-
221
return 0 if chunk.empty?
-
-
197
chunk = decode_chunk(chunk)
-
-
197
@stream.on_chunk(chunk.dup)
-
-
197
chunk.size
-
end
-
-
14
private
-
-
14
def transition(*)
-
183
return if @stream
-
-
183
super
-
end
-
end
-
end
-
14
register_plugin :stream, Stream
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
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
-
#
-
8
module Upgrade
-
8
class << self
-
8
def configure(klass)
-
32
klass.plugin(:"upgrade/h2")
-
end
-
-
8
def extra_options(options)
-
32
options.merge(upgrade_handlers: {})
-
end
-
end
-
-
8
module OptionsMethods
-
8
def option_upgrade_handlers(value)
-
88
raise TypeError, ":upgrade_handlers must be a Hash" unless value.is_a?(Hash)
-
-
88
value
-
end
-
end
-
-
8
module InstanceMethods
-
8
def fetch_response(request, selector, options)
-
277
response = super
-
-
277
if response
-
88
return response unless response.is_a?(Response)
-
-
88
return response unless response.headers.key?("upgrade")
-
-
32
upgrade_protocol = response.headers["upgrade"].split(/ *, */).first
-
-
32
return response unless upgrade_protocol && options.upgrade_handlers.key?(upgrade_protocol)
-
-
32
protocol_handler = options.upgrade_handlers[upgrade_protocol]
-
-
32
return response unless protocol_handler
-
-
32
log { "upgrading to #{upgrade_protocol}..." }
-
32
connection = find_connection(request.uri, selector, options)
-
-
# do not upgrade already upgraded connections
-
32
return if connection.upgrade_protocol == upgrade_protocol
-
-
32
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
-
32
return if response.status == 101 && !connection.hijacked
-
end
-
-
205
response
-
end
-
end
-
-
8
module ConnectionMethods
-
8
attr_reader :upgrade_protocol, :hijacked
-
-
8
def hijack_io
-
8
@hijacked = true
-
-
# connection is taken away from selector and not given back to the pool.
-
8
@current_session.deselect_connection(self, @current_selector, true)
-
end
-
end
-
end
-
8
register_plugin(:upgrade, Upgrade)
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
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
-
#
-
8
module H2
-
8
class << self
-
8
def extra_options(options)
-
32
options.merge(upgrade_handlers: options.upgrade_handlers.merge("h2" => self))
-
end
-
-
8
def call(connection, _request, _response)
-
8
connection.upgrade_to_h2
-
end
-
end
-
-
8
module ConnectionMethods
-
8
using URIExtensions
-
-
8
def upgrade_to_h2
-
8
prev_parser = @parser
-
-
8
if prev_parser
-
8
prev_parser.reset
-
7
@inflight -= prev_parser.requests.size
-
end
-
-
8
@parser = Connection::HTTP2.new(@write_buffer, @options)
-
8
set_parser_callbacks(@parser)
-
8
@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.
-
8
purge_after_closed
-
8
transition(:idle)
-
-
8
prev_parser.requests.each do |req|
-
req.transition(:idle)
-
send(req)
-
end
-
end
-
end
-
end
-
8
register_plugin(:"upgrade/h2", H2)
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
module Plugins
-
#
-
# This plugin implements convenience methods for performing WEBDAV requests.
-
#
-
# https://gitlab.com/os85/httpx/wikis/WebDav
-
#
-
8
module WebDav
-
8
def self.configure(klass)
-
96
klass.plugin(:xml)
-
end
-
-
8
module InstanceMethods
-
8
def copy(src, dest)
-
16
request("COPY", src, headers: { "destination" => @options.origin.merge(dest) })
-
end
-
-
8
def move(src, dest)
-
16
request("MOVE", src, headers: { "destination" => @options.origin.merge(dest) })
-
end
-
-
8
def lock(path, timeout: nil, &blk)
-
48
headers = {}
-
42
headers["timeout"] = if timeout && timeout.positive?
-
16
"Second-#{timeout}"
-
else
-
32
"Infinite, Second-4100000000"
-
end
-
48
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>"
-
48
response = request("LOCK", path, headers: headers, xml: xml)
-
-
48
return response unless response.is_a?(Response)
-
-
48
return response unless blk && response.status == 200
-
-
16
lock_token = response.headers["lock-token"]
-
-
1
begin
-
16
blk.call(response)
-
ensure
-
16
unlock(path, lock_token)
-
end
-
-
16
response
-
end
-
-
8
def unlock(path, lock_token)
-
32
request("UNLOCK", path, headers: { "lock-token" => lock_token })
-
end
-
-
8
def mkcol(dir)
-
16
request("MKCOL", dir)
-
end
-
-
8
def propfind(path, xml = nil)
-
64
body = case xml
-
when :acl
-
16
'<?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
-
32
'<?xml version="1.0" encoding="utf-8"?><DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
-
else
-
16
xml
-
end
-
-
64
request("PROPFIND", path, headers: { "depth" => "1" }, xml: body)
-
end
-
-
8
def proppatch(path, xml)
-
6
body = "<?xml version=\"1.0\"?>" \
-
12
"<D:propertyupdate xmlns:D=\"DAV:\" xmlns:Z=\"http://ns.example.com/standards/z39.50/\">#{xml}</D:propertyupdate>"
-
16
request("PROPPATCH", path, xml: body)
-
end
-
# %i[ orderpatch acl report search]
-
end
-
end
-
8
register_plugin(:webdav, WebDav)
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
module Plugins
-
#
-
# This plugin supports request XML encoding/response decoding using the nokogiri gem.
-
#
-
# https://gitlab.com/os85/httpx/wikis/XML
-
#
-
8
module XML
-
8
MIME_TYPES = %r{\b(application|text)/(.+\+)?xml\b}.freeze
-
8
module Transcoder
-
8
module_function
-
-
8
class Encoder
-
8
def initialize(xml)
-
160
@raw = xml
-
end
-
-
8
def content_type
-
160
charset = @raw.respond_to?(:encoding) && @raw.encoding ? @raw.encoding.to_s.downcase : "utf-8"
-
160
"application/xml; charset=#{charset}"
-
end
-
-
8
def bytesize
-
512
@raw.to_s.bytesize
-
end
-
-
8
def to_s
-
160
@raw.to_s
-
end
-
end
-
-
8
def encode(xml)
-
160
Encoder.new(xml)
-
end
-
-
8
def decode(response)
-
24
content_type = response.content_type.mime_type
-
-
24
raise HTTPX::Error, "invalid form mime type (#{content_type})" unless MIME_TYPES.match?(content_type)
-
-
24
Nokogiri::XML.method(:parse)
-
end
-
end
-
-
8
class << self
-
8
def load_dependencies(*)
-
144
require "nokogiri"
-
end
-
end
-
-
8
module ResponseMethods
-
# decodes the response payload into a Nokogiri::XML::Node object **if** the payload is valid
-
# "application/xml" (requires the "nokogiri" gem).
-
8
def xml
-
16
decode(Transcoder)
-
end
-
end
-
-
8
module RequestBodyClassMethods
-
# ..., xml: Nokogiri::XML::Node #=> xml encoder
-
8
def initialize_body(params)
-
592
if (xml = params.delete(:xml))
-
# @type var xml: Nokogiri::XML::Node | String
-
140
return Transcoder.encode(xml)
-
end
-
-
432
super
-
end
-
end
-
end
-
-
8
register_plugin(:xml, XML)
-
end
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
26
module ResponsePatternMatchExtensions
-
26
def deconstruct
-
41
[@status, @headers, @body]
-
end
-
-
26
def deconstruct_keys(_keys)
-
70
{ status: @status, headers: @headers, body: @body }
-
end
-
end
-
-
26
module ErrorResponsePatternMatchExtensions
-
26
def deconstruct
-
11
[@error]
-
end
-
-
26
def deconstruct_keys(_keys)
-
35
{ error: @error }
-
end
-
end
-
-
26
module HeadersPatternMatchExtensions
-
26
def deconstruct
-
7
to_a
-
end
-
end
-
-
26
Headers.include HeadersPatternMatchExtensions
-
26
Response.include ResponsePatternMatchExtensions
-
26
ErrorResponse.include ErrorResponsePatternMatchExtensions
-
end
-
# frozen_string_literal: true
-
-
26
require "httpx/selector"
-
26
require "httpx/connection"
-
26
require "httpx/resolver"
-
-
26
module HTTPX
-
26
class Pool
-
26
using ArrayExtensions::FilterMap
-
26
using URIExtensions
-
-
26
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)
-
#
-
26
def initialize(options)
-
10381
@max_connections_per_origin = options.fetch(:max_connections_per_origin, Float::INFINITY)
-
10381
@pool_timeout = options.fetch(:pool_timeout, POOL_TIMEOUT)
-
16113
@resolvers = Hash.new { |hs, resolver_type| hs[resolver_type] = [] }
-
10381
@resolver_mtx = Thread::Mutex.new
-
10381
@connections = []
-
10381
@connection_mtx = Thread::Mutex.new
-
10381
@origin_counters = Hash.new(0)
-
15552
@origin_conds = Hash.new { |hs, orig| hs[orig] = ConditionVariable.new }
-
end
-
-
26
def pop_connection
-
11103
@connection_mtx.synchronize do
-
11103
conn = @connections.shift
-
11103
@origin_conds.delete(conn.origin) if conn && (@origin_counters[conn.origin.to_s] -= 1).zero?
-
11103
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.
-
#
-
26
def checkout_connection(uri, options)
-
7567
return checkout_new_connection(uri, options) if options.io
-
-
7501
@connection_mtx.synchronize do
-
7501
acquire_connection(uri, options) || begin
-
6898
if @origin_counters[uri.origin] == @max_connections_per_origin
-
-
16
@origin_conds[uri.origin].wait(@connection_mtx, @pool_timeout)
-
-
16
return acquire_connection(uri, options) || raise(PoolTimeoutError.new(uri.origin, @pool_timeout))
-
end
-
-
6882
@origin_counters[uri.origin] += 1
-
-
6882
checkout_new_connection(uri, options)
-
end
-
end
-
end
-
-
26
def checkin_connection(connection)
-
7628
return if connection.options.io
-
-
7562
@connection_mtx.synchronize do
-
7562
@connections << connection
-
-
7562
@origin_conds[connection.origin.to_s].signal
-
end
-
end
-
-
26
def checkout_mergeable_connection(connection)
-
6841
return if connection.options.io
-
-
6841
@connection_mtx.synchronize do
-
6841
idx = @connections.find_index do |ch|
-
235
ch != connection && ch.mergeable?(connection)
-
end
-
6841
@connections.delete_at(idx) if idx
-
end
-
end
-
-
26
def reset_resolvers
-
13510
@resolver_mtx.synchronize { @resolvers.clear }
-
end
-
-
26
def checkout_resolver(options)
-
6698
resolver_type = options.resolver_class
-
6698
resolver_type = Resolver.resolver_for(resolver_type)
-
-
6698
@resolver_mtx.synchronize do
-
6698
resolvers = @resolvers[resolver_type]
-
-
6698
idx = resolvers.find_index do |res|
-
37
res.options == options
-
end
-
6698
resolvers.delete_at(idx) if idx
-
end || checkout_new_resolver(resolver_type, options)
-
end
-
-
26
def checkin_resolver(resolver)
-
353
@resolver_mtx.synchronize do
-
353
resolvers = @resolvers[resolver.class]
-
-
353
resolver = resolver.multi
-
-
353
resolvers << resolver unless resolvers.include?(resolver)
-
end
-
end
-
-
26
private
-
-
26
def acquire_connection(uri, options)
-
7517
idx = @connections.find_index do |connection|
-
831
connection.match?(uri, options)
-
end
-
-
7517
@connections.delete_at(idx) if idx
-
end
-
-
26
def checkout_new_connection(uri, options)
-
6948
options.connection_class.new(uri, options)
-
end
-
-
26
def checkout_new_resolver(resolver_type, options)
-
6670
if resolver_type.multi?
-
6645
Resolver::Multi.new(resolver_type, options)
-
else
-
25
resolver_type.new(options)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
26
module Punycode
-
26
module_function
-
-
begin
-
26
require "idnx"
-
-
25
def encode_hostname(hostname)
-
32
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
-
-
26
require "delegate"
-
26
require "forwardable"
-
-
26
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.
-
26
class Request
-
26
extend Forwardable
-
26
include Callbacks
-
26
using URIExtensions
-
-
# default value used for "user-agent" header, when not overridden.
-
26
USER_AGENT = "httpx.rb/#{VERSION}".freeze # rubocop:disable Style/RedundantFreeze
-
-
# the upcased string HTTP verb for this request.
-
26
attr_reader :verb
-
-
# the absolute URI object for this request.
-
26
attr_reader :uri
-
-
# an HTTPX::Headers object containing the request HTTP headers.
-
26
attr_reader :headers
-
-
# an HTTPX::Request::Body object containing the request body payload (or +nil+, whenn there is none).
-
26
attr_reader :body
-
-
# a symbol describing which frame is currently being flushed.
-
26
attr_reader :state
-
-
# an HTTPX::Options object containing request options.
-
26
attr_reader :options
-
-
# the corresponding HTTPX::Response object, when there is one.
-
26
attr_reader :response
-
-
# Exception raised during enumerable body writes.
-
26
attr_reader :drain_error
-
-
# The IP address from the peer server.
-
26
attr_accessor :peer_address
-
-
26
attr_writer :persistent
-
-
# will be +true+ when request body has been completely flushed.
-
26
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.
-
26
def initialize(verb, uri, options, params = EMPTY_HASH)
-
9437
@verb = verb.to_s.upcase
-
9437
@uri = Utils.to_uri(uri)
-
-
9436
@headers = options.headers.dup
-
9436
merge_headers(params.delete(:headers)) if params.key?(:headers)
-
-
9436
@headers["user-agent"] ||= USER_AGENT
-
9436
@headers["accept"] ||= "*/*"
-
-
# forego compression in the Range request case
-
9436
if @headers.key?("range")
-
8
@headers.delete("accept-encoding")
-
else
-
9428
@headers["accept-encoding"] ||= options.supported_compression_formats
-
end
-
-
9436
@query_params = params.delete(:params) if params.key?(:params)
-
-
9436
@body = options.request_body_class.new(@headers, options, **params)
-
-
9428
@options = @body.options
-
-
9428
if @uri.relative? || @uri.host.nil?
-
600
origin = @options.origin
-
600
raise(Error, "invalid URI: #{@uri}") unless origin
-
-
576
base_path = @options.base_path
-
-
576
@uri = origin.merge("#{base_path}#{@uri}")
-
end
-
-
9404
@state = :idle
-
9404
@response = nil
-
9404
@peer_address = nil
-
9404
@persistent = @options.persistent
-
end
-
-
# the read timeout defined for this requet.
-
26
def read_timeout
-
18614
@options.timeout[:read_timeout]
-
end
-
-
# the write timeout defined for this requet.
-
26
def write_timeout
-
18614
@options.timeout[:write_timeout]
-
end
-
-
# the request timeout defined for this requet.
-
26
def request_timeout
-
18330
@options.timeout[:request_timeout]
-
end
-
-
26
def persistent?
-
4668
@persistent
-
end
-
-
# if the request contains trailer headers
-
26
def trailers?
-
2846
defined?(@trailers)
-
end
-
-
# returns an instance of HTTPX::Headers containing the trailer headers
-
26
def trailers
-
88
@trailers ||= @options.headers_class.new
-
end
-
-
# returns +:r+ or +:w+, depending on whether the request is waiting for a response or flushing.
-
26
def interests
-
24195
return :r if @state == :done || @state == :expect
-
-
2903
:w
-
end
-
-
# merges +h+ into the instance of HTTPX::Headers of the request.
-
26
def merge_headers(h)
-
805
@headers = @headers.merge(h)
-
end
-
-
# the URI scheme of the request +uri+.
-
26
def scheme
-
3407
@uri.scheme
-
end
-
-
# sets the +response+ on this request.
-
26
def response=(response)
-
8836
return unless response
-
-
8836
if response.is_a?(Response) && response.status < 200
-
# deal with informational responses
-
-
160
if response.status == 100 && @headers.key?("expect")
-
136
@informational_status = response.status
-
136
return
-
end
-
-
# 103 Early Hints advertises resources in document to browsers.
-
# not very relevant for an HTTP client, discard.
-
24
return if response.status >= 103
-
end
-
-
8700
@response = response
-
-
8700
emit(:response_started, response)
-
end
-
-
# returnns the URI path of the request +uri+.
-
26
def path
-
8269
path = uri.path.dup
-
8269
path = +"" if path.nil?
-
8269
path << "/" if path.empty?
-
8269
path << "?#{query}" unless query.empty?
-
8269
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"
-
26
def authority
-
8315
@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"
-
26
def origin
-
3687
@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"
-
26
def query
-
9182
return @query if defined?(@query)
-
-
7684
query = []
-
7684
if (q = @query_params)
-
152
query << Transcoder::Form.encode(q)
-
end
-
7684
query << @uri.query if @uri.query
-
7684
@query = query.join("&")
-
end
-
-
# consumes and returns the next available chunk of request body that can be sent
-
26
def drain_body
-
8902
return nil if @body.nil?
-
-
8902
@drainer ||= @body.each
-
8902
chunk = @drainer.next.dup
-
-
6003
emit(:body_chunk, chunk)
-
6003
chunk
-
rescue StopIteration
-
2887
nil
-
rescue StandardError => e
-
12
@drain_error = e
-
12
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)
-
26
def transition(nextstate)
-
34024
case nextstate
-
when :idle
-
694
@body.rewind
-
694
@response = nil
-
694
@drainer = nil
-
when :headers
-
10356
return unless @state == :idle
-
when :body
-
10340
return unless @state == :headers ||
-
@state == :expect
-
-
8422
if @headers.key?("expect")
-
499
if @informational_status && @informational_status == 100
-
# check for 100 Continue response, and deallocate the var
-
# if @informational_status == 100
-
# @response = nil
-
# end
-
else
-
371
return if @state == :expect # do not re-set it
-
-
144
nextstate = :expect
-
end
-
end
-
when :trailers
-
8406
return unless @state == :body
-
when :done
-
8414
return if @state == :expect
-
end
-
33026
@state = nextstate
-
33026
emit(@state, self)
-
13472
nil
-
end
-
-
# whether the request supports the 100-continue handshake and already processed the 100 response.
-
26
def expects?
-
7760
@headers["expect"] == "100-continue" && @informational_status == 100 && !@response
-
end
-
end
-
end
-
-
26
require_relative "request/body"
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
# Implementation of the HTTP Request body as a delegator which iterates (responds to +each+) payload chunks.
-
26
class Request::Body < SimpleDelegator
-
26
class << self
-
26
def new(_, options, body: nil, **params)
-
9444
if body.is_a?(self)
-
# request derives its options from body
-
16
body.options = options.merge(params)
-
14
return body
-
end
-
-
9428
super
-
end
-
end
-
-
26
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
-
26
def initialize(h, options, **params)
-
9428
@headers = h
-
9428
@body = self.class.initialize_body(params)
-
9428
@options = options.merge(params)
-
-
9428
if @body
-
3014
if @options.compress_request_body && @headers.key?("content-encoding")
-
-
96
@headers.get("content-encoding").each do |encoding|
-
96
@body = self.class.initialize_deflater_body(@body, encoding)
-
end
-
end
-
-
3014
@headers["content-type"] ||= @body.content_type
-
3014
@headers["content-length"] = @body.bytesize unless unbounded_body?
-
end
-
-
9420
super(@body)
-
end
-
-
# consumes and yields the request payload in chunks.
-
26
def each(&block)
-
6062
return enum_for(__method__) unless block
-
3035
return if @body.nil?
-
-
2963
body = stream(@body)
-
2963
if body.respond_to?(:read)
-
1233
::IO.copy_stream(body, ProcIO.new(block))
-
1729
elsif body.respond_to?(:each)
-
406
body.each(&block)
-
else
-
1324
block[body.to_s]
-
end
-
end
-
-
# if the +@body+ is rewindable, it rewinnds it.
-
26
def rewind
-
758
return if empty?
-
-
160
@body.rewind if @body.respond_to?(:rewind)
-
end
-
-
# return +true+ if the +body+ has been fully drained (or does nnot exist).
-
26
def empty?
-
18261
return true if @body.nil?
-
8079
return false if chunked?
-
-
7983
@body.bytesize.zero?
-
end
-
-
# returns the +@body+ payload size in bytes.
-
26
def bytesize
-
3278
return 0 if @body.nil?
-
-
128
@body.bytesize
-
end
-
-
# sets the body to yield using chunked trannsfer encoding format.
-
26
def stream(body)
-
2963
return body unless chunked?
-
-
96
Transcoder::Chunker.encode(body.enum_for(:each))
-
end
-
-
# returns whether the body yields infinitely.
-
26
def unbounded_body?
-
3676
return @unbounded_body if defined?(@unbounded_body)
-
-
3086
@unbounded_body = !@body.nil? && (chunked? || @body.bytesize == Float::INFINITY)
-
end
-
-
# returns whether the chunked transfer encoding header is set.
-
26
def chunked?
-
18924
@headers["transfer-encoding"] == "chunked"
-
end
-
-
# sets the chunked transfer encoding header.
-
26
def chunk!
-
32
@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:
-
-
26
class << self
-
26
def initialize_body(params)
-
9268
if (body = params.delete(:body))
-
# @type var body: bodyIO
-
1266
Transcoder::Body.encode(body)
-
8002
elsif (form = params.delete(:form))
-
# @type var form: Transcoder::urlencoded_input
-
1505
Transcoder::Form.encode(form)
-
6497
elsif (json = params.delete(:json))
-
# @type var body: _ToJson
-
83
Transcoder::JSON.encode(json)
-
end
-
end
-
-
# returns the +body+ wrapped with the correct deflater accordinng to the given +encodisng+.
-
26
def initialize_deflater_body(body, encoding)
-
87
case encoding
-
when "gzip"
-
48
Transcoder::GZIP.encode(body)
-
when "deflate"
-
24
Transcoder::Deflate.encode(body)
-
when "identity"
-
16
body
-
else
-
8
body
-
end
-
end
-
end
-
end
-
-
# Wrapper yielder which can be used with functions which expect an IO writer.
-
26
class ProcIO
-
26
def initialize(block)
-
1233
@block = block
-
end
-
-
# Implementation the IO write protocol, which yield the given chunk to +@block+.
-
26
def write(data)
-
3369
@block.call(data.dup)
-
3361
data.bytesize
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "resolv"
-
26
require "ipaddr"
-
-
26
module HTTPX
-
26
module Resolver
-
26
RESOLVE_TIMEOUT = [2, 3].freeze
-
-
26
require "httpx/resolver/resolver"
-
26
require "httpx/resolver/system"
-
26
require "httpx/resolver/native"
-
26
require "httpx/resolver/https"
-
26
require "httpx/resolver/multi"
-
-
26
@lookup_mutex = Thread::Mutex.new
-
198
@lookups = Hash.new { |h, k| h[k] = [] }
-
-
26
@identifier_mutex = Thread::Mutex.new
-
26
@identifier = 1
-
26
@system_resolver = Resolv::Hosts.new
-
-
26
module_function
-
-
26
def resolver_for(resolver_type)
-
5979
case resolver_type
-
6561
when :native then Native
-
33
when :system then System
-
74
when :https then HTTPS
-
else
-
76
return resolver_type if resolver_type.is_a?(Class) && resolver_type < Resolver
-
-
8
raise Error, "unsupported resolver type (#{resolver_type})"
-
end
-
end
-
-
26
def nolookup_resolve(hostname)
-
6549
ip_resolve(hostname) || cached_lookup(hostname) || system_resolve(hostname)
-
end
-
-
26
def ip_resolve(hostname)
-
6549
[IPAddr.new(hostname)]
-
rescue ArgumentError
-
end
-
-
26
def system_resolve(hostname)
-
545
ips = @system_resolver.getaddresses(hostname)
-
545
return if ips.empty?
-
-
663
ips.map { |ip| IPAddr.new(ip) }
-
rescue IOError
-
end
-
-
26
def cached_lookup(hostname)
-
6020
now = Utils.now
-
6020
lookup_synchronize do |lookups|
-
6020
lookup(hostname, lookups, now)
-
end
-
end
-
-
26
def cached_lookup_set(hostname, family, entries)
-
242
now = Utils.now
-
242
entries.each do |entry|
-
304
entry["TTL"] += now
-
end
-
242
lookup_synchronize do |lookups|
-
215
case family
-
when Socket::AF_INET6
-
40
lookups[hostname].concat(entries)
-
when Socket::AF_INET
-
202
lookups[hostname].unshift(*entries)
-
end
-
242
entries.each do |entry|
-
304
next unless entry["name"] != hostname
-
-
26
case family
-
when Socket::AF_INET6
-
8
lookups[entry["name"]] << entry
-
when Socket::AF_INET
-
20
lookups[entry["name"]].unshift(entry)
-
end
-
end
-
end
-
end
-
-
# do not use directly!
-
26
def lookup(hostname, lookups, ttl)
-
6028
return unless lookups.key?(hostname)
-
-
5483
entries = lookups[hostname] = lookups[hostname].select do |address|
-
16004
address["TTL"] > ttl
-
end
-
-
5483
ips = entries.flat_map do |address|
-
15983
if address.key?("alias")
-
8
lookup(address["alias"], lookups, ttl)
-
else
-
15975
IPAddr.new(address["data"])
-
end
-
end.compact
-
-
5483
ips unless ips.empty?
-
end
-
-
26
def generate_id
-
1560
id_synchronize { @identifier = (@identifier + 1) & 0xFFFF }
-
end
-
-
26
def encode_dns_query(hostname, type: Resolv::DNS::Resource::IN::A, message_id: generate_id)
-
725
Resolv::DNS::Message.new(message_id).tap do |query|
-
780
query.rd = 1
-
780
query.add_question(hostname, type)
-
109
end.encode
-
end
-
-
26
def decode_dns_answer(payload)
-
54
begin
-
714
message = Resolv::DNS::Message.decode(payload)
-
rescue Resolv::DNS::DecodeError => e
-
6
return :decode_error, e
-
end
-
-
# no domain was found
-
708
return :no_domain_found if message.rcode == Resolv::DNS::RCode::NXDomain
-
-
288
return :message_truncated if message.tc == 1
-
-
276
return :dns_error, message.rcode if message.rcode != Resolv::DNS::RCode::NoError
-
-
264
addresses = []
-
-
264
message.each_answer do |question, _, value|
-
1040
case value
-
when Resolv::DNS::Resource::IN::CNAME
-
20
addresses << {
-
"name" => question.to_s,
-
"TTL" => value.ttl,
-
"alias" => value.name.to_s,
-
}
-
when Resolv::DNS::Resource::IN::A,
-
Resolv::DNS::Resource::IN::AAAA
-
1046
addresses << {
-
24
"name" => question.to_s,
-
"TTL" => value.ttl,
-
"data" => value.address.to_s,
-
}
-
end
-
end
-
-
264
[:ok, addresses]
-
end
-
-
26
def lookup_synchronize
-
12524
@lookup_mutex.synchronize { yield(@lookups) }
-
end
-
-
26
def id_synchronize(&block)
-
780
@identifier_mutex.synchronize(&block)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "resolv"
-
26
require "uri"
-
26
require "cgi"
-
26
require "forwardable"
-
26
require "httpx/base64"
-
-
26
module HTTPX
-
26
class Resolver::HTTPS < Resolver::Resolver
-
26
extend Forwardable
-
26
using URIExtensions
-
-
26
module DNSExtensions
-
26
refine Resolv::DNS do
-
26
def generate_candidates(name)
-
42
@config.generate_candidates(name)
-
end
-
end
-
end
-
26
using DNSExtensions
-
-
26
NAMESERVER = "https://1.1.1.1/dns-query"
-
-
2
DEFAULTS = {
-
24
uri: NAMESERVER,
-
use_get: false,
-
}.freeze
-
-
26
def_delegators :@resolver_connection, :state, :connecting?, :to_io, :call, :close, :terminate, :inflight?
-
-
26
def initialize(_, options)
-
90
super
-
90
@resolver_options = DEFAULTS.merge(@options.resolver_options)
-
90
@queries = {}
-
90
@requests = {}
-
90
@connections = []
-
90
@uri = URI(@resolver_options[:uri])
-
90
@uri_addresses = nil
-
90
@resolver = Resolv::DNS.new
-
90
@resolver.timeouts = @resolver_options.fetch(:timeouts, Resolver::RESOLVE_TIMEOUT)
-
90
@resolver.lazy_initialize
-
end
-
-
26
def <<(connection)
-
90
return if @uri.origin == connection.peer.to_s
-
-
48
@uri_addresses ||= HTTPX::Resolver.nolookup_resolve(@uri.host) || @resolver.getaddresses(@uri.host)
-
-
48
if @uri_addresses.empty?
-
6
ex = ResolveError.new("Can't resolve DNS server #{@uri.host}")
-
6
ex.set_backtrace(caller)
-
6
connection.force_reset
-
6
throw(:resolve_error, ex)
-
end
-
-
42
resolve(connection)
-
end
-
-
26
def closed?
-
true
-
end
-
-
26
def empty?
-
84
true
-
end
-
-
26
def resolver_connection
-
# TODO: leaks connection object into the pool
-
66
@resolver_connection ||= @current_session.find_connection(@uri, @current_selector,
-
@options.merge(ssl: { alpn_protocols: %w[h2] })).tap do |conn|
-
42
emit_addresses(conn, @family, @uri_addresses) unless conn.addresses
-
end
-
end
-
-
26
private
-
-
26
def resolve(connection = @connections.first, hostname = nil)
-
66
return unless connection
-
-
66
hostname ||= @queries.key(connection)
-
-
66
if hostname.nil?
-
42
hostname = connection.peer.host
-
log do
-
"resolver #{FAMILY_TYPES[@record_type]}: resolve IDN #{connection.peer.non_ascii_hostname} as #{hostname}"
-
42
end if connection.peer.non_ascii_hostname
-
-
42
hostname = @resolver.generate_candidates(hostname).each do |name|
-
126
@queries[name.to_s] = connection
-
end.first.to_s
-
else
-
24
@queries[hostname] = connection
-
end
-
66
log { "resolver #{FAMILY_TYPES[@record_type]}: query for #{hostname}" }
-
-
begin
-
66
request = build_request(hostname)
-
66
request.on(:response, &method(:on_response).curry(2)[request])
-
66
request.on(:promise, &method(:on_promise))
-
66
@requests[request] = hostname
-
66
resolver_connection.send(request)
-
66
@connections << connection
-
rescue ResolveError, Resolv::DNS::EncodeError => e
-
reset_hostname(hostname)
-
emit_resolve_error(connection, connection.peer.host, e)
-
end
-
end
-
-
26
def on_response(request, response)
-
66
response.raise_for_status
-
rescue StandardError => e
-
6
hostname = @requests.delete(request)
-
6
connection = reset_hostname(hostname)
-
6
emit_resolve_error(connection, connection.peer.host, e)
-
else
-
# @type var response: HTTPX::Response
-
60
parse(request, response)
-
ensure
-
66
@requests.delete(request)
-
end
-
-
26
def on_promise(_, stream)
-
log(level: 2) { "#{stream.id}: refusing stream!" }
-
stream.refuse
-
end
-
-
26
def parse(request, response)
-
60
code, result = decode_response_body(response)
-
-
60
case code
-
when :ok
-
18
parse_addresses(result, request)
-
when :no_domain_found
-
# Indicates no such domain was found.
-
-
36
host = @requests.delete(request)
-
36
connection = reset_hostname(host, reset_candidates: false)
-
-
36
unless @queries.value?(connection)
-
12
emit_resolve_error(connection)
-
12
return
-
end
-
-
24
resolve
-
when :dns_error
-
host = @requests.delete(request)
-
connection = reset_hostname(host)
-
-
emit_resolve_error(connection)
-
when :decode_error
-
6
host = @requests.delete(request)
-
6
connection = reset_hostname(host)
-
6
emit_resolve_error(connection, connection.peer.host, result)
-
end
-
end
-
-
26
def parse_addresses(answers, request)
-
18
if answers.empty?
-
# no address found, eliminate candidates
-
host = @requests.delete(request)
-
connection = reset_hostname(host)
-
emit_resolve_error(connection)
-
return
-
-
else
-
42
answers = answers.group_by { |answer| answer["name"] }
-
18
answers.each do |hostname, addresses|
-
24
addresses = addresses.flat_map do |address|
-
24
if address.key?("alias")
-
6
alias_address = answers[address["alias"]]
-
6
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
-
6
alias_address
-
end
-
else
-
18
address
-
end
-
end.compact
-
24
next if addresses.empty?
-
-
24
hostname.delete_suffix!(".") if hostname.end_with?(".")
-
24
connection = reset_hostname(hostname, reset_candidates: false)
-
24
next unless connection # probably a retried query for which there's an answer
-
-
18
@connections.delete(connection)
-
-
# eliminate other candidates
-
54
@queries.delete_if { |_, conn| connection == conn }
-
-
18
Resolver.cached_lookup_set(hostname, @family, addresses) if @resolver_options[:cache]
-
54
catch(:coalesced) { emit_addresses(connection, @family, addresses.map { |addr| addr["data"] }) }
-
end
-
end
-
18
return if @connections.empty?
-
-
resolve
-
end
-
-
26
def build_request(hostname)
-
60
uri = @uri.dup
-
60
rklass = @options.request_class
-
60
payload = Resolver.encode_dns_query(hostname, type: @record_type)
-
-
60
if @resolver_options[:use_get]
-
6
params = URI.decode_www_form(uri.query.to_s)
-
6
params << ["type", FAMILY_TYPES[@record_type]]
-
6
params << ["dns", Base64.urlsafe_encode64(payload, padding: false)]
-
6
uri.query = URI.encode_www_form(params)
-
6
request = rklass.new("GET", uri, @options)
-
else
-
54
request = rklass.new("POST", uri, @options, body: [payload])
-
54
request.headers["content-type"] = "application/dns-message"
-
end
-
60
request.headers["accept"] = "application/dns-message"
-
60
request
-
end
-
-
26
def decode_response_body(response)
-
54
case response.headers["content-type"]
-
when "application/dns-udpwireformat",
-
"application/dns-message"
-
54
Resolver.decode_dns_answer(response.to_s)
-
else
-
raise Error, "unsupported DNS mime-type (#{response.headers["content-type"]})"
-
end
-
end
-
-
26
def reset_hostname(hostname, reset_candidates: true)
-
72
connection = @queries.delete(hostname)
-
-
72
return connection unless connection && reset_candidates
-
-
# eliminate other candidates
-
36
candidates = @queries.select { |_, conn| connection == conn }.keys
-
36
@queries.delete_if { |h, _| candidates.include?(h) }
-
-
12
connection
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "forwardable"
-
26
require "resolv"
-
-
26
module HTTPX
-
26
class Resolver::Multi
-
26
include Callbacks
-
26
using ArrayExtensions::FilterMap
-
-
26
attr_reader :resolvers, :options
-
-
26
def initialize(resolver_type, options)
-
6645
@current_selector = nil
-
6645
@current_session = nil
-
6645
@options = options
-
6645
@resolver_options = @options.resolver_options
-
-
6645
@resolvers = options.ip_families.map do |ip_family|
-
6645
resolver = resolver_type.new(ip_family, options)
-
6645
resolver.multi = self
-
6645
resolver
-
end
-
-
6645
@errors = Hash.new { |hs, k| hs[k] = [] }
-
end
-
-
26
def current_selector=(s)
-
6673
@current_selector = s
-
13346
@resolvers.each { |r| r.__send__(__method__, s) }
-
end
-
-
26
def current_session=(s)
-
6673
@current_session = s
-
13346
@resolvers.each { |r| r.__send__(__method__, s) }
-
end
-
-
26
def closed?
-
@resolvers.all?(&:closed?)
-
end
-
-
26
def empty?
-
@resolvers.all?(&:empty?)
-
end
-
-
26
def inflight?
-
@resolvers.any(&:inflight?)
-
end
-
-
26
def timeout
-
@resolvers.filter_map(&:timeout).min
-
end
-
-
26
def close
-
@resolvers.each(&:close)
-
end
-
-
26
def connections
-
@resolvers.filter_map { |r| r.resolver_connection if r.respond_to?(:resolver_connection) }
-
end
-
-
26
def early_resolve(connection)
-
6675
hostname = connection.peer.host
-
6675
addresses = @resolver_options[:cache] && (connection.addresses || HTTPX::Resolver.nolookup_resolve(hostname))
-
6675
return false unless addresses
-
-
6224
resolved = false
-
6445
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.
-
12858
resolver = @resolvers.find { |r| r.family == family } || @resolvers.first
-
-
6429
next unless resolver # this should ever happen
-
-
# it does not matter which resolver it is, as early-resolve code is shared.
-
6429
resolver.emit_addresses(connection, family, addrs, true)
-
-
6390
resolved = true
-
end
-
-
6185
resolved
-
end
-
-
26
def lazy_resolve(connection)
-
451
@resolvers.each do |resolver|
-
451
resolver << @current_session.try_clone_connection(connection, @current_selector, resolver.family)
-
439
next if resolver.empty?
-
-
355
@current_session.select_resolver(resolver, @current_selector)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "forwardable"
-
26
require "resolv"
-
-
26
module HTTPX
-
26
class Resolver::Native < Resolver::Resolver
-
26
extend Forwardable
-
26
using URIExtensions
-
-
16
DEFAULTS = {
-
10
nameserver: nil,
-
**Resolv::DNS::Config.default_config_hash,
-
packet_size: 512,
-
timeouts: Resolver::RESOLVE_TIMEOUT,
-
}.freeze
-
-
26
DNS_PORT = 53
-
-
26
def_delegator :@connections, :empty?
-
-
26
attr_reader :state
-
-
26
def initialize(family, options)
-
6555
super
-
6555
@ns_index = 0
-
6555
@resolver_options = DEFAULTS.merge(@options.resolver_options)
-
6555
@socket_type = @resolver_options.fetch(:socket_type, :udp)
-
6555
@nameserver = if (nameserver = @resolver_options[:nameserver])
-
6549
nameserver = nameserver[family] if nameserver.is_a?(Hash)
-
6549
Array(nameserver)
-
end
-
6555
@ndots = @resolver_options.fetch(:ndots, 1)
-
19665
@search = Array(@resolver_options[:search]).map { |srch| srch.scan(/[^.]+/) }
-
6555
@_timeouts = Array(@resolver_options[:timeouts])
-
8101
@timeouts = Hash.new { |timeouts, host| timeouts[host] = @_timeouts.dup }
-
6555
@connections = []
-
6555
@queries = {}
-
6555
@read_buffer = "".b
-
6555
@write_buffer = Buffer.new(@resolver_options[:packet_size])
-
6555
@state = :idle
-
end
-
-
26
def close
-
353
transition(:closed)
-
end
-
-
26
def closed?
-
706
@state == :closed
-
end
-
-
26
def to_io
-
1229
@io.to_io
-
end
-
-
26
def call
-
1005
case @state
-
when :open
-
1085
consume
-
end
-
305
nil
-
rescue Errno::EHOSTUNREACH => e
-
18
@ns_index += 1
-
18
nameserver = @nameserver
-
18
if nameserver && @ns_index < nameserver.size
-
12
log do
-
"resolver #{FAMILY_TYPES[@record_type]}: " \
-
"failed resolving on nameserver #{@nameserver[@ns_index - 1]} (#{e.message})"
-
end
-
12
transition(:idle)
-
12
@timeouts.clear
-
else
-
6
handle_error(e)
-
end
-
rescue NativeResolveError => e
-
24
handle_error(e)
-
end
-
-
26
def interests
-
5132
case @state
-
when :idle
-
4405
transition(:open)
-
when :closed
-
12
transition(:idle)
-
12
transition(:open)
-
end
-
-
5219
calculate_interests
-
end
-
-
26
def <<(connection)
-
361
if @nameserver.nil?
-
6
ex = ResolveError.new("No available nameserver")
-
6
ex.set_backtrace(caller)
-
6
connection.force_reset
-
6
throw(:resolve_error, ex)
-
else
-
355
@connections << connection
-
355
resolve
-
end
-
end
-
-
26
def timeout
-
5219
return if @connections.empty?
-
-
5219
@start_timeout = Utils.now
-
5219
hosts = @queries.keys
-
5219
@timeouts.values_at(*hosts).reject(&:empty?).map(&:first).min
-
end
-
-
26
def handle_socket_timeout(interval)
-
96
do_retry(interval)
-
end
-
-
26
private
-
-
26
def calculate_interests
-
7233
return :w unless @write_buffer.empty?
-
-
5681
return :r unless @queries.empty?
-
-
591
nil
-
end
-
-
26
def consume
-
1067
dread if calculate_interests == :r
-
947
do_retry
-
947
dwrite if calculate_interests == :w
-
end
-
-
26
def do_retry(loop_time = nil)
-
1043
return if @queries.empty? || !@start_timeout
-
-
810
loop_time ||= Utils.elapsed_time(@start_timeout)
-
-
810
query = @queries.first
-
-
810
return unless query
-
-
810
h, connection = query
-
810
host = connection.peer.host
-
810
timeout = (@timeouts[host][0] -= loop_time)
-
-
810
return unless timeout <= 0
-
-
72
elapsed_after = @_timeouts[@_timeouts.size - @timeouts[host].size]
-
72
@timeouts[host].shift
-
-
72
if !@timeouts[host].empty?
-
42
log do
-
"resolver #{FAMILY_TYPES[@record_type]}: timeout after #{elapsed_after}s, retry (with #{@timeouts[host].first}s) #{host}..."
-
end
-
# must downgrade to tcp AND retry on same host as last
-
42
downgrade_socket
-
42
resolve(connection, h)
-
30
elsif @ns_index + 1 < @nameserver.size
-
# try on the next nameserver
-
6
@ns_index += 1
-
6
log do
-
"resolver #{FAMILY_TYPES[@record_type]}: failed resolving #{host} on nameserver #{@nameserver[@ns_index - 1]} (timeout error)"
-
end
-
6
transition(:idle)
-
6
@timeouts.clear
-
6
resolve(connection, h)
-
else
-
-
24
@timeouts.delete(host)
-
24
reset_hostname(h, reset_candidates: false)
-
-
24
return unless @queries.empty?
-
-
6
@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.
-
6
ex = ResolveTimeoutError.new(loop_time, "Timed out while resolving #{connection.peer.host}")
-
6
ex.set_backtrace(ex ? ex.backtrace : caller)
-
6
emit_resolve_error(connection, host, ex)
-
6
emit(:close, self)
-
end
-
end
-
-
26
def dread(wsize = @resolver_options[:packet_size])
-
660
loop do
-
973
wsize = @large_packet.capacity if @large_packet
-
-
973
siz = @io.read(wsize, @read_buffer)
-
-
973
unless siz
-
ex = EOFError.new("descriptor closed")
-
ex.set_backtrace(caller)
-
raise ex
-
end
-
-
973
return unless siz.positive?
-
-
672
if @socket_type == :tcp
-
# packet may be incomplete, need to keep draining from the socket
-
30
if @large_packet
-
# large packet buffer already exists, continue pumping
-
12
@large_packet << @read_buffer
-
-
12
next unless @large_packet.full?
-
-
12
parse(@large_packet.to_s)
-
12
@large_packet = nil
-
# downgrade to udp again
-
12
downgrade_socket
-
12
return
-
else
-
18
size = @read_buffer[0, 2].unpack1("n")
-
18
buffer = @read_buffer.byteslice(2..-1)
-
-
18
if size > @read_buffer.bytesize
-
# only do buffer logic if it's worth it, and the whole packet isn't here already
-
12
@large_packet = Buffer.new(size)
-
12
@large_packet << buffer
-
-
12
next
-
else
-
6
parse(buffer)
-
end
-
end
-
else # udp
-
642
parse(@read_buffer)
-
end
-
-
528
return if @state == :closed
-
end
-
end
-
-
26
def dwrite
-
714
loop do
-
1428
return if @write_buffer.empty?
-
-
714
siz = @io.write(@write_buffer)
-
-
714
unless siz
-
ex = EOFError.new("descriptor closed")
-
ex.set_backtrace(caller)
-
raise ex
-
end
-
-
714
return unless siz.positive?
-
-
714
return if @state == :closed
-
end
-
end
-
-
26
def parse(buffer)
-
660
code, result = Resolver.decode_dns_answer(buffer)
-
-
604
case code
-
when :ok
-
246
parse_addresses(result)
-
when :no_domain_found
-
# Indicates no such domain was found.
-
384
hostname, connection = @queries.first
-
384
reset_hostname(hostname, reset_candidates: false)
-
-
384
unless @queries.value?(connection)
-
96
@connections.delete(connection)
-
96
ex = NativeResolveError.new(connection, connection.peer.host, "name or service not known")
-
96
ex.set_backtrace(ex ? ex.backtrace : caller)
-
96
emit_resolve_error(connection, connection.peer.host, ex)
-
96
emit(:close, self)
-
end
-
-
384
resolve
-
when :message_truncated
-
# TODO: what to do if it's already tcp??
-
12
return if @socket_type == :tcp
-
-
12
@socket_type = :tcp
-
-
12
hostname, _ = @queries.first
-
12
reset_hostname(hostname)
-
12
transition(:closed)
-
when :dns_error
-
12
hostname, connection = @queries.first
-
12
reset_hostname(hostname)
-
12
@connections.delete(connection)
-
12
ex = NativeResolveError.new(connection, connection.peer.host, "unknown DNS error (error code #{result})")
-
12
raise ex
-
when :decode_error
-
6
hostname, connection = @queries.first
-
6
reset_hostname(hostname)
-
6
@connections.delete(connection)
-
6
ex = NativeResolveError.new(connection, connection.peer.host, result.message)
-
6
ex.set_backtrace(result.backtrace)
-
6
raise ex
-
end
-
end
-
-
26
def parse_addresses(addresses)
-
246
if addresses.empty?
-
# no address found, eliminate candidates
-
6
hostname, connection = @queries.first
-
6
reset_hostname(hostname)
-
6
@connections.delete(connection)
-
6
raise NativeResolveError.new(connection, connection.peer.host)
-
else
-
240
address = addresses.first
-
240
name = address["name"]
-
-
240
connection = @queries.delete(name)
-
-
240
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
-
-
240
if address.key?("alias") # CNAME
-
18
hostname_alias = address["alias"]
-
# clean up intermediate queries
-
18
@timeouts.delete(name) unless connection.peer.host == name
-
-
18
if early_resolve(connection, hostname: hostname_alias)
-
1
@connections.delete(connection)
-
else
-
17
if @socket_type == :tcp
-
# must downgrade to udp if tcp
-
6
@socket_type = @resolver_options.fetch(:socket_type, :udp)
-
6
transition(:idle)
-
6
transition(:open)
-
end
-
17
log { "resolver #{FAMILY_TYPES[@record_type]}: ALIAS #{hostname_alias} for #{name}" }
-
17
resolve(connection, hostname_alias)
-
17
return
-
end
-
else
-
222
reset_hostname(name, connection: connection)
-
222
@timeouts.delete(connection.peer.host)
-
222
@connections.delete(connection)
-
222
Resolver.cached_lookup_set(connection.peer.host, @family, addresses) if @resolver_options[:cache]
-
1082
catch(:coalesced) { emit_addresses(connection, @family, addresses.map { |addr| addr["data"] }) }
-
end
-
end
-
223
return emit(:close, self) if @connections.empty?
-
-
2
resolve
-
end
-
-
26
def resolve(connection = @connections.first, hostname = nil)
-
818
raise Error, "no URI to resolve" unless connection
-
-
722
return unless @write_buffer.empty?
-
-
720
hostname ||= @queries.key(connection)
-
-
720
if hostname.nil?
-
367
hostname = connection.peer.host
-
log do
-
"resolver #{FAMILY_TYPES[@record_type]}: " \
-
"resolve IDN #{connection.peer.non_ascii_hostname} as #{hostname}"
-
366
end if connection.peer.non_ascii_hostname
-
-
367
hostname = generate_candidates(hostname).each do |name|
-
1352
@queries[name] = connection
-
end.first
-
else
-
325
@queries[hostname] = connection
-
end
-
720
log { "resolver #{FAMILY_TYPES[@record_type]}: query for #{hostname}" }
-
54
begin
-
720
@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
-
-
26
def encode_dns_query(hostname)
-
720
message_id = Resolver.generate_id
-
720
msg = Resolver.encode_dns_query(hostname, type: @record_type, message_id: message_id)
-
720
msg[0, 2] = [msg.size, message_id].pack("nn") if @socket_type == :tcp
-
720
msg
-
end
-
-
26
def generate_candidates(name)
-
367
return [name] if name.end_with?(".")
-
-
367
candidates = []
-
367
name_parts = name.scan(/[^.]+/)
-
367
candidates = [name] if @ndots <= name_parts.size - 1
-
1101
candidates.concat(@search.map { |domain| [*name_parts, *domain].join(".") })
-
367
fname = "#{name}."
-
367
candidates << fname unless candidates.include?(fname)
-
-
367
candidates
-
end
-
-
26
def build_socket
-
395
ip, port = @nameserver[@ns_index]
-
395
port ||= DNS_PORT
-
-
366
case @socket_type
-
when :udp
-
377
log { "resolver #{FAMILY_TYPES[@record_type]}: server: udp://#{ip}:#{port}..." }
-
377
UDP.new(ip, port, @options)
-
when :tcp
-
18
log { "resolver #{FAMILY_TYPES[@record_type]}: server: tcp://#{ip}:#{port}..." }
-
18
origin = URI("tcp://#{ip}:#{port}")
-
18
TCP.new(origin, [ip], @options)
-
end
-
end
-
-
26
def downgrade_socket
-
54
return unless @socket_type == :tcp
-
-
6
@socket_type = @resolver_options.fetch(:socket_type, :udp)
-
6
transition(:idle)
-
6
transition(:open)
-
end
-
-
26
def transition(nextstate)
-
4778
case nextstate
-
when :idle
-
42
if @io
-
42
@io.close
-
42
@io = nil
-
end
-
when :open
-
4429
return unless @state == :idle
-
-
4429
@io ||= build_socket
-
-
4429
@io.connect
-
4429
return unless @io.connected?
-
-
395
resolve if @queries.empty? && !@connections.empty?
-
when :closed
-
365
return unless @state == :open
-
-
365
@io.close if @io
-
365
@start_timeout = nil
-
365
@write_buffer.clear
-
365
@read_buffer.clear
-
end
-
802
@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
-
-
26
def handle_error(error)
-
30
if error.respond_to?(:connection) &&
-
error.respond_to?(:host)
-
24
reset_hostname(error.host, connection: error.connection)
-
24
@connections.delete(error.connection)
-
24
emit_resolve_error(error.connection, error.host, error)
-
else
-
6
@queries.each do |host, connection|
-
6
reset_hostname(host, connection: connection)
-
6
@connections.delete(connection)
-
6
emit_resolve_error(connection, host, error)
-
end
-
end
-
30
emit(:close, self) if @connections.empty?
-
end
-
-
26
def reset_hostname(hostname, connection: @queries.delete(hostname), reset_candidates: true)
-
696
@timeouts.delete(hostname)
-
696
@timeouts.delete(hostname)
-
-
696
return unless connection && reset_candidates
-
-
# eliminate other candidates
-
1086
candidates = @queries.select { |_, conn| connection == conn }.keys
-
1086
@queries.delete_if { |h, _| candidates.include?(h) }
-
# reset timeouts
-
1095
@timeouts.delete_if { |h, _| candidates.include?(h) }
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "resolv"
-
26
require "ipaddr"
-
-
26
module HTTPX
-
26
class Resolver::Resolver
-
26
include Callbacks
-
26
include Loggable
-
-
26
using ArrayExtensions::Intersect
-
-
2
RECORD_TYPES = {
-
24
Socket::AF_INET6 => Resolv::DNS::Resource::IN::AAAA,
-
Socket::AF_INET => Resolv::DNS::Resource::IN::A,
-
}.freeze
-
-
2
FAMILY_TYPES = {
-
24
Resolv::DNS::Resource::IN::AAAA => "AAAA",
-
Resolv::DNS::Resource::IN::A => "A",
-
}.freeze
-
-
26
class << self
-
26
def multi?
-
6645
true
-
end
-
end
-
-
26
attr_reader :family, :options
-
-
26
attr_writer :current_selector, :current_session
-
-
26
attr_accessor :multi
-
-
26
def initialize(family, options)
-
6670
@family = family
-
6670
@record_type = RECORD_TYPES[family]
-
6670
@options = options
-
-
6670
set_resolver_callbacks
-
end
-
-
26
def each_connection(&block)
-
220
enum_for(__method__) unless block
-
-
220
return unless @connections
-
-
220
@connections.each(&block)
-
end
-
-
26
def close; end
-
-
26
alias_method :terminate, :close
-
-
26
def closed?
-
true
-
end
-
-
26
def empty?
-
true
-
end
-
-
26
def inflight?
-
false
-
end
-
-
26
def emit_addresses(connection, family, addresses, early_resolve = false)
-
6724
addresses.map! do |address|
-
17616
address.is_a?(IPAddr) ? address : IPAddr.new(address.to_s)
-
end
-
-
# double emission check, but allow early resolution to work
-
6724
return if !early_resolve && connection.addresses && !addresses.intersect?(connection.addresses)
-
-
6724
log do
-
64
"resolver #{FAMILY_TYPES[RECORD_TYPES[family]]}: " \
-
5
"answer #{FAMILY_TYPES[RECORD_TYPES[family]]} #{connection.peer.host}: #{addresses.inspect}"
-
end
-
6724
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 #{FAMILY_TYPES[RECORD_TYPES[family]]}: 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
-
6724
emit_resolved_connection(connection, addresses, early_resolve)
-
end
-
end
-
-
26
private
-
-
26
def emit_resolved_connection(connection, addresses, early_resolve)
-
begin
-
6724
connection.addresses = addresses
-
-
6678
emit(:resolve, connection)
-
24
rescue StandardError => e
-
46
if early_resolve
-
39
connection.force_reset
-
39
throw(:resolve_error, e)
-
else
-
7
emit(:error, connection, e)
-
end
-
end
-
end
-
-
26
def early_resolve(connection, hostname: connection.peer.host)
-
18
addresses = @resolver_options[:cache] && (connection.addresses || HTTPX::Resolver.nolookup_resolve(hostname))
-
-
18
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
-
-
26
def emit_resolve_error(connection, hostname = connection.peer.host, ex = nil)
-
169
emit_connection_error(connection, resolve_error(hostname, ex))
-
end
-
-
26
def resolve_error(hostname, ex = nil)
-
169
return ex if ex.is_a?(ResolveError) || ex.is_a?(ResolveTimeoutError)
-
-
42
message = ex ? ex.message : "Can't resolve #{hostname}"
-
42
error = ResolveError.new(message)
-
42
error.set_backtrace(ex ? ex.backtrace : caller)
-
42
error
-
end
-
-
26
def set_resolver_callbacks
-
6670
on(:resolve, &method(:resolve_connection))
-
6670
on(:error, &method(:emit_connection_error))
-
6670
on(:close, &method(:close_resolver))
-
end
-
-
26
def resolve_connection(connection)
-
6678
@current_session.__send__(:on_resolver_connection, connection, @current_selector)
-
end
-
-
26
def emit_connection_error(connection, error)
-
163
return connection.emit(:connect_error, error) if connection.connecting? && connection.callbacks_for?(:connect_error)
-
-
163
connection.emit(:error, error)
-
end
-
-
26
def close_resolver(resolver)
-
353
@current_session.__send__(:on_resolver_close, resolver, @current_selector)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "forwardable"
-
26
require "resolv"
-
-
26
module HTTPX
-
26
class Resolver::System < Resolver::Resolver
-
26
using URIExtensions
-
26
extend Forwardable
-
-
26
RESOLV_ERRORS = [Resolv::ResolvError,
-
Resolv::DNS::Requester::RequestError,
-
Resolv::DNS::EncodeError,
-
Resolv::DNS::DecodeError].freeze
-
-
26
DONE = 1
-
26
ERROR = 2
-
-
26
class << self
-
26
def multi?
-
25
false
-
end
-
end
-
-
26
attr_reader :state
-
-
26
def_delegator :@connections, :empty?
-
-
26
def initialize(options)
-
25
super(nil, options)
-
25
@resolver_options = @options.resolver_options
-
25
resolv_options = @resolver_options.dup
-
25
timeouts = resolv_options.delete(:timeouts) || Resolver::RESOLVE_TIMEOUT
-
25
@_timeouts = Array(timeouts)
-
50
@timeouts = Hash.new { |tims, host| tims[host] = @_timeouts.dup }
-
25
resolv_options.delete(:cache)
-
25
@connections = []
-
25
@queries = []
-
25
@ips = []
-
25
@pipe_mutex = Thread::Mutex.new
-
25
@state = :idle
-
end
-
-
26
def resolvers
-
return enum_for(__method__) unless block_given?
-
-
yield self
-
end
-
-
26
def multi
-
self
-
end
-
-
26
def empty?
-
true
-
end
-
-
26
def close
-
transition(:closed)
-
end
-
-
26
def closed?
-
@state == :closed
-
end
-
-
26
def to_io
-
@pipe_read.to_io
-
end
-
-
26
def call
-
case @state
-
when :open
-
consume
-
end
-
nil
-
end
-
-
26
def interests
-
return if @queries.empty?
-
-
:r
-
end
-
-
26
def timeout
-
return unless @queries.empty?
-
-
_, connection = @queries.first
-
-
return unless connection
-
-
@timeouts[connection.peer.host].first
-
end
-
-
26
def <<(connection)
-
25
@connections << connection
-
25
resolve
-
end
-
-
26
def early_resolve(connection, **)
-
25
self << connection
-
12
true
-
end
-
-
26
def handle_socket_timeout(interval)
-
error = HTTPX::ResolveTimeoutError.new(interval, "timed out while waiting on select")
-
error.set_backtrace(caller)
-
on_error(error)
-
end
-
-
26
private
-
-
26
def transition(nextstate)
-
25
case nextstate
-
when :idle
-
@timeouts.clear
-
when :open
-
25
return unless @state == :idle
-
-
25
@pipe_read, @pipe_write = ::IO.pipe
-
when :closed
-
return unless @state == :open
-
-
@pipe_write.close
-
@pipe_read.close
-
end
-
25
@state = nextstate
-
end
-
-
26
def consume
-
25
return if @connections.empty?
-
-
25
if @pipe_read.wait_readable
-
25
event = @pipe_read.getbyte
-
-
25
case event
-
when DONE
-
24
*pair, addrs = @pipe_mutex.synchronize { @ips.pop }
-
12
@queries.delete(pair)
-
12
_, connection = pair
-
12
@connections.delete(connection)
-
-
12
family, connection = pair
-
24
catch(:coalesced) { emit_addresses(connection, family, addrs) }
-
when ERROR
-
26
*pair, error = @pipe_mutex.synchronize { @ips.pop }
-
13
@queries.delete(pair)
-
13
@connections.delete(connection)
-
-
13
_, connection = pair
-
13
emit_resolve_error(connection, connection.peer.host, error)
-
end
-
end
-
-
12
return emit(:close, self) if @connections.empty?
-
-
resolve
-
end
-
-
26
def resolve(connection = @connections.first)
-
25
raise Error, "no URI to resolve" unless connection
-
25
return unless @queries.empty?
-
-
25
hostname = connection.peer.host
-
25
scheme = connection.origin.scheme
-
log do
-
"resolver: resolve IDN #{connection.peer.non_ascii_hostname} as #{hostname}"
-
25
end if connection.peer.non_ascii_hostname
-
-
25
transition(:open)
-
-
25
connection.options.ip_families.each do |family|
-
25
@queries << [family, connection]
-
end
-
25
async_resolve(connection, hostname, scheme)
-
25
consume
-
end
-
-
26
def async_resolve(connection, hostname, scheme)
-
25
families = connection.options.ip_families
-
25
log { "resolver: query for #{hostname}" }
-
25
timeouts = @timeouts[connection.peer.host]
-
25
resolve_timeout = timeouts.first
-
-
25
Thread.start do
-
25
Thread.current.report_on_exception = false
-
begin
-
25
addrs = if resolve_timeout
-
-
25
Timeout.timeout(resolve_timeout) do
-
25
__addrinfo_resolve(hostname, scheme)
-
end
-
else
-
__addrinfo_resolve(hostname, scheme)
-
end
-
12
addrs = addrs.sort_by(&:afamily).group_by(&:afamily)
-
12
families.each do |family|
-
12
addresses = addrs[family]
-
12
next unless addresses
-
-
12
addresses.map!(&:ip_address)
-
12
addresses.uniq!
-
12
@pipe_mutex.synchronize do
-
12
@ips.unshift([family, connection, addresses])
-
12
@pipe_write.putc(DONE) unless @pipe_write.closed?
-
end
-
end
-
rescue StandardError => e
-
13
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
-
13
@pipe_mutex.synchronize do
-
13
families.each do |family|
-
13
@ips.unshift([family, connection, e])
-
13
@pipe_write.putc(ERROR) unless @pipe_write.closed?
-
end
-
end
-
end
-
end
-
end
-
-
26
def __addrinfo_resolve(host, scheme)
-
25
Addrinfo.getaddrinfo(host, scheme, Socket::AF_UNSPEC, Socket::SOCK_STREAM)
-
end
-
-
26
def emit_connection_error(_, error)
-
13
throw(:resolve_error, error)
-
end
-
-
26
def close_resolver(resolver); end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "objspace"
-
26
require "stringio"
-
26
require "tempfile"
-
26
require "fileutils"
-
26
require "forwardable"
-
-
26
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).
-
#
-
26
class Response
-
26
extend Forwardable
-
26
include Callbacks
-
-
# the HTTP response status code
-
26
attr_reader :status
-
-
# an HTTPX::Headers object containing the response HTTP headers.
-
26
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
-
26
attr_reader :body
-
-
# The HTTP protocol version used to fetch the response.
-
26
attr_reader :version
-
-
# returns the response body buffered in a string.
-
26
def_delegator :@body, :to_s
-
-
26
def_delegator :@body, :to_str
-
-
# implements the IO reader +#read+ interface.
-
26
def_delegator :@body, :read
-
-
# copies the response body to a different location.
-
26
def_delegator :@body, :copy_to
-
-
# closes the body.
-
26
def_delegator :@body, :close
-
-
# the corresponding request uri.
-
26
def_delegator :@request, :uri
-
-
# the IP address of the peer server.
-
26
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+.
-
26
def initialize(request, status, version, headers)
-
8607
@request = request
-
8607
@options = request.options
-
8607
@version = version
-
8607
@status = Integer(status)
-
8607
@headers = @options.headers_class.new(headers)
-
8607
@body = @options.response_body_class.new(self, @options)
-
8607
@finished = complete?
-
8607
@content_type = nil
-
end
-
-
# merges headers defined in +h+ into the response headers.
-
26
def merge_headers(h)
-
192
@headers = @headers.merge(h)
-
end
-
-
# writes +data+ chunk into the response body.
-
26
def <<(data)
-
11426
@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"
-
26
def content_type
-
8976
@content_type ||= ContentType.new(@headers["content-type"])
-
end
-
-
# returns whether the response has been fully fetched.
-
26
def finished?
-
4550
@finished
-
end
-
-
# marks the response as finished, freezes the headers.
-
26
def finish!
-
4440
@finished = true
-
4440
@headers.freeze
-
end
-
-
# returns whether the response contains body payload.
-
26
def bodyless?
-
8607
@request.verb == "HEAD" ||
-
@status < 200 || # informational response
-
@status == 204 ||
-
@status == 205 ||
-
@status == 304 || begin
-
8161
content_length = @headers["content-length"]
-
8161
return false if content_length.nil?
-
-
7052
content_length == "0"
-
end
-
end
-
-
26
def complete?
-
8607
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
-
26
def error
-
562
return if @status < 400
-
-
54
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
-
26
def raise_for_status
-
522
return self unless (err = error)
-
-
38
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
-
26
def json(*args)
-
129
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".
-
26
def form
-
64
decode(Transcoder::Form)
-
end
-
-
26
def xml
-
# TODO: remove at next major version.
-
8
warn "DEPRECATION WARNING: calling `.#{__method__}` on plain HTTPX responses is deprecated. " \
-
1
"Use HTTPX.plugin(:xml) sessions and call `.#{__method__}` in its responses instead."
-
8
require "httpx/plugins/xml"
-
8
decode(Plugins::XML::Transcoder)
-
end
-
-
26
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>
-
26
def decode(transcoder, *args)
-
# TODO: check if content-type is a valid format, i.e. "application/json" for json parsing
-
-
217
decoder = transcoder.decode(self)
-
-
193
raise Error, "no decoder available for \"#{transcoder}\"" unless decoder
-
-
193
@body.rewind
-
-
193
decoder.call(self, *args)
-
end
-
end
-
-
# Helper class which decodes the HTTP "content-type" header.
-
26
class ContentType
-
26
MIME_TYPE_RE = %r{^([^/]+/[^;]+)(?:$|;)}.freeze
-
26
CHARSET_RE = /;\s*charset=([^;]+)/i.freeze
-
-
26
def initialize(header_value)
-
8938
@header_value = header_value
-
end
-
-
# returns the mime type declared in the header.
-
#
-
# ContentType.new("application/json; charset=utf-8").mime_type #=> "application/json"
-
26
def mime_type
-
217
return @mime_type if defined?(@mime_type)
-
-
179
m = @header_value.to_s[MIME_TYPE_RE, 1]
-
179
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
-
26
def charset
-
8759
return @charset if defined?(@charset)
-
-
8759
m = @header_value.to_s[CHARSET_RE, 1]
-
8759
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
-
26
class ErrorResponse
-
26
include Loggable
-
26
extend Forwardable
-
-
# the corresponding HTTPX::Request instance.
-
26
attr_reader :request
-
-
# the HTTPX::Response instance, when there is one (i.e. error happens fetching the response).
-
26
attr_reader :response
-
-
# the wrapped exception.
-
26
attr_reader :error
-
-
# the request uri
-
26
def_delegator :@request, :uri
-
-
# the IP address of the peer server.
-
26
def_delegator :@request, :peer_address
-
-
26
def initialize(request, error)
-
1157
@request = request
-
1157
@response = request.response if request.response.is_a?(Response)
-
1157
@error = error
-
1157
@options = request.options
-
1157
log_exception(@error)
-
end
-
-
# returns the exception full message.
-
26
def to_s
-
8
@error.full_message(highlight: false)
-
end
-
-
# closes the error resources.
-
26
def close
-
40
@response.close if @response && @response.respond_to?(:close)
-
end
-
-
# always true for error responses.
-
26
def finished?
-
8
true
-
end
-
-
# raises the wrapped exception.
-
26
def raise_for_status
-
76
raise @error
-
end
-
-
# buffers lost chunks to error response
-
26
def <<(data)
-
8
@response << data
-
end
-
end
-
end
-
-
26
require_relative "response/body"
-
26
require_relative "response/buffer"
-
26
require_relative "pmatch_extensions" if RUBY_VERSION >= "2.7.0"
-
# frozen_string_literal: true
-
-
26
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).
-
26
class Response::Body
-
# the payload encoding (i.e. "utf-8", "ASCII-8BIT")
-
26
attr_reader :encoding
-
-
# Array of encodings contained in the response "content-encoding" header.
-
26
attr_reader :encodings
-
-
# initialized with the corresponding HTTPX::Response +response+ and HTTPX::Options +options+.
-
26
def initialize(response, options)
-
8759
@response = response
-
8759
@headers = response.headers
-
8759
@options = options
-
8759
@window_size = options.window_size
-
8759
@encodings = []
-
8759
@length = 0
-
8759
@buffer = nil
-
8759
@reader = nil
-
8759
@state = :idle
-
-
# initialize response encoding
-
8759
@encoding = if (enc = response.content_type.charset)
-
167
begin
-
1505
Encoding.find(enc)
-
rescue ArgumentError
-
32
Encoding::BINARY
-
end
-
else
-
7254
Encoding::BINARY
-
end
-
-
8759
initialize_inflaters
-
end
-
-
26
def initialize_dup(other)
-
32
super
-
-
32
@buffer = other.instance_variable_get(:@buffer).dup
-
end
-
-
26
def closed?
-
296
@state == :closed
-
end
-
-
# write the response payload +chunk+ into the buffer. Inflates the chunk when required
-
# and supported.
-
26
def write(chunk)
-
11261
return if @state == :closed
-
-
11261
return 0 if chunk.empty?
-
-
10871
chunk = decode_chunk(chunk)
-
-
10871
size = chunk.bytesize
-
9674
@length += size
-
10871
transition(:open)
-
10871
@buffer.write(chunk)
-
-
10871
@response.emit(:chunk_received, chunk)
-
10855
size
-
end
-
-
# reads a chunk from the payload (implementation of the IO reader protocol).
-
26
def read(*args)
-
281
return unless @buffer
-
-
281
unless @reader
-
123
rewind
-
123
@reader = @buffer
-
end
-
-
281
@reader.read(*args)
-
end
-
-
# size of the decoded response payload. May differ from "content-length" header if
-
# response was encoded over-the-wire.
-
26
def bytesize
-
224
@length
-
end
-
-
# yields the payload in chunks.
-
26
def each
-
64
return enum_for(__method__) unless block_given?
-
-
5
begin
-
48
if @buffer
-
48
rewind
-
126
while (chunk = @buffer.read(@window_size))
-
48
yield(chunk.force_encoding(@encoding))
-
end
-
end
-
ensure
-
48
close
-
end
-
end
-
-
# returns the declared filename in the "contennt-disposition" header, when present.
-
26
def filename
-
48
return unless @headers.key?("content-disposition")
-
-
40
Utils.get_filename(@headers["content-disposition"])
-
end
-
-
# returns the full response payload as a string.
-
26
def to_s
-
4414
return "".b unless @buffer
-
-
4104
@buffer.to_s
-
end
-
-
26
alias_method :to_str, :to_s
-
-
# whether the payload is empty.
-
26
def empty?
-
32
@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"))
-
26
def copy_to(dest)
-
48
return unless @buffer
-
-
48
rewind
-
-
48
if dest.respond_to?(:path) && @buffer.respond_to?(:path)
-
8
FileUtils.mv(@buffer.path, dest.path)
-
else
-
40
::IO.copy_stream(@buffer, dest)
-
end
-
end
-
-
# closes/cleans the buffer, resets everything
-
26
def close
-
662
if @buffer
-
498
@buffer.close
-
498
@buffer = nil
-
end
-
662
@length = 0
-
662
transition(:closed)
-
end
-
-
26
def ==(other)
-
118
object_id == other.object_id || begin
-
118
if other.respond_to?(:read)
-
80
_with_same_buffer_pos { FileUtils.compare_stream(@buffer, other) }
-
else
-
78
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.
-
26
def rewind
-
452
return unless @buffer
-
-
# in case there's some reading going on
-
452
@reader = nil
-
-
452
@buffer.rewind
-
end
-
-
26
private
-
-
# prepares inflaters for the advertised encodings in "content-encoding" header.
-
26
def initialize_inflaters
-
8759
@inflaters = nil
-
-
8759
return unless @headers.key?("content-encoding")
-
-
187
return unless @options.decompress_response_body
-
-
171
@inflaters = @headers.get("content-encoding").filter_map do |encoding|
-
171
next if encoding == "identity"
-
-
171
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.
-
171
break unless inflater
-
-
171
@encodings << encoding
-
171
inflater
-
end
-
end
-
-
# passes the +chunk+ through all inflaters to decode it.
-
26
def decode_chunk(chunk)
-
44
@inflaters.reverse_each do |inflater|
-
452
chunk = inflater.call(chunk)
-
11013
end if @inflaters
-
-
11014
chunk
-
end
-
-
# tries transitioning the body STM to the +nextstate+.
-
26
def transition(nextstate)
-
10265
case nextstate
-
when :open
-
10871
return unless @state == :idle
-
-
6746
@buffer = Response::Buffer.new(
-
threshold_size: @options.body_threshold_size,
-
bytesize: @length,
-
encoding: @encoding
-
)
-
when :closed
-
662
return if @state == :closed
-
end
-
-
7408
@state = nextstate
-
end
-
-
26
def _with_same_buffer_pos # :nodoc:
-
40
return yield unless @buffer && @buffer.respond_to?(:pos)
-
-
# @type ivar @buffer: StringIO | Tempfile
-
40
current_pos = @buffer.pos
-
40
@buffer.rewind
-
4
begin
-
40
yield
-
ensure
-
40
@buffer.pos = current_pos
-
end
-
end
-
-
26
class << self
-
26
def initialize_inflater_by_encoding(encoding, response, **kwargs) # :nodoc:
-
154
case encoding
-
when "gzip"
-
155
Transcoder::GZIP.decode(response, **kwargs)
-
when "deflate"
-
16
Transcoder::Deflate.decode(response, **kwargs)
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "delegate"
-
26
require "stringio"
-
26
require "tempfile"
-
-
26
module HTTPX
-
# wraps and delegates to an internal buffer, which can be a StringIO or a Tempfile.
-
26
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+.
-
26
def initialize(threshold_size:, bytesize: 0, encoding: Encoding::BINARY)
-
6942
@threshold_size = threshold_size
-
6942
@bytesize = bytesize
-
6942
@encoding = encoding
-
6942
@buffer = StringIO.new("".b)
-
6942
super(@buffer)
-
end
-
-
26
def initialize_dup(other)
-
32
super
-
-
32
@buffer = other.instance_variable_get(:@buffer).dup
-
end
-
-
# size in bytes of the buffered content.
-
26
def size
-
324
@bytesize
-
end
-
-
# writes the +chunk+ into the buffer.
-
26
def write(chunk)
-
10011
@bytesize += chunk.bytesize
-
11249
try_upgrade_buffer
-
11249
@buffer.write(chunk)
-
end
-
-
# returns the buffered content as a string.
-
26
def to_s
-
3706
case @buffer
-
when StringIO
-
475
begin
-
4120
@buffer.string.force_encoding(@encoding)
-
rescue ArgumentError
-
@buffer.string
-
end
-
when Tempfile
-
80
rewind
-
160
content = _with_same_buffer_pos { @buffer.read }
-
9
begin
-
80
content.force_encoding(@encoding)
-
rescue ArgumentError # ex: unknown encoding name - utf
-
content
-
end
-
end
-
end
-
-
# closes the buffer.
-
26
def close
-
610
@buffer.close
-
610
@buffer.unlink if @buffer.respond_to?(:unlink)
-
end
-
-
26
private
-
-
# initializes the buffer into a StringIO, or turns it into a Tempfile when the threshold
-
# has been reached.
-
26
def try_upgrade_buffer
-
11249
return unless @bytesize > @threshold_size
-
-
463
return if @buffer.is_a?(Tempfile)
-
-
163
aux = @buffer
-
-
163
@buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
-
163
if aux
-
163
aux.rewind
-
163
::IO.copy_stream(aux, @buffer)
-
163
aux.close
-
end
-
-
163
__setobj__(@buffer)
-
end
-
-
26
def _with_same_buffer_pos # :nodoc:
-
80
current_pos = @buffer.pos
-
80
@buffer.rewind
-
9
begin
-
80
yield
-
ensure
-
80
@buffer.pos = current_pos
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "io/wait"
-
-
26
module HTTPX
-
26
class Selector
-
26
extend Forwardable
-
-
26
READABLE = %i[rw r].freeze
-
26
WRITABLE = %i[rw w].freeze
-
-
26
private_constant :READABLE
-
26
private_constant :WRITABLE
-
-
26
def_delegator :@timers, :after
-
-
26
def_delegator :@selectables, :empty?
-
-
26
def initialize
-
7130
@timers = Timers.new
-
7130
@selectables = []
-
end
-
-
26
def each(&blk)
-
@selectables.each(&blk)
-
end
-
-
26
def next_tick
-
2787723
catch(:jump_tick) do
-
2787723
timeout = next_timeout
-
2787723
if timeout && timeout.negative?
-
@timers.fire
-
throw(:jump_tick)
-
end
-
-
522905
begin
-
2787723
select(timeout, &:call)
-
2787502
@timers.fire
-
rescue TimeoutError => e
-
@timers.fire(e)
-
end
-
end
-
rescue StandardError => e
-
117
emit_error(e)
-
rescue Exception # rubocop:disable Lint/RescueException
-
104
each_connection(&:force_reset)
-
104
raise
-
end
-
-
26
def terminate
-
# array may change during iteration
-
6755
selectables = @selectables.reject(&:inflight?)
-
-
6755
selectables.each(&:terminate)
-
-
7040
until selectables.empty?
-
2644
next_tick
-
-
2351
selectables &= @selectables
-
end
-
end
-
-
26
def find_resolver(options)
-
6700
res = @selectables.find do |c|
-
53
c.is_a?(Resolver::Resolver) && options == c.options
-
end
-
-
6700
res.multi if res
-
end
-
-
26
def each_connection(&block)
-
31644
return enum_for(__method__) unless block
-
-
16065
@selectables.each do |c|
-
2109
if c.is_a?(Resolver::Resolver)
-
220
c.each_connection(&block)
-
else
-
1889
yield c
-
end
-
end
-
end
-
-
26
def find_connection(request_uri, options)
-
8711
each_connection.find do |connection|
-
1198
connection.match?(request_uri, options)
-
end
-
end
-
-
26
def find_mergeable_connection(connection)
-
6868
each_connection.find do |ch|
-
284
ch != connection && ch.mergeable?(connection)
-
end
-
end
-
-
26
def empty?
-
813
@selectables.empty?
-
end
-
-
# deregisters +io+ from selectables.
-
26
def deregister(io)
-
8034
@selectables.delete(io)
-
end
-
-
# register +io+.
-
26
def register(io)
-
8199
return if @selectables.include?(io)
-
-
7840
@selectables << io
-
end
-
-
26
private
-
-
26
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.
-
2787723
return if interval.nil? && @selectables.empty?
-
-
2785079
return select_one(interval, &block) if @selectables.size == 1
-
-
362
select_many(interval, &block)
-
end
-
-
26
def select_many(interval, &block)
-
362
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
-
362
@selectables.delete_if do |io|
-
392
interests = io.interests
-
-
392
(r ||= []) << io if READABLE.include?(interests)
-
392
(w ||= []) << io if WRITABLE.include?(interests)
-
-
392
io.state == :closed
-
end
-
-
# TODO: what to do if there are no selectables?
-
-
362
readers, writers = IO.select(r, w, nil, interval)
-
-
362
if readers.nil? && writers.nil? && interval
-
176
[*r, *w].each { |io| io.handle_socket_timeout(interval) }
-
176
return
-
end
-
end
-
-
186
if writers
-
4
readers.each do |io|
-
105
yield io
-
-
# so that we don't yield 2 times
-
105
writers.delete(io)
-
185
end if readers
-
-
186
writers.each(&block)
-
else
-
readers.each(&block) if readers
-
end
-
end
-
-
26
def select_one(interval)
-
2784717
io = @selectables.first
-
-
2784717
return unless io
-
-
2784717
interests = io.interests
-
-
2784716
result = case interests
-
12086
when :r then io.to_io.wait_readable(interval)
-
9233
when :w then io.to_io.wait_writable(interval)
-
when :rw then io.to_io.wait(interval, :read_write)
-
2763397
when nil then return
-
end
-
-
21319
unless result || interval.nil?
-
557
io.handle_socket_timeout(interval)
-
484
return
-
end
-
# raise TimeoutError.new(interval, "timed out while waiting on select")
-
-
20762
yield io
-
# rescue IOError, SystemCallError
-
# @selectables.reject!(&:closed?)
-
# raise unless @selectables.empty?
-
end
-
-
26
def next_timeout
-
364163
[
-
1900654
@timers.wait_interval,
-
@selectables.filter_map(&:timeout).min,
-
522905
].compact.min
-
end
-
-
26
def emit_error(e)
-
117
@selectables.each do |c|
-
next if c.is_a?(Resolver::Resolver)
-
-
c.emit(:error, e)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
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
-
26
class Session
-
26
include Loggable
-
26
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.
-
26
def initialize(options = EMPTY_HASH, &blk)
-
10365
@options = self.class.default_options.merge(options)
-
10365
@responses = {}
-
10365
@persistent = @options.persistent
-
10365
@pool = @options.pool_class.new(@options.pool_options)
-
10365
@wrapped = false
-
10365
@closing = false
-
10365
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
-
26
def wrap
-
519
prev_wrapped = @wrapped
-
519
@wrapped = true
-
519
was_initialized = false
-
519
current_selector = get_current_selector do
-
519
selector = Selector.new
-
-
519
set_current_selector(selector)
-
-
519
was_initialized = true
-
-
519
selector
-
end
-
50
begin
-
519
yield self
-
ensure
-
519
unless prev_wrapped
-
519
if @persistent
-
1
deactivate(current_selector)
-
else
-
518
close(current_selector)
-
end
-
end
-
519
@wrapped = prev_wrapped
-
519
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.
-
26
def close(selector = Selector.new)
-
# throw resolvers away from the pool
-
6755
@pool.reset_resolvers
-
-
# preparing to throw away connections
-
15823
while (connection = @pool.pop_connection)
-
4348
next if connection.state == :closed
-
-
160
connection.current_session = self
-
160
connection.current_selector = selector
-
160
select_connection(connection, selector)
-
end
-
763
begin
-
6755
@closing = true
-
6755
selector.terminate
-
ensure
-
6755
@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" })
-
#
-
26
def request(*args, **params)
-
6982
raise ArgumentError, "must perform at least one request" if args.empty?
-
-
6982
requests = args.first.is_a?(Request) ? args : build_requests(*args, params)
-
6957
responses = send_requests(*requests)
-
6839
return responses.first if responses.size == 1
-
-
191
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)
-
26
def build_request(verb, uri, params = EMPTY_HASH, options = @options)
-
8359
rklass = options.request_class
-
8359
request = rklass.new(verb, uri, options, params)
-
8334
request.persistent = @persistent
-
8334
set_request_callbacks(request)
-
8334
request
-
end
-
-
26
def select_connection(connection, selector)
-
8199
selector.register(connection)
-
end
-
-
26
alias_method :select_resolver, :select_connection
-
-
26
def deselect_connection(connection, selector, cloned = false)
-
7681
selector.deregister(connection)
-
-
# when connections coalesce
-
7681
return if connection.state == :idle
-
-
7644
return if cloned
-
-
7636
return if @closing && connection.state == :closed
-
-
7628
@pool.checkin_connection(connection)
-
end
-
-
26
def deselect_resolver(resolver, selector)
-
353
selector.deregister(resolver)
-
-
353
return if @closing && resolver.closed?
-
-
353
@pool.checkin_resolver(resolver)
-
end
-
-
26
def try_clone_connection(connection, selector, family)
-
451
connection.family ||= family
-
-
451
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.
-
26
def find_connection(request_uri, selector, options)
-
8711
if (connection = selector.find_connection(request_uri, options))
-
1080
return connection
-
end
-
-
7567
connection = @pool.checkout_connection(request_uri, options)
-
-
7543
connection.current_session = self
-
7543
connection.current_selector = selector
-
-
6699
case connection.state
-
when :idle
-
6866
do_init_connection(connection, selector)
-
when :open
-
66
select_connection(connection, selector) if options.io
-
when :closed
-
604
connection.idling
-
604
select_connection(connection, selector)
-
when :closing
-
connection.once(:close) do
-
connection.idling
-
select_connection(connection, selector)
-
end
-
end
-
-
7479
connection
-
end
-
-
26
private
-
-
26
def deactivate(selector)
-
382
selector.each_connection do |connection|
-
326
connection.deactivate
-
326
deselect_connection(connection, selector) if connection.state == :inactive
-
end
-
end
-
-
# callback executed when a response for a given request has been received.
-
26
def on_response(request, response)
-
7708
@responses[request] = response
-
end
-
-
# callback executed when an HTTP/2 promise frame has been received.
-
26
def on_promise(_, stream)
-
8
log(level: 2) { "#{stream.id}: refusing stream!" }
-
8
stream.refuse
-
end
-
-
# returns the corresponding HTTP::Response to the given +request+ if it has been received.
-
26
def fetch_response(request, _selector, _options)
-
2792829
@responses.delete(request)
-
end
-
-
# sends the +request+ to the corresponding HTTPX::Connection
-
26
def send_request(request, selector, options = request.options)
-
1803
error = begin
-
8645
catch(:resolve_error) do
-
8645
connection = find_connection(request.uri, selector, options)
-
8533
connection.send(request)
-
end
-
rescue StandardError => e
-
32
e
-
end
-
8639
return unless error && error.is_a?(Exception)
-
-
112
if error.is_a?(Error)
-
112
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+.
-
26
def build_requests(*args, params)
-
6466
requests = if args.size == 1
-
78
reqs = args.first
-
78
reqs.map do |verb, uri, ps = EMPTY_HASH|
-
156
request_params = params
-
156
request_params = request_params.merge(ps) unless ps.empty?
-
156
build_request(verb, uri, request_params)
-
end
-
else
-
6388
verb, uris = args
-
6388
if uris.respond_to?(:each)
-
6148
uris.enum_for(:each).map do |uri, ps = EMPTY_HASH|
-
6890
request_params = params
-
6890
request_params = request_params.merge(ps) unless ps.empty?
-
6890
build_request(verb, uri, request_params)
-
end
-
else
-
240
[build_request(verb, uris, params)]
-
end
-
end
-
6441
raise ArgumentError, "wrong number of URIs (given 0, expect 1..+1)" if requests.empty?
-
-
6441
requests
-
end
-
-
26
def set_request_callbacks(request)
-
8334
request.on(:response, &method(:on_response).curry(2)[request])
-
8334
request.on(:promise, &method(:on_promise))
-
end
-
-
26
def do_init_connection(connection, selector)
-
6866
resolve_connection(connection, selector) unless connection.family
-
end
-
-
# sends an array of HTTPX::Request +requests+, returns the respective array of HTTPX::Response objects.
-
26
def send_requests(*requests)
-
13459
selector = get_current_selector { Selector.new }
-
779
begin
-
7055
_send_requests(requests, selector)
-
7049
receive_requests(requests, selector)
-
ensure
-
7055
unless @wrapped
-
6411
if @persistent
-
381
deactivate(selector)
-
else
-
6030
close(selector)
-
end
-
end
-
end
-
end
-
-
# sends an array of HTTPX::Request objects
-
26
def _send_requests(requests, selector)
-
7055
requests.each do |request|
-
7860
send_request(request, selector)
-
end
-
end
-
-
# returns the array of HTTPX::Response objects corresponding to the array of HTTPX::Request +requests+.
-
26
def receive_requests(requests, selector)
-
# @type var responses: Array[response]
-
7049
responses = []
-
-
# guarantee ordered responses
-
7049
loop do
-
7862
request = requests.first
-
-
7862
return responses unless request
-
-
3155852
catch(:coalesced) { selector.next_tick } until (response = fetch_response(request, selector, request.options))
-
7750
request.emit(:complete, response)
-
-
7750
responses << response
-
7750
requests.shift
-
-
7750
break if requests.empty?
-
-
813
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
-
6937
responses
-
end
-
-
26
def resolve_connection(connection, selector)
-
6890
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.
-
#
-
190
connection.once(:connect_error, &connection.method(:handle_error))
-
190
on_resolver_connection(connection, selector)
-
188
return
-
end
-
-
6700
resolver = find_resolver_for(connection, selector)
-
-
6700
resolver.early_resolve(connection) || resolver.lazy_resolve(connection)
-
end
-
-
26
def on_resolver_connection(connection, selector)
-
6868
from_pool = false
-
6868
found_connection = selector.find_mergeable_connection(connection) || begin
-
6841
from_pool = true
-
6841
@pool.checkout_mergeable_connection(connection)
-
end
-
-
6868
return select_connection(connection, selector) unless found_connection
-
-
27
if found_connection.open?
-
26
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
-
-
26
def on_resolver_close(resolver, selector)
-
353
return if resolver.closed?
-
-
353
deselect_resolver(resolver, selector)
-
353
resolver.close unless resolver.closed?
-
end
-
-
26
def find_resolver_for(connection, selector)
-
6700
resolver = selector.find_resolver(connection.options)
-
-
6700
unless resolver
-
6698
resolver = @pool.checkout_resolver(connection.options)
-
6698
resolver.current_session = self
-
6698
resolver.current_selector = selector
-
end
-
-
6700
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+.
-
26
def coalesce_connections(conn1, conn2, selector, from_pool)
-
27
unless conn1.coalescable?(conn2)
-
14
select_connection(conn2, selector)
-
14
@pool.checkin_connection(conn1) if from_pool
-
14
return false
-
end
-
-
13
conn2.emit(:tcp_open, conn1)
-
13
conn1.merge(conn2)
-
13
conn2.coalesced_connection = conn1
-
13
select_connection(conn1, selector) if from_pool
-
13
deselect_connection(conn2, selector)
-
13
true
-
end
-
-
26
def get_current_selector
-
7574
selector_store[self] || (yield if block_given?)
-
end
-
-
26
def set_current_selector(selector)
-
1413
if selector
-
805
selector_store[self] = selector
-
else
-
519
selector_store.delete(self)
-
end
-
end
-
-
26
def selector_store
-
8987
th_current = Thread.current
-
8987
th_current.thread_variable_get(:httpx_persistent_selector_store) || begin
-
110
{}.compare_by_identity.tap do |store|
-
110
th_current.thread_variable_set(:httpx_persistent_selector_store, store)
-
end
-
end
-
end
-
-
26
@default_options = Options.new
-
26
@default_options.freeze
-
26
@plugins = []
-
-
26
class << self
-
26
attr_reader :default_options
-
-
26
def inherited(klass)
-
5229
super
-
5229
klass.instance_variable_set(:@default_options, @default_options)
-
5229
klass.instance_variable_set(:@plugins, @plugins.dup)
-
5229
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)
-
#
-
26
def plugin(pl, options = nil, &block)
-
# raise Error, "Cannot add a plugin to a frozen config" if frozen?
-
7103
pl = Plugins.load_plugin(pl) if pl.is_a?(Symbol)
-
7103
if !@plugins.include?(pl)
-
6873
@plugins << pl
-
6873
pl.load_dependencies(self, &block) if pl.respond_to?(:load_dependencies)
-
-
6873
@default_options = @default_options.dup
-
-
6873
include(pl::InstanceMethods) if defined?(pl::InstanceMethods)
-
6873
extend(pl::ClassMethods) if defined?(pl::ClassMethods)
-
-
6873
opts = @default_options
-
6873
opts.extend_with_plugin_classes(pl)
-
6873
if defined?(pl::OptionsMethods)
-
-
2845
(pl::OptionsMethods.instance_methods - Object.instance_methods).each do |meth|
-
8119
opts.options_class.method_added(meth)
-
end
-
2845
@default_options = opts.options_class.new(opts)
-
end
-
-
6873
@default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
-
6873
@default_options = @default_options.merge(options) if options
-
-
6873
pl.configure(self, &block) if pl.respond_to?(:configure)
-
-
6873
@default_options.freeze
-
229
elsif options
-
# this can happen when two plugins are loaded, an one of them calls the other under the hood,
-
# albeit changing some default.
-
16
@default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
-
16
@default_options = @default_options.merge(options) if options
-
-
16
@default_options.freeze
-
end
-
7103
self
-
end
-
end
-
end
-
-
# session may be overridden by certain adapters.
-
26
S = Session
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
26
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
-
-
26
module HTTPX
-
26
class Timers
-
26
def initialize
-
7130
@intervals = []
-
end
-
-
26
def after(interval_in_secs, cb = nil, &blk)
-
36934
return unless interval_in_secs
-
-
36934
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.
-
66825
unless (interval = @intervals.find { |t| t.interval == interval_in_secs })
-
8346
interval = Interval.new(interval_in_secs)
-
16358
interval.on_empty { @intervals.delete(interval) }
-
8346
@intervals << interval
-
8346
@intervals.sort!
-
end
-
-
36934
interval << callback
-
-
36934
@next_interval_at = nil
-
-
36934
interval
-
end
-
-
26
def wait_interval
-
2787723
return if @intervals.empty?
-
-
2767475
@next_interval_at = Utils.now
-
-
2767475
@intervals.first.interval
-
end
-
-
26
def fire(error = nil)
-
2787502
raise error if error && error.timeout != @intervals.first
-
2787502
return if @intervals.empty? || !@next_interval_at
-
-
2761421
elapsed_time = Utils.elapsed_time(@next_interval_at)
-
-
5522856
@intervals = @intervals.drop_while { |interval| interval.elapse(elapsed_time) <= 0 }
-
-
2761421
@next_interval_at = nil if @intervals.empty?
-
end
-
-
26
class Interval
-
26
include Comparable
-
-
26
attr_reader :interval
-
-
26
def initialize(interval)
-
8346
@interval = interval
-
8346
@callbacks = []
-
8346
@on_empty = nil
-
end
-
-
26
def on_empty(&blk)
-
8346
@on_empty = blk
-
end
-
-
26
def <=>(other)
-
743
@interval <=> other.interval
-
end
-
-
26
def ==(other)
-
2458
return @interval == other if other.is_a?(Numeric)
-
-
2458
@interval == other.to_f # rubocop:disable Lint/FloatComparison
-
end
-
-
26
def to_f
-
2458
Float(@interval)
-
end
-
-
26
def <<(callback)
-
36934
@callbacks << callback
-
end
-
-
26
def delete(callback)
-
54463
@callbacks.delete(callback)
-
54463
@on_empty.call if @callbacks.empty?
-
end
-
-
26
def no_callbacks?
-
54463
@callbacks.empty?
-
end
-
-
26
def elapsed?
-
1283
@interval <= 0
-
end
-
-
26
def elapse(elapsed)
-
2399302
@interval -= elapsed
-
-
2761435
if @interval <= 0
-
551
cb = @callbacks.dup
-
551
cb.each(&:call)
-
end
-
-
2761435
@interval
-
end
-
end
-
26
private_constant :Interval
-
end
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
26
module Transcoder
-
26
module_function
-
-
26
def normalize_keys(key, value, cond = nil, &block)
-
3415
if cond && cond.call(value)
-
1065
block.call(key.to_s, value)
-
2349
elsif value.respond_to?(:to_ary)
-
454
if value.empty?
-
128
block.call("#{key}[]")
-
else
-
326
value.to_ary.each do |element|
-
524
normalize_keys("#{key}[]", element, cond, &block)
-
end
-
end
-
1895
elsif value.respond_to?(:to_hash)
-
512
value.to_hash.each do |child_key, child_value|
-
512
normalize_keys("#{key}[#{child_key}]", child_value, cond, &block)
-
end
-
else
-
1384
block.call(key.to_s, value)
-
end
-
end
-
-
# based on https://github.com/rack/rack/blob/d15dd728440710cfc35ed155d66a98dc2c07ae42/lib/rack/query_parser.rb#L82
-
26
def normalize_query(params, name, v, depth)
-
184
raise Error, "params depth surpasses what's supported" if depth <= 0
-
-
184
name =~ /\A[\[\]]*([^\[\]]+)\]*/
-
184
k = Regexp.last_match(1) || ""
-
184
after = Regexp.last_match ? Regexp.last_match.post_match : ""
-
-
184
if k.empty?
-
16
return Array(v) if !v.empty? && name == "[]"
-
-
7
return
-
end
-
-
147
case after
-
when ""
-
49
params[k] = v
-
when "["
-
7
params[name] = v
-
when "[]"
-
16
params[k] ||= []
-
16
raise Error, "expected Array (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Array)
-
-
16
params[k] << v
-
when /^\[\]\[([^\[\]]+)\]$/, /^\[\](.+)$/
-
32
child_key = Regexp.last_match(1)
-
32
params[k] ||= []
-
32
raise Error, "expected Array (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Array)
-
-
32
if params[k].last.is_a?(Hash) && !params_hash_has_key?(params[k].last, child_key)
-
8
normalize_query(params[k].last, child_key, v, depth - 1)
-
else
-
24
params[k] << normalize_query({}, child_key, v, depth - 1)
-
end
-
else
-
56
params[k] ||= {}
-
56
raise Error, "expected Hash (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Hash)
-
-
49
params[k] = normalize_query(params[k], after, v, depth - 1)
-
end
-
-
168
params
-
end
-
-
26
def params_hash_has_key?(hash, key)
-
16
return false if key.include?("[]")
-
-
16
key.split(/[\[\]]+/).inject(hash) do |h, part|
-
16
next h if part == ""
-
16
return false unless h.is_a?(Hash) && h.key?(part)
-
-
8
h[part]
-
end
-
-
8
true
-
end
-
end
-
end
-
-
26
require "httpx/transcoder/body"
-
26
require "httpx/transcoder/form"
-
26
require "httpx/transcoder/json"
-
26
require "httpx/transcoder/chunker"
-
26
require "httpx/transcoder/deflate"
-
26
require "httpx/transcoder/gzip"
-
# frozen_string_literal: true
-
-
26
require "forwardable"
-
-
26
module HTTPX::Transcoder
-
26
module Body
-
26
class Error < HTTPX::Error; end
-
-
26
module_function
-
-
26
class Encoder
-
26
extend Forwardable
-
-
26
def_delegator :@raw, :to_s
-
-
26
def_delegator :@raw, :==
-
-
26
def initialize(body)
-
1266
@raw = body
-
end
-
-
26
def bytesize
-
4742
if @raw.respond_to?(:bytesize)
-
2468
@raw.bytesize
-
2273
elsif @raw.respond_to?(:to_ary)
-
926
@raw.sum(&:bytesize)
-
1347
elsif @raw.respond_to?(:size)
-
796
@raw.size || Float::INFINITY
-
551
elsif @raw.respond_to?(:length)
-
256
@raw.length || Float::INFINITY
-
295
elsif @raw.respond_to?(:each)
-
288
Float::INFINITY
-
else
-
8
raise Error, "cannot determine size of body: #{@raw.inspect}"
-
end
-
end
-
-
26
def content_type
-
1218
"application/octet-stream"
-
end
-
-
26
private
-
-
26
def respond_to_missing?(meth, *args)
-
4590
@raw.respond_to?(meth, *args) || super
-
end
-
-
26
def method_missing(meth, *args, &block)
-
1107
return super unless @raw.respond_to?(meth)
-
-
1107
@raw.__send__(meth, *args, &block)
-
end
-
end
-
-
26
def encode(body)
-
1266
Encoder.new(body)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "forwardable"
-
-
26
module HTTPX::Transcoder
-
26
module Chunker
-
26
class Error < HTTPX::Error; end
-
-
26
CRLF = "\r\n".b
-
-
26
class Encoder
-
26
extend Forwardable
-
-
26
def initialize(body)
-
96
@raw = body
-
end
-
-
26
def each
-
96
return enum_for(__method__) unless block_given?
-
-
96
@raw.each do |chunk|
-
448
yield "#{chunk.bytesize.to_s(16)}#{CRLF}#{chunk}#{CRLF}"
-
end
-
96
yield "0#{CRLF}"
-
end
-
-
26
def respond_to_missing?(meth, *args)
-
156
@raw.respond_to?(meth, *args) || super
-
end
-
end
-
-
26
class Decoder
-
26
extend Forwardable
-
-
26
def_delegator :@buffer, :empty?
-
-
26
def_delegator :@buffer, :<<
-
-
26
def_delegator :@buffer, :clear
-
-
26
def initialize(buffer, trailers = false)
-
114
@buffer = buffer
-
114
@chunk_buffer = "".b
-
114
@finished = false
-
114
@state = :length
-
114
@trailers = trailers
-
end
-
-
26
def to_s
-
106
@buffer
-
end
-
-
26
def each
-
197
loop do
-
1043
case @state
-
when :length
-
340
index = @buffer.index(CRLF)
-
340
return unless index && index.positive?
-
-
# Read hex-length
-
340
hexlen = @buffer.byteslice(0, index)
-
340
@buffer = @buffer.byteslice(index..-1) || "".b
-
340
hexlen[/\h/] || raise(Error, "wrong chunk size line: #{hexlen}")
-
340
@chunk_length = hexlen.hex
-
# check if is last chunk
-
340
@finished = @chunk_length.zero?
-
340
nextstate(:crlf)
-
when :crlf
-
566
crlf_size = @finished && !@trailers ? 4 : 2
-
# consume CRLF
-
566
return if @buffer.bytesize < crlf_size
-
566
raise Error, "wrong chunked encoding format" unless @buffer.start_with?(CRLF * (crlf_size / 2))
-
-
566
@buffer = @buffer.byteslice(crlf_size..-1)
-
566
if @chunk_length.nil?
-
226
nextstate(:length)
-
else
-
340
return if @finished
-
-
234
nextstate(:data)
-
end
-
when :data
-
284
chunk = @buffer.byteslice(0, @chunk_length)
-
284
@buffer = @buffer.byteslice(@chunk_length..-1) || "".b
-
284
@chunk_buffer << chunk
-
249
@chunk_length -= chunk.bytesize
-
284
if @chunk_length.zero?
-
234
yield @chunk_buffer unless @chunk_buffer.empty?
-
226
@chunk_buffer.clear
-
226
@chunk_length = nil
-
226
nextstate(:crlf)
-
end
-
end
-
1076
break if @buffer.empty?
-
end
-
end
-
-
26
def finished?
-
189
@finished
-
end
-
-
26
private
-
-
26
def nextstate(state)
-
1026
@state = state
-
end
-
end
-
-
26
module_function
-
-
26
def encode(chunks)
-
96
Encoder.new(chunks)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "zlib"
-
26
require_relative "utils/deflater"
-
-
26
module HTTPX
-
26
module Transcoder
-
26
module Deflate
-
26
class Deflater < Transcoder::Deflater
-
26
def deflate(chunk)
-
72
@deflater ||= Zlib::Deflate.new
-
-
72
if chunk.nil?
-
48
unless @deflater.closed?
-
24
last = @deflater.finish
-
24
@deflater.close
-
24
last.empty? ? nil : last
-
end
-
else
-
24
@deflater.deflate(chunk)
-
end
-
end
-
end
-
-
26
module_function
-
-
26
def encode(body)
-
24
Deflater.new(body)
-
end
-
-
26
def decode(response, bytesize: nil)
-
16
bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
-
16
GZIP::Inflater.new(bytesize)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "forwardable"
-
26
require "uri"
-
26
require_relative "multipart"
-
-
26
module HTTPX
-
26
module Transcoder
-
26
module Form
-
26
module_function
-
-
26
PARAM_DEPTH_LIMIT = 32
-
-
26
class Encoder
-
26
extend Forwardable
-
-
26
def_delegator :@raw, :to_s
-
-
26
def_delegator :@raw, :to_str
-
-
26
def_delegator :@raw, :bytesize
-
-
26
def_delegator :@raw, :==
-
-
26
def initialize(form)
-
706
@raw = form.each_with_object("".b) do |(key, val), buf|
-
1186
HTTPX::Transcoder.normalize_keys(key, val) do |k, v|
-
1384
buf << "&" unless buf.empty?
-
1384
buf << URI.encode_www_form_component(k)
-
1384
buf << "=#{URI.encode_www_form_component(v.to_s)}" unless v.nil?
-
end
-
end
-
end
-
-
26
def content_type
-
554
"application/x-www-form-urlencoded"
-
end
-
end
-
-
26
module Decoder
-
26
module_function
-
-
26
def call(response, *)
-
40
URI.decode_www_form(response.to_s).each_with_object({}) do |(field, value), params|
-
96
HTTPX::Transcoder.normalize_query(params, field, value, PARAM_DEPTH_LIMIT)
-
end
-
end
-
end
-
-
26
def encode(form)
-
1657
if multipart?(form)
-
951
Multipart::Encoder.new(form)
-
else
-
706
Encoder.new(form)
-
end
-
end
-
-
26
def decode(response)
-
64
content_type = response.content_type.mime_type
-
-
56
case content_type
-
when "application/x-www-form-urlencoded"
-
40
Decoder
-
when "multipart/form-data"
-
16
Multipart::Decoder.new(response)
-
else
-
8
raise Error, "invalid form mime type (#{content_type})"
-
end
-
end
-
-
26
def multipart?(data)
-
1657
data.any? do |_, v|
-
2201
Multipart::MULTIPART_VALUE_COND.call(v) ||
-
1698
(v.respond_to?(:to_ary) && v.to_ary.any?(&Multipart::MULTIPART_VALUE_COND)) ||
-
2082
(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
-
-
26
require "zlib"
-
-
26
module HTTPX
-
26
module Transcoder
-
26
module GZIP
-
26
class Deflater < Transcoder::Deflater
-
26
def initialize(body)
-
48
@compressed_chunk = "".b
-
48
super
-
end
-
-
26
def deflate(chunk)
-
96
@deflater ||= Zlib::GzipWriter.new(self)
-
-
96
if chunk.nil?
-
48
unless @deflater.closed?
-
48
@deflater.flush
-
48
@deflater.close
-
48
compressed_chunk
-
end
-
else
-
48
@deflater.write(chunk)
-
48
compressed_chunk
-
end
-
end
-
-
26
private
-
-
26
def write(chunk)
-
144
@compressed_chunk << chunk
-
end
-
-
26
def compressed_chunk
-
96
@compressed_chunk.dup
-
ensure
-
96
@compressed_chunk.clear
-
end
-
end
-
-
26
class Inflater
-
26
def initialize(bytesize)
-
171
@inflater = Zlib::Inflate.new(Zlib::MAX_WBITS + 32)
-
171
@bytesize = bytesize
-
end
-
-
26
def call(chunk)
-
452
buffer = @inflater.inflate(chunk)
-
408
@bytesize -= chunk.bytesize
-
452
if @bytesize <= 0
-
108
buffer << @inflater.finish
-
108
@inflater.close
-
end
-
452
buffer
-
end
-
end
-
-
26
module_function
-
-
26
def encode(body)
-
48
Deflater.new(body)
-
end
-
-
26
def decode(response, bytesize: nil)
-
155
bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
-
155
Inflater.new(bytesize)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "forwardable"
-
-
26
module HTTPX::Transcoder
-
26
module JSON
-
26
module_function
-
-
26
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
-
-
26
class Encoder
-
26
extend Forwardable
-
-
26
def_delegator :@raw, :to_s
-
-
26
def_delegator :@raw, :bytesize
-
-
26
def_delegator :@raw, :==
-
-
26
def initialize(json)
-
83
@raw = JSON.json_dump(json)
-
83
@charset = @raw.encoding.name.downcase
-
end
-
-
26
def content_type
-
83
"application/json; charset=#{@charset}"
-
end
-
end
-
-
26
def encode(json)
-
83
Encoder.new(json)
-
end
-
-
26
def decode(response)
-
129
content_type = response.content_type.mime_type
-
-
129
raise HTTPX::Error, "invalid json mime type (#{content_type})" unless JSON_REGEX.match?(content_type)
-
-
113
method(:json_load)
-
end
-
-
# rubocop:disable Style/SingleLineMethods
-
26
if defined?(MultiJson)
-
4
def json_load(*args); MultiJson.load(*args); end
-
2
def json_dump(*args); MultiJson.dump(*args); end
-
24
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
-
23
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
-
23
require "json"
-
114
def json_load(*args); ::JSON.parse(*args); end
-
93
def json_dump(*args); ::JSON.dump(*args); end
-
end
-
# rubocop:enable Style/SingleLineMethods
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require_relative "multipart/encoder"
-
26
require_relative "multipart/decoder"
-
26
require_relative "multipart/part"
-
26
require_relative "multipart/mime_type_detector"
-
-
26
module HTTPX::Transcoder
-
26
module Multipart
-
26
MULTIPART_VALUE_COND = lambda do |value|
-
4878
value.respond_to?(:read) ||
-
3506
(value.respond_to?(:to_hash) &&
-
value.key?(:body) &&
-
644
(value.key?(:filename) || value.key?(:content_type)))
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "tempfile"
-
26
require "delegate"
-
-
26
module HTTPX
-
26
module Transcoder
-
26
module Multipart
-
26
class FilePart < SimpleDelegator
-
26
attr_reader :original_filename, :content_type
-
-
26
def initialize(filename, content_type)
-
32
@original_filename = filename
-
32
@content_type = content_type
-
32
@file = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
32
super(@file)
-
end
-
end
-
-
26
class Decoder
-
26
include HTTPX::Utils
-
-
26
CRLF = "\r\n"
-
26
BOUNDARY_RE = /;\s*boundary=([^;]+)/i.freeze
-
26
MULTIPART_CONTENT_TYPE = /Content-Type: (.*)#{CRLF}/ni.freeze
-
26
MULTIPART_CONTENT_DISPOSITION = /Content-Disposition:.*;\s*name=(#{VALUE})/ni.freeze
-
26
MULTIPART_CONTENT_ID = /Content-ID:\s*([^#{CRLF}]*)/ni.freeze
-
26
WINDOW_SIZE = 2 << 14
-
-
26
def initialize(response)
-
2
@boundary = begin
-
16
m = response.headers["content-type"].to_s[BOUNDARY_RE, 1]
-
16
raise Error, "no boundary declared in content-type header" unless m
-
-
16
m.strip
-
end
-
16
@buffer = "".b
-
16
@parts = {}
-
16
@intermediate_boundary = "--#{@boundary}"
-
16
@state = :idle
-
end
-
-
26
def call(response, *)
-
16
response.body.each do |chunk|
-
16
@buffer << chunk
-
-
16
parse
-
end
-
-
16
raise Error, "invalid or unsupported multipart format" unless @buffer.empty?
-
-
16
@parts
-
end
-
-
26
private
-
-
26
def parse
-
14
case @state
-
when :idle
-
16
raise Error, "payload does not start with boundary" unless @buffer.start_with?("#{@intermediate_boundary}#{CRLF}")
-
-
16
@buffer = @buffer.byteslice(@intermediate_boundary.bytesize + 2..-1)
-
-
16
@state = :part_header
-
when :part_header
-
48
idx = @buffer.index("#{CRLF}#{CRLF}")
-
-
# raise Error, "couldn't parse part headers" unless idx
-
48
return unless idx
-
-
48
head = @buffer.byteslice(0..idx + 4 - 1)
-
-
48
@buffer = @buffer.byteslice(head.bytesize..-1)
-
-
48
content_type = head[MULTIPART_CONTENT_TYPE, 1]
-
84
if (name = head[MULTIPART_CONTENT_DISPOSITION, 1])
-
48
name = /\A"(.*)"\Z/ =~ name ? Regexp.last_match(1) : name.dup
-
48
name.gsub!(/\\(.)/, "\\1")
-
12
name
-
else
-
name = head[MULTIPART_CONTENT_ID, 1]
-
end
-
-
48
filename = HTTPX::Utils.get_filename(head)
-
-
48
name = filename || +"#{content_type || "text/plain"}[]" if name.nil? || name.empty?
-
-
48
@current = name
-
-
42
@parts[name] = if filename
-
32
FilePart.new(filename, content_type)
-
else
-
16
"".b
-
end
-
-
48
@state = :part_body
-
when :part_body
-
48
part = @parts[@current]
-
-
48
body_separator = if part.is_a?(FilePart)
-
28
"#{CRLF}#{CRLF}"
-
else
-
16
CRLF
-
end
-
48
idx = @buffer.index(body_separator)
-
-
48
if idx
-
48
payload = @buffer.byteslice(0..idx - 1)
-
48
@buffer = @buffer.byteslice(idx + body_separator.bytesize..-1)
-
48
part << payload
-
48
part.rewind if part.respond_to?(:rewind)
-
48
@state = :parse_boundary
-
else
-
part << @buffer
-
@buffer.clear
-
end
-
when :parse_boundary
-
48
raise Error, "payload does not start with boundary" unless @buffer.start_with?(@intermediate_boundary)
-
-
48
@buffer = @buffer.byteslice(@intermediate_boundary.bytesize..-1)
-
-
48
if @buffer == "--"
-
16
@buffer.clear
-
16
@state = :done
-
16
return
-
31
elsif @buffer.start_with?(CRLF)
-
32
@buffer = @buffer.byteslice(2..-1)
-
32
@state = :part_header
-
else
-
return
-
end
-
when :done
-
raise Error, "parsing should have been over by now"
-
20
end until @buffer.empty?
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
26
module Transcoder::Multipart
-
26
class Encoder
-
26
attr_reader :bytesize
-
-
26
def initialize(form)
-
951
@boundary = ("-" * 21) << SecureRandom.hex(21)
-
951
@part_index = 0
-
951
@buffer = "".b
-
-
951
@form = form
-
951
@parts = to_parts(form)
-
end
-
-
26
def content_type
-
951
"multipart/form-data; boundary=#{@boundary}"
-
end
-
-
26
def to_s
-
18
read
-
ensure
-
18
rewind
-
end
-
-
26
def read(length = nil, outbuf = nil)
-
3794
data = String(outbuf).clear.force_encoding(Encoding::BINARY) if outbuf
-
3794
data ||= "".b
-
-
3794
read_chunks(data, length)
-
-
3794
data unless length && data.empty?
-
end
-
-
26
def rewind
-
50
form = @form.each_with_object([]) do |(key, val), aux|
-
50
if val.respond_to?(:path) && val.respond_to?(:reopen) && val.respond_to?(:closed?) && val.closed?
-
50
val = val.reopen(val.path, File::RDONLY)
-
end
-
50
val.rewind if val.respond_to?(:rewind)
-
50
aux << [key, val]
-
end
-
50
@form = form
-
50
@parts = to_parts(form)
-
50
@part_index = 0
-
end
-
-
26
private
-
-
26
def to_parts(form)
-
1001
@bytesize = 0
-
1001
params = form.each_with_object([]) do |(key, val), aux|
-
1193
Transcoder.normalize_keys(key, val, MULTIPART_VALUE_COND) do |k, v|
-
1193
next if v.nil?
-
-
1193
value, content_type, filename = Part.call(v)
-
-
1193
header = header_part(k, content_type, filename)
-
1049
@bytesize += header.size
-
1193
aux << header
-
-
1049
@bytesize += value.size
-
1193
aux << value
-
-
1193
delimiter = StringIO.new("\r\n")
-
1049
@bytesize += delimiter.size
-
1193
aux << delimiter
-
end
-
end
-
1001
final_delimiter = StringIO.new("--#{@boundary}--\r\n")
-
881
@bytesize += final_delimiter.size
-
1001
params << final_delimiter
-
-
1001
params
-
end
-
-
26
def header_part(key, content_type, filename)
-
1193
header = "--#{@boundary}\r\n".b
-
1193
header << "Content-Disposition: form-data; name=#{key.inspect}".b
-
1193
header << "; filename=#{filename.inspect}" if filename
-
1193
header << "\r\nContent-Type: #{content_type}\r\n\r\n"
-
1193
StringIO.new(header)
-
end
-
-
26
def read_chunks(buffer, length = nil)
-
4894
while @part_index < @parts.size
-
10860
chunk = read_from_part(length)
-
-
10860
next unless chunk
-
-
6328
buffer << chunk.force_encoding(Encoding::BINARY)
-
-
6328
next unless length
-
-
5522
length -= chunk.bytesize
-
-
6262
break if length.zero?
-
end
-
end
-
-
# if there's a current part to read from, tries to read a chunk.
-
26
def read_from_part(max_length = nil)
-
10860
part = @parts[@part_index]
-
-
10860
chunk = part.read(max_length, @buffer)
-
-
10860
return chunk if chunk && !chunk.empty?
-
-
4532
part.close if part.respond_to?(:close)
-
-
3980
@part_index += 1
-
-
1692
nil
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
26
module Transcoder::Multipart
-
26
module MimeTypeDetector
-
26
module_function
-
-
26
DEFAULT_MIMETYPE = "application/octet-stream"
-
-
# inspired by https://github.com/shrinerb/shrine/blob/master/lib/shrine/plugins/determine_mime_type.rb
-
26
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
-
24
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
-
-
23
elsif defined?(MimeMagic)
-
-
1
def call(file, _)
-
1
mime = MimeMagic.by_magic(file)
-
1
mime.type if mime
-
end
-
-
22
elsif system("which file", out: File::NULL)
-
23
require "open3"
-
-
23
def call(file, _)
-
677
return if file.eof? # file command returns "application/x-empty" for empty files
-
-
633
Open3.popen3(*%w[file --mime-type --brief -]) do |stdin, stdout, stderr, thread|
-
75
begin
-
633
::IO.copy_stream(file, stdin.binmode)
-
rescue Errno::EPIPE
-
end
-
633
file.rewind
-
633
stdin.close
-
-
633
status = thread.value
-
-
# call to file command failed
-
633
if status.nil? || !status.success?
-
$stderr.print(stderr.read)
-
else
-
-
633
output = stdout.read.strip
-
-
633
if output.include?("cannot open")
-
$stderr.print(output)
-
else
-
633
output
-
end
-
end
-
end
-
end
-
-
else
-
-
def call(_, _); end
-
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
26
module Transcoder::Multipart
-
26
module Part
-
26
module_function
-
-
26
def call(value)
-
# take out specialized objects of the way
-
1193
if value.respond_to?(:filename) && value.respond_to?(:content_type) && value.respond_to?(:read)
-
112
return value, value.content_type, value.filename
-
end
-
-
1065
content_type = filename = nil
-
-
1065
if value.is_a?(Hash)
-
322
content_type = value[:content_type]
-
322
filename = value[:filename]
-
322
value = value[:body]
-
end
-
-
1065
value = value.open(File::RDONLY) if Object.const_defined?(:Pathname) && value.is_a?(Pathname)
-
-
1065
if value.respond_to?(:path) && value.respond_to?(:read)
-
# either a File, a Tempfile, or something else which has to quack like a file
-
681
filename ||= File.basename(value.path)
-
681
content_type ||= MimeTypeDetector.call(value, filename) || "application/octet-stream"
-
681
[value, content_type, filename]
-
else
-
384
[StringIO.new(value.to_s), content_type || "text/plain", filename]
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require "stringio"
-
-
26
module HTTPX
-
26
module Transcoder
-
26
class BodyReader
-
26
def initialize(body)
-
210
@body = if body.respond_to?(:read)
-
20
body.rewind if body.respond_to?(:rewind)
-
20
body
-
189
elsif body.respond_to?(:each)
-
36
body.enum_for(:each)
-
else
-
154
StringIO.new(body.to_s)
-
end
-
end
-
-
26
def bytesize
-
402
return @body.bytesize if @body.respond_to?(:bytesize)
-
-
366
Float::INFINITY
-
end
-
-
26
def read(length = nil, outbuf = nil)
-
456
return @body.read(length, outbuf) if @body.respond_to?(:read)
-
-
begin
-
84
chunk = @body.next
-
48
if outbuf
-
48
outbuf.clear.force_encoding(Encoding::BINARY)
-
48
outbuf << chunk
-
else
-
outbuf = chunk
-
end
-
48
outbuf unless length && outbuf.empty?
-
24
rescue StopIteration
-
end
-
end
-
-
26
def close
-
48
@body.close if @body.respond_to?(:close)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
require_relative "body_reader"
-
-
26
module HTTPX
-
26
module Transcoder
-
26
class Deflater
-
26
attr_reader :content_type
-
-
26
def initialize(body)
-
84
@content_type = body.content_type
-
84
@body = BodyReader.new(body)
-
84
@closed = false
-
end
-
-
26
def bytesize
-
324
buffer_deflate!
-
-
324
@buffer.size
-
end
-
-
26
def read(length = nil, outbuf = nil)
-
416
return @buffer.read(length, outbuf) if @buffer
-
-
240
return if @closed
-
-
192
chunk = @body.read(length)
-
-
192
compressed_chunk = deflate(chunk)
-
-
192
return unless compressed_chunk
-
-
156
if outbuf
-
144
outbuf.clear.force_encoding(Encoding::BINARY)
-
144
outbuf << compressed_chunk
-
else
-
12
compressed_chunk
-
end
-
end
-
-
26
def close
-
48
return if @closed
-
-
48
@buffer.close if @buffer
-
-
48
@body.close
-
-
48
@closed = true
-
end
-
-
26
def rewind
-
28
return unless @buffer
-
-
16
@buffer.rewind
-
end
-
-
26
private
-
-
# rubocop:disable Naming/MemoizedInstanceVariableName
-
26
def buffer_deflate!
-
324
return @buffer if defined?(@buffer)
-
-
84
buffer = Response::Buffer.new(
-
threshold_size: Options::MAX_BODY_THRESHOLD_SIZE
-
)
-
84
::IO.copy_stream(self, buffer)
-
-
84
buffer.rewind if buffer.respond_to?(:rewind)
-
-
84
@buffer = buffer
-
end
-
# rubocop:enable Naming/MemoizedInstanceVariableName
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
26
module HTTPX
-
26
module Utils
-
26
using URIExtensions
-
-
26
TOKEN = %r{[^\s()<>,;:\\"/\[\]?=]+}.freeze
-
26
VALUE = /"(?:\\"|[^"])*"|#{TOKEN}/.freeze
-
26
FILENAME_REGEX = /\s*filename=(#{VALUE})/.freeze
-
26
FILENAME_EXTENSION_REGEX = /\s*filename\*=(#{VALUE})/.freeze
-
-
26
module_function
-
-
26
def now
-
2793851
Process.clock_gettime(Process::CLOCK_MONOTONIC)
-
end
-
-
26
def elapsed_time(monotonic_timestamp)
-
2762590
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.
-
26
def parse_retry_after(retry_after)
-
# first: bet on it being an integer
-
62
Integer(retry_after)
-
rescue ArgumentError
-
# Then it's a datetime
-
16
time = Time.httpdate(retry_after)
-
16
time - Time.now
-
end
-
-
26
def get_filename(header, _prefix_regex = nil)
-
88
filename = nil
-
77
case header
-
when FILENAME_REGEX
-
56
filename = Regexp.last_match(1)
-
56
filename = Regexp.last_match(1) if filename =~ /^"(.*)"$/
-
when FILENAME_EXTENSION_REGEX
-
16
filename = Regexp.last_match(1)
-
16
encoding, _, filename = filename.split("'", 3)
-
end
-
-
88
return unless filename
-
-
136
filename = URI::DEFAULT_PARSER.unescape(filename) if filename.scan(/%.?.?/).all? { |s| /%[0-9a-fA-F]{2}/.match?(s) }
-
-
72
filename.scrub!
-
-
72
filename = filename.gsub(/\\(.)/, '\1') unless /\\[^\\"]/.match?(filename)
-
-
72
filename.force_encoding ::Encoding.find(encoding) if encoding
-
-
72
filename
-
end
-
-
26
URIParser = URI::RFC2396_Parser.new
-
-
26
def to_uri(uri)
-
16697
return URI(uri) unless uri.is_a?(String) && !uri.ascii_only?
-
-
33
uri = URI(URIParser.escape(uri))
-
-
33
non_ascii_hostname = URIParser.unescape(uri.host)
-
-
33
non_ascii_hostname.force_encoding(Encoding::UTF_8)
-
-
33
idna_hostname = Punycode.encode_hostname(non_ascii_hostname)
-
-
33
uri.host = idna_hostname
-
32
uri.non_ascii_hostname = non_ascii_hostname
-
32
uri
-
end
-
end
-
end