-
# frozen_string_literal: true
-
-
23
require "httpx/version"
-
-
23
require "httpx/extensions"
-
-
23
require "httpx/errors"
-
23
require "httpx/utils"
-
23
require "httpx/punycode"
-
23
require "httpx/domain_name"
-
23
require "httpx/altsvc"
-
23
require "httpx/callbacks"
-
23
require "httpx/loggable"
-
23
require "httpx/transcoder"
-
23
require "httpx/timers"
-
23
require "httpx/pool"
-
23
require "httpx/headers"
-
23
require "httpx/request"
-
23
require "httpx/response"
-
23
require "httpx/options"
-
23
require "httpx/chainable"
-
-
# Top-Level Namespace
-
#
-
23
module HTTPX
-
23
EMPTY = [].freeze
-
-
# All plugins should be stored under this module/namespace. Can register and load
-
# plugins.
-
#
-
23
module Plugins
-
23
@plugins = {}
-
23
@plugins_mutex = Thread::Mutex.new
-
-
# Loads a plugin based on a name. If the plugin hasn't been loaded, tries to load
-
# it from the load path under "httpx/plugins/" directory.
-
#
-
23
def self.load_plugin(name)
-
3652
h = @plugins
-
3652
m = @plugins_mutex
-
7304
unless (plugin = m.synchronize { h[name] })
-
80
require "httpx/plugins/#{name}"
-
160
raise "Plugin #{name} hasn't been registered" unless (plugin = m.synchronize { h[name] })
-
end
-
3652
plugin
-
end
-
-
# Registers a plugin (+mod+) in the central store indexed by +name+.
-
#
-
23
def self.register_plugin(name, mod)
-
225
h = @plugins
-
225
m = @plugins_mutex
-
424
m.synchronize { h[name] = mod }
-
end
-
end
-
-
23
extend Chainable
-
end
-
-
23
require "httpx/session"
-
23
require "httpx/session_extensions"
-
-
# load integrations when possible
-
-
23
require "httpx/adapters/datadog" if defined?(DDTrace) || defined?(Datadog)
-
23
require "httpx/adapters/sentry" if defined?(Sentry)
-
23
require "httpx/adapters/webmock" if defined?(WebMock)
-
# frozen_string_literal: true
-
-
5
require "datadog/tracing/contrib/integration"
-
5
require "datadog/tracing/contrib/configuration/settings"
-
5
require "datadog/tracing/contrib/patcher"
-
-
5
module Datadog::Tracing
-
5
module Contrib
-
5
module HTTPX
-
5
DATADOG_VERSION = defined?(::DDTrace) ? ::DDTrace::VERSION : ::Datadog::VERSION
-
-
5
METADATA_MODULE = Datadog::Tracing::Metadata
-
-
5
TYPE_OUTBOUND = Datadog::Tracing::Metadata::Ext::HTTP::TYPE_OUTBOUND
-
-
5
TAG_PEER_SERVICE = Datadog::Tracing::Metadata::Ext::TAG_PEER_SERVICE
-
-
5
TAG_URL = Datadog::Tracing::Metadata::Ext::HTTP::TAG_URL
-
5
TAG_METHOD = Datadog::Tracing::Metadata::Ext::HTTP::TAG_METHOD
-
5
TAG_TARGET_HOST = Datadog::Tracing::Metadata::Ext::NET::TAG_TARGET_HOST
-
5
TAG_TARGET_PORT = Datadog::Tracing::Metadata::Ext::NET::TAG_TARGET_PORT
-
-
5
TAG_STATUS_CODE = Datadog::Tracing::Metadata::Ext::HTTP::TAG_STATUS_CODE
-
-
# HTTPX Datadog Plugin
-
#
-
# Enables tracing for httpx requests.
-
#
-
# A span will be created for each request transaction; the span is created lazily only when
-
# receiving a response, and it is fed the start time stored inside the tracer object.
-
#
-
5
module Plugin
-
5
class RequestTracer
-
5
include Contrib::HttpAnnotationHelper
-
-
5
SPAN_REQUEST = "httpx.request"
-
-
# initializes the tracer object on the +request+.
-
5
def initialize(request)
-
106
@request = request
-
106
@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.
-
123
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.
-
193
request.on(:headers) { call }
-
end
-
-
# sets up the span start time, while preparing the on response callback.
-
5
def call(*args)
-
93
return if @start_time
-
-
88
start(*args)
-
-
88
@request.once(:response, &method(:finish))
-
end
-
-
5
private
-
-
# just sets the span init time. It can be passed a +start_time+ in cases where
-
# this is collected outside the request transaction.
-
5
def start(start_time = now)
-
93
@start_time = start_time
-
end
-
-
# resets the start time for already finished request transactions.
-
5
def reset
-
17
return unless @start_time
-
-
5
start
-
end
-
-
# creates the span from the collected +@start_time+ to what the +response+ state
-
# contains. It also resets internal state to allow this object to be reused.
-
5
def finish(response)
-
88
return unless @start_time
-
-
88
span = initialize_span
-
-
88
return unless span
-
-
88
if response.is_a?(::HTTPX::ErrorResponse)
-
6
span.set_error(response.error)
-
else
-
82
span.set_tag(TAG_STATUS_CODE, response.status.to_s)
-
-
82
span.set_error(::HTTPX::HTTPError.new(response)) if response.status >= 400 && response.status <= 599
-
end
-
-
88
span.finish
-
ensure
-
88
@start_time = nil
-
end
-
-
# return a span initialized with the +@request+ state.
-
5
def initialize_span
-
88
verb = @request.verb
-
88
uri = @request.uri
-
-
88
span = create_span(@request)
-
-
88
span.resource = verb
-
-
# Add additional request specific tags to the span.
-
-
88
span.set_tag(TAG_URL, @request.path)
-
88
span.set_tag(TAG_METHOD, verb)
-
-
88
span.set_tag(TAG_TARGET_HOST, uri.host)
-
88
span.set_tag(TAG_TARGET_PORT, uri.port.to_s)
-
-
# Tag as an external peer service
-
88
span.set_tag(TAG_PEER_SERVICE, span.service)
-
-
88
if configuration[:distributed_tracing]
-
83
propagate_trace_http(
-
Datadog::Tracing.active_trace.to_digest,
-
@request.headers
-
)
-
end
-
-
# Set analytics sample rate
-
88
if Contrib::Analytics.enabled?(configuration[:analytics_enabled])
-
10
Contrib::Analytics.set_sample_rate(span, configuration[:analytics_sample_rate])
-
end
-
-
88
span
-
rescue StandardError => e
-
Datadog.logger.error("error preparing span for http request: #{e}")
-
Datadog.logger.error(e.backtrace)
-
end
-
-
5
def now
-
87
::Datadog::Core::Utils::Time.now.utc
-
end
-
-
5
def configuration
-
274
@configuration ||= Datadog.configuration.tracing[:httpx, @request.uri.host]
-
end
-
-
5
if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("2.0.0.beta1")
-
2
def propagate_trace_http(digest, headers)
-
30
Datadog::Tracing::Contrib::HTTP.inject(digest, headers)
-
end
-
-
2
def create_span(request)
-
32
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)
-
53
Datadog::Tracing::Propagation::HTTP.inject!(digest, headers)
-
end
-
-
3
def create_span(request)
-
56
Datadog::Tracing.trace(
-
SPAN_REQUEST,
-
service: service_name(request.uri.host, configuration, Datadog.configuration_for(self)),
-
span_type: TYPE_OUTBOUND,
-
start_time: @start_time
-
)
-
end
-
end
-
end
-
-
5
module RequestMethods
-
# intercepts request initialization to inject the tracing logic.
-
5
def initialize(*)
-
100
super
-
-
100
return unless Datadog::Tracing.enabled?
-
-
100
RequestTracer.new(self)
-
end
-
end
-
-
5
module ConnectionMethods
-
5
attr_reader :init_time
-
-
5
def initialize(*)
-
91
super
-
-
91
@init_time = ::Datadog::Core::Utils::Time.now.utc
-
end
-
-
# handles the case when the +error+ happened during name resolution, which meanns
-
# that the tracing logic hasn't been injected yet; in such cases, the approximate
-
# initial resolving time is collected from the connection, and used as span start time,
-
# and the tracing object in inserted before the on response callback is called.
-
5
def handle_error(error)
-
6
return super unless Datadog::Tracing.enabled?
-
-
6
return super unless error.respond_to?(:connection)
-
-
6
@pending.each do |request|
-
6
RequestTracer.new(request).call(error.connection.init_time)
-
end
-
-
6
super
-
end
-
end
-
end
-
-
5
module Configuration
-
# Default settings for httpx
-
#
-
5
class Settings < Datadog::Tracing::Contrib::Configuration::Settings
-
5
DEFAULT_ERROR_HANDLER = lambda do |response|
-
Datadog::Ext::HTTP::ERROR_RANGE.cover?(response.status)
-
end
-
-
5
option :service_name, default: "httpx"
-
5
option :distributed_tracing, default: true
-
5
option :split_by_domain, default: false
-
-
5
if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
-
5
option :enabled do |o|
-
5
o.type :bool
-
5
o.env "DD_TRACE_HTTPX_ENABLED"
-
5
o.default true
-
end
-
-
5
option :analytics_enabled do |o|
-
5
o.type :bool
-
5
o.env "DD_TRACE_HTTPX_ANALYTICS_ENABLED"
-
5
o.default false
-
end
-
-
5
option :analytics_sample_rate do |o|
-
5
o.type :float
-
5
o.env "DD_TRACE_HTTPX_ANALYTICS_SAMPLE_RATE"
-
5
o.default 1.0
-
end
-
else
-
option :enabled do |o|
-
o.default { env_to_bool("DD_TRACE_HTTPX_ENABLED", true) }
-
o.lazy
-
end
-
-
option :analytics_enabled do |o|
-
o.default { env_to_bool(%w[DD_TRACE_HTTPX_ANALYTICS_ENABLED DD_HTTPX_ANALYTICS_ENABLED], false) }
-
o.lazy
-
end
-
-
option :analytics_sample_rate do |o|
-
o.default { env_to_float(%w[DD_TRACE_HTTPX_ANALYTICS_SAMPLE_RATE DD_HTTPX_ANALYTICS_SAMPLE_RATE], 1.0) }
-
o.lazy
-
end
-
end
-
-
5
if defined?(Datadog::Tracing::Contrib::SpanAttributeSchema)
-
5
option :service_name do |o|
-
5
o.default do
-
56
Datadog::Tracing::Contrib::SpanAttributeSchema.fetch_service_name(
-
"DD_TRACE_HTTPX_SERVICE_NAME",
-
"httpx"
-
)
-
end
-
5
o.lazy unless Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
-
end
-
else
-
option :service_name do |o|
-
o.default do
-
ENV.fetch("DD_TRACE_HTTPX_SERVICE_NAME", "httpx")
-
end
-
o.lazy unless Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
-
end
-
end
-
-
5
option :distributed_tracing, default: true
-
-
5
if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.15.0")
-
5
option :error_handler do |o|
-
5
o.type :proc
-
5
o.default_proc(&DEFAULT_ERROR_HANDLER)
-
end
-
elsif Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
-
option :error_handler do |o|
-
o.type :proc
-
o.experimental_default_proc(&DEFAULT_ERROR_HANDLER)
-
end
-
else
-
option :error_handler, default: DEFAULT_ERROR_HANDLER
-
end
-
end
-
end
-
-
# Patcher enables patching of 'httpx' with datadog components.
-
#
-
5
module Patcher
-
5
include Datadog::Tracing::Contrib::Patcher
-
-
5
module_function
-
-
5
def target_version
-
10
Integration.version
-
end
-
-
# loads a session instannce with the datadog plugin, and replaces the
-
# base HTTPX::Session with the patched session class.
-
5
def patch
-
5
datadog_session = ::HTTPX.plugin(Plugin)
-
-
5
::HTTPX.send(:remove_const, :Session)
-
5
::HTTPX.send(:const_set, :Session, datadog_session.class)
-
end
-
end
-
-
# Datadog Integration for HTTPX.
-
#
-
5
class Integration
-
5
include Contrib::Integration
-
-
5
MINIMUM_VERSION = Gem::Version.new("0.10.2")
-
-
5
register_as :httpx
-
-
5
def self.version
-
205
Gem.loaded_specs["httpx"] && Gem.loaded_specs["httpx"].version
-
end
-
-
5
def self.loaded?
-
65
defined?(::HTTPX::Request)
-
end
-
-
5
def self.compatible?
-
65
super && version >= MINIMUM_VERSION
-
end
-
-
5
def new_configuration
-
66
Configuration::Settings.new
-
end
-
-
5
def patcher
-
130
Patcher
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
7
require "delegate"
-
7
require "httpx"
-
7
require "faraday"
-
-
7
module Faraday
-
7
class Adapter
-
7
class HTTPX < Faraday::Adapter
-
7
module RequestMixin
-
7
def build_connection(env)
-
163
return @connection if defined?(@connection)
-
-
163
@connection = ::HTTPX.plugin(:persistent).plugin(ReasonPlugin)
-
163
@connection = @connection.with(@connection_options) unless @connection_options.empty?
-
163
connection_opts = options_from_env(env)
-
-
163
if (bind = env.request.bind)
-
6
@bind = TCPSocket.new(bind[:host], bind[:port])
-
5
connection_opts[:io] = @bind
-
end
-
163
@connection = @connection.with(connection_opts)
-
-
163
if (proxy = env.request.proxy)
-
6
proxy_options = { uri: proxy.uri }
-
6
proxy_options[:username] = proxy.user if proxy.user
-
6
proxy_options[:password] = proxy.password if proxy.password
-
-
6
@connection = @connection.plugin(:proxy).with(proxy: proxy_options)
-
end
-
163
@connection = @connection.plugin(OnDataPlugin) if env.request.stream_response?
-
-
163
@connection
-
end
-
-
7
def close
-
168
@connection.close if @connection
-
168
@bind.close if @bind
-
end
-
-
7
private
-
-
7
def connect(env, &blk)
-
163
connection(env, &blk)
-
rescue ::HTTPX::TLSError => e
-
6
raise Faraday::SSLError, e
-
rescue Errno::ECONNABORTED,
-
Errno::ECONNREFUSED,
-
Errno::ECONNRESET,
-
Errno::EHOSTUNREACH,
-
Errno::EINVAL,
-
Errno::ENETUNREACH,
-
Errno::EPIPE,
-
::HTTPX::ConnectionError => e
-
6
raise Faraday::ConnectionFailed, e
-
end
-
-
7
def build_request(env)
-
169
meth = env[:method]
-
-
28
request_options = {
-
141
headers: env.request_headers,
-
body: env.body,
-
}
-
169
[meth.to_s.upcase, env.url, request_options]
-
end
-
-
7
def options_from_env(env)
-
163
timeout_options = {}
-
163
req_opts = env.request
-
163
if (sec = request_timeout(:read, req_opts))
-
5
timeout_options[:read_timeout] = sec
-
end
-
-
163
if (sec = request_timeout(:write, req_opts))
-
5
timeout_options[:write_timeout] = sec
-
end
-
-
163
if (sec = request_timeout(:open, req_opts))
-
5
timeout_options[:connect_timeout] = sec
-
end
-
-
27
{
-
136
ssl: ssl_options_from_env(env),
-
timeout: timeout_options,
-
}
-
end
-
-
7
if defined?(::OpenSSL)
-
7
def ssl_options_from_env(env)
-
163
ssl_options = {}
-
-
163
unless env.ssl.verify.nil?
-
10
ssl_options[:verify_mode] = env.ssl.verify ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
-
end
-
-
163
ssl_options[:ca_file] = env.ssl.ca_file if env.ssl.ca_file
-
163
ssl_options[:ca_path] = env.ssl.ca_path if env.ssl.ca_path
-
163
ssl_options[:cert_store] = env.ssl.cert_store if env.ssl.cert_store
-
163
ssl_options[:cert] = env.ssl.client_cert if env.ssl.client_cert
-
163
ssl_options[:key] = env.ssl.client_key if env.ssl.client_key
-
163
ssl_options[:ssl_version] = env.ssl.version if env.ssl.version
-
163
ssl_options[:verify_depth] = env.ssl.verify_depth if env.ssl.verify_depth
-
163
ssl_options[:min_version] = env.ssl.min_version if env.ssl.min_version
-
163
ssl_options[:max_version] = env.ssl.max_version if env.ssl.max_version
-
163
ssl_options
-
end
-
else
-
def ssl_options_from_env(*)
-
{}
-
end
-
end
-
end
-
-
7
include RequestMixin
-
-
7
module OnDataPlugin
-
7
module RequestMethods
-
7
attr_writer :response_on_data
-
-
7
def response=(response)
-
12
super
-
-
12
return if response.is_a?(::HTTPX::ErrorResponse)
-
-
12
response.body.on_data = @response_on_data
-
end
-
end
-
-
7
module ResponseBodyMethods
-
7
attr_writer :on_data
-
-
7
def write(chunk)
-
24
return super unless @on_data
-
-
24
@on_data.call(chunk, chunk.bytesize)
-
end
-
end
-
end
-
-
7
module ReasonPlugin
-
7
def self.load_dependencies(*)
-
163
require "net/http/status"
-
end
-
-
7
module ResponseMethods
-
7
def reason
-
133
Net::HTTP::STATUS_CODES.fetch(@status)
-
end
-
end
-
end
-
-
7
class ParallelManager
-
7
class ResponseHandler < SimpleDelegator
-
7
attr_reader :env
-
-
7
def initialize(env)
-
24
@env = env
-
24
super
-
end
-
-
7
def on_response(&blk)
-
48
if blk
-
24
@on_response = ->(response) do
-
24
blk.call(response)
-
end
-
24
self
-
else
-
24
@on_response
-
end
-
end
-
-
7
def on_complete(&blk)
-
48
if blk
-
24
@on_complete = blk
-
24
self
-
else
-
24
@on_complete
-
end
-
end
-
end
-
-
7
include RequestMixin
-
-
7
def initialize(options)
-
24
@handlers = []
-
24
@connection_options = options
-
end
-
-
7
def enqueue(request)
-
24
handler = ResponseHandler.new(request)
-
24
@handlers << handler
-
24
handler
-
end
-
-
7
def run
-
24
return unless @handlers.last
-
-
18
env = @handlers.last.env
-
-
18
connect(env) do |session|
-
42
requests = @handlers.map { |handler| session.build_request(*build_request(handler.env)) }
-
-
18
if env.request.stream_response?
-
6
requests.each do |request|
-
6
request.response_on_data = env.request.on_data
-
end
-
end
-
-
18
responses = session.request(*requests)
-
18
Array(responses).each_with_index do |response, index|
-
24
handler = @handlers[index]
-
24
handler.on_response.call(response)
-
24
handler.on_complete.call(handler.env)
-
end
-
end
-
rescue ::HTTPX::TimeoutError => e
-
raise Faraday::TimeoutError, e
-
end
-
-
# from Faraday::Adapter#connection
-
7
def connection(env)
-
18
conn = build_connection(env)
-
18
return conn unless block_given?
-
-
18
yield conn
-
end
-
-
7
private
-
-
# from Faraday::Adapter#request_timeout
-
7
def request_timeout(type, options)
-
54
key = Faraday::Adapter::TIMEOUT_KEYS[type]
-
54
options[key] || options[:timeout]
-
end
-
end
-
-
7
self.supports_parallel = true
-
-
7
class << self
-
7
def setup_parallel_manager(options = {})
-
24
ParallelManager.new(options)
-
end
-
end
-
-
7
def call(env)
-
169
super
-
169
if parallel?(env)
-
24
handler = env[:parallel_manager].enqueue(env)
-
24
handler.on_response do |response|
-
24
if response.is_a?(::HTTPX::Response)
-
18
save_response(env, response.status, response.body.to_s, response.headers, response.reason) do |response_headers|
-
18
response_headers.merge!(response.headers)
-
end
-
else
-
5
env[:error] = response.error
-
6
save_response(env, 0, "", {}, nil)
-
end
-
end
-
20
return handler
-
end
-
-
145
response = connect_and_request(env)
-
115
save_response(env, response.status, response.body.to_s, response.headers, response.reason) do |response_headers|
-
115
response_headers.merge!(response.headers)
-
end
-
115
@app.call(env)
-
end
-
-
7
private
-
-
7
def connect_and_request(env)
-
145
connect(env) do |session|
-
145
request = session.build_request(*build_request(env))
-
-
145
request.response_on_data = env.request.on_data if env.request.stream_response?
-
-
145
response = session.request(request)
-
# do not call #raise_for_status for HTTP 4xx or 5xx, as faraday has a middleware for that.
-
145
response.raise_for_status unless response.is_a?(::HTTPX::Response)
-
115
response
-
end
-
rescue ::HTTPX::TimeoutError => e
-
18
raise Faraday::TimeoutError, e
-
end
-
-
7
def parallel?(env)
-
169
env[:parallel_manager]
-
end
-
end
-
-
7
register_middleware httpx: HTTPX
-
end
-
end
-
# frozen_string_literal: true
-
-
5
require "sentry-ruby"
-
-
5
module HTTPX::Plugins
-
5
module Sentry
-
5
module Tracer
-
5
module_function
-
-
5
def call(request)
-
88
sentry_span = start_sentry_span
-
-
88
return unless sentry_span
-
-
88
set_sentry_trace_header(request, sentry_span)
-
-
88
request.on(:response, &method(:finish_sentry_span).curry(3)[sentry_span, request])
-
end
-
-
5
def start_sentry_span
-
88
return unless ::Sentry.initialized? && (span = ::Sentry.get_current_scope.get_span)
-
88
return if span.sampled == false
-
-
88
span.start_child(op: "httpx.client", start_timestamp: ::Sentry.utc_now.to_f)
-
end
-
-
5
def set_sentry_trace_header(request, sentry_span)
-
88
return unless sentry_span
-
-
88
config = ::Sentry.configuration
-
88
url = request.uri.to_s
-
-
176
return unless config.propagate_traces && config.trace_propagation_targets.any? { |target| url.match?(target) }
-
-
88
trace = ::Sentry.get_current_client.generate_sentry_trace(sentry_span)
-
88
request.headers[::Sentry::SENTRY_TRACE_HEADER_NAME] = trace if trace
-
end
-
-
5
def finish_sentry_span(span, request, response)
-
96
return unless ::Sentry.initialized?
-
-
96
record_sentry_breadcrumb(request, response)
-
96
record_sentry_span(request, response, span)
-
end
-
-
5
def record_sentry_breadcrumb(req, res)
-
96
return unless ::Sentry.configuration.breadcrumbs_logger.include?(:http_logger)
-
-
96
request_info = extract_request_info(req)
-
-
96
data = if res.is_a?(HTTPX::ErrorResponse)
-
9
{ error: res.error.message, **request_info }
-
else
-
87
{ status: res.status, **request_info }
-
end
-
-
96
crumb = ::Sentry::Breadcrumb.new(
-
level: :info,
-
category: "httpx",
-
type: :info,
-
data: data
-
)
-
96
::Sentry.add_breadcrumb(crumb)
-
end
-
-
5
def record_sentry_span(req, res, sentry_span)
-
96
return unless sentry_span
-
-
96
request_info = extract_request_info(req)
-
96
sentry_span.set_description("#{request_info[:method]} #{request_info[:url]}")
-
96
if res.is_a?(HTTPX::ErrorResponse)
-
9
sentry_span.set_data(:error, res.error.message)
-
else
-
87
sentry_span.set_data(:status, res.status)
-
end
-
96
sentry_span.set_timestamp(::Sentry.utc_now.to_f)
-
end
-
-
5
def extract_request_info(req)
-
192
uri = req.uri
-
-
result = {
-
192
method: req.verb,
-
}
-
-
192
if ::Sentry.configuration.send_default_pii
-
20
uri += "?#{req.query}" unless req.query.empty?
-
20
result[:body] = req.body.to_s unless req.body.empty? || req.body.unbounded_body?
-
end
-
-
192
result[:url] = uri.to_s
-
-
192
result
-
end
-
end
-
-
5
module RequestMethods
-
5
def __sentry_enable_trace!
-
96
return if @__sentry_enable_trace
-
-
88
Tracer.call(self)
-
88
@__sentry_enable_trace = true
-
end
-
end
-
-
5
module ConnectionMethods
-
5
def send(request)
-
96
request.__sentry_enable_trace!
-
-
96
super
-
end
-
end
-
end
-
end
-
-
5
Sentry.register_patch(:httpx) do
-
25
sentry_session = HTTPX.plugin(HTTPX::Plugins::Sentry)
-
-
25
HTTPX.send(:remove_const, :Session)
-
25
HTTPX.send(:const_set, :Session, sentry_session.class)
-
end
-
# frozen_string_literal: true
-
-
6
module WebMock
-
6
module HttpLibAdapters
-
6
require "net/http/status"
-
6
HTTP_REASONS = Net::HTTP::STATUS_CODES
-
-
#
-
# HTTPX plugin for webmock.
-
#
-
# Requests are "hijacked" at the session, before they're distributed to a connection.
-
#
-
6
module Plugin
-
6
class << self
-
6
def build_webmock_request_signature(request)
-
126
uri = WebMock::Util::URI.heuristic_parse(request.uri)
-
126
uri.query = request.query
-
126
uri.path = uri.normalized_path.gsub("[^:]//", "/")
-
-
126
WebMock::RequestSignature.new(
-
request.verb.downcase.to_sym,
-
uri.to_s,
-
body: request.body.each.to_a.join,
-
headers: request.headers.to_h
-
)
-
end
-
-
6
def build_webmock_response(_request, response)
-
5
webmock_response = WebMock::Response.new
-
5
webmock_response.status = [response.status, HTTP_REASONS[response.status]]
-
5
webmock_response.body = response.body.to_s
-
5
webmock_response.headers = response.headers.to_h
-
5
webmock_response
-
end
-
-
6
def build_from_webmock_response(request, webmock_response)
-
116
return build_error_response(request, HTTPX::TimeoutError.new(1, "Timed out")) if webmock_response.should_timeout
-
-
101
return build_error_response(request, webmock_response.exception) if webmock_response.exception
-
-
96
request.options.response_class.new(request,
-
webmock_response.status[0],
-
"2.0",
-
webmock_response.headers).tap do |res|
-
96
res.mocked = true
-
end
-
end
-
-
6
def build_error_response(request, exception)
-
20
HTTPX::ErrorResponse.new(request, exception, request.options)
-
end
-
end
-
-
6
module InstanceMethods
-
6
def init_connection(*)
-
101
connection = super
-
101
connection.once(:unmock_connection) do
-
5
unless connection.addresses
-
5
connection.__send__(:callbacks)[:connect_error].clear
-
5
pool.__send__(:unregister_connection, connection)
-
end
-
5
pool.__send__(:resolve_connection, connection)
-
end
-
101
connection
-
end
-
end
-
-
6
module ResponseMethods
-
6
attr_accessor :mocked
-
-
6
def initialize(*)
-
101
super
-
101
@mocked = false
-
end
-
end
-
-
6
module ResponseBodyMethods
-
6
def decode_chunk(chunk)
-
50
return chunk if @response.mocked
-
-
5
super
-
end
-
end
-
-
6
module ConnectionMethods
-
6
def initialize(*)
-
101
super
-
101
@mocked = true
-
end
-
-
6
def open?
-
106
return true if @mocked
-
-
5
super
-
end
-
-
6
def interests
-
4313
return if @mocked
-
-
40
super
-
end
-
-
6
def send(request)
-
126
request_signature = Plugin.build_webmock_request_signature(request)
-
126
WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
-
-
126
if (mock_response = WebMock::StubRegistry.instance.response_for_request(request_signature))
-
116
response = Plugin.build_from_webmock_response(request, mock_response)
-
116
WebMock::CallbackRegistry.invoke_callbacks({ lib: :httpx }, request_signature, mock_response)
-
116
log { "mocking #{request.uri} with #{mock_response.inspect}" }
-
116
request.response = response
-
116
request.emit(:response, response)
-
116
response << mock_response.body.dup unless response.is_a?(HTTPX::ErrorResponse)
-
10
elsif WebMock.net_connect_allowed?(request_signature.uri)
-
5
if WebMock::CallbackRegistry.any_callbacks?
-
5
request.on(:response) do |resp|
-
5
unless resp.is_a?(HTTPX::ErrorResponse)
-
5
webmock_response = Plugin.build_webmock_response(request, resp)
-
5
WebMock::CallbackRegistry.invoke_callbacks(
-
{ lib: :httpx, real_request: true }, request_signature,
-
webmock_response
-
)
-
end
-
end
-
end
-
5
@mocked = false
-
5
emit(:unmock_connection, self)
-
5
super
-
else
-
5
raise WebMock::NetConnectNotAllowedError, request_signature
-
end
-
end
-
end
-
end
-
-
6
class HttpxAdapter < HttpLibAdapter
-
6
adapter_for :httpx
-
-
6
class << self
-
6
def enable!
-
247
@original_session ||= HTTPX::Session
-
-
247
webmock_session = HTTPX.plugin(Plugin)
-
-
247
HTTPX.send(:remove_const, :Session)
-
247
HTTPX.send(:const_set, :Session, webmock_session.class)
-
end
-
-
6
def disable!
-
247
return unless @original_session
-
-
241
HTTPX.send(:remove_const, :Session)
-
241
HTTPX.send(:const_set, :Session, @original_session)
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "strscan"
-
-
23
module HTTPX
-
23
module AltSvc
-
# makes connections able to accept requests destined to primary service.
-
23
module ConnectionMixin
-
23
using URIExtensions
-
-
23
def send(request)
-
6
request.headers["alt-used"] = @origin.authority if @parser && !@write_buffer.full? && match_altsvcs?(request.uri)
-
-
6
super
-
end
-
-
23
def match?(uri, options)
-
6
return false if !used? && (@state == :closing || @state == :closed)
-
-
6
match_altsvcs?(uri) && match_altsvc_options?(uri, options)
-
end
-
-
23
private
-
-
# checks if this is connection is an alternative service of
-
# +uri+
-
23
def match_altsvcs?(uri)
-
18
@origins.any? { |origin| altsvc_match?(uri, origin) } ||
-
AltSvc.cached_altsvc(@origin).any? do |altsvc|
-
origin = altsvc["origin"]
-
altsvc_match?(origin, uri.origin)
-
end
-
end
-
-
23
def match_altsvc_options?(uri, options)
-
6
return @options == options unless @options.ssl.all? do |k, v|
-
6
v == (k == :hostname ? uri.host : options.ssl[k])
-
end
-
-
6
@options.options_equals?(options, Options::REQUEST_BODY_IVARS + %i[@ssl])
-
end
-
-
23
def altsvc_match?(uri, other_uri)
-
12
other_uri = URI(other_uri)
-
-
12
uri.origin == other_uri.origin || begin
-
5
case uri.scheme
-
when "h2"
-
(other_uri.scheme == "https" || other_uri.scheme == "h2") &&
-
uri.host == other_uri.host &&
-
uri.port == other_uri.port
-
else
-
6
false
-
end
-
end
-
end
-
end
-
-
23
@altsvc_mutex = Thread::Mutex.new
-
38
@altsvcs = Hash.new { |h, k| h[k] = [] }
-
-
23
module_function
-
-
23
def cached_altsvc(origin)
-
30
now = Utils.now
-
30
@altsvc_mutex.synchronize do
-
30
lookup(origin, now)
-
end
-
end
-
-
23
def cached_altsvc_set(origin, entry)
-
18
now = Utils.now
-
18
@altsvc_mutex.synchronize do
-
18
return if @altsvcs[origin].any? { |altsvc| altsvc["origin"] == entry["origin"] }
-
-
18
entry["TTL"] = Integer(entry["ma"]) + now if entry.key?("ma")
-
18
@altsvcs[origin] << entry
-
18
entry
-
end
-
end
-
-
23
def lookup(origin, ttl)
-
30
return [] unless @altsvcs.key?(origin)
-
-
20
@altsvcs[origin] = @altsvcs[origin].select do |entry|
-
18
!entry.key?("TTL") || entry["TTL"] > ttl
-
end
-
36
@altsvcs[origin].reject { |entry| entry["noop"] }
-
end
-
-
23
def emit(request, response)
-
5555
return unless response.respond_to?(:headers)
-
# Alt-Svc
-
5534
return unless response.headers.key?("alt-svc")
-
-
64
origin = request.origin
-
64
host = request.uri.host
-
-
64
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).
-
64
if altsvc == "clear"
-
6
@altsvc_mutex.synchronize do
-
6
@altsvcs[origin].clear
-
end
-
-
5
return
-
end
-
-
58
parse(altsvc) do |alt_origin, alt_params|
-
6
alt_origin.host ||= host
-
6
yield(alt_origin, origin, alt_params)
-
end
-
end
-
-
23
def parse(altsvc)
-
142
return enum_for(__method__, altsvc) unless block_given?
-
-
100
scanner = StringScanner.new(altsvc)
-
106
until scanner.eos?
-
100
alt_service = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
-
-
100
alt_params = []
-
100
loop do
-
118
alt_param = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
-
118
alt_params << alt_param.strip if alt_param
-
118
scanner.skip(/;/)
-
118
break if scanner.eos? || scanner.scan(/ *, */)
-
end
-
200
alt_params = Hash[alt_params.map { |field| field.split("=") }]
-
-
100
alt_proto, alt_authority = alt_service.split("=")
-
100
alt_origin = parse_altsvc_origin(alt_proto, alt_authority)
-
100
return unless alt_origin
-
-
36
yield(alt_origin, alt_params.merge("proto" => alt_proto))
-
end
-
end
-
-
23
def parse_altsvc_scheme(alt_proto)
-
101
case alt_proto
-
when "h2c"
-
6
"http"
-
when "h2"
-
42
"https"
-
end
-
end
-
-
23
def parse_altsvc_origin(alt_proto, alt_origin)
-
100
alt_scheme = parse_altsvc_scheme(alt_proto)
-
-
100
return unless alt_scheme
-
-
36
alt_origin = alt_origin[1..-2] if alt_origin.start_with?("\"") && alt_origin.end_with?("\"")
-
-
36
URI.parse("#{alt_scheme}://#{alt_origin}")
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
-
23
module HTTPX
-
# Internal class to abstract a string buffer, by wrapping a string and providing the
-
# minimum possible API and functionality required.
-
#
-
# buffer = Buffer.new(640)
-
# buffer.full? #=> false
-
# buffer << "aa"
-
# buffer.capacity #=> 638
-
#
-
23
class Buffer
-
23
extend Forwardable
-
-
23
def_delegator :@buffer, :<<
-
-
23
def_delegator :@buffer, :to_s
-
-
23
def_delegator :@buffer, :to_str
-
-
23
def_delegator :@buffer, :empty?
-
-
23
def_delegator :@buffer, :bytesize
-
-
23
def_delegator :@buffer, :clear
-
-
23
def_delegator :@buffer, :replace
-
-
23
attr_reader :limit
-
-
23
def initialize(limit)
-
10783
@buffer = "".b
-
10783
@limit = limit
-
end
-
-
23
def full?
-
1568611
@buffer.bytesize >= @limit
-
end
-
-
23
def capacity
-
10
@limit - @buffer.bytesize
-
end
-
-
23
def shift!(fin)
-
15896
@buffer = @buffer.byteslice(fin..-1) || "".b
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Callbacks
-
23
def on(type, &action)
-
208140
callbacks(type) << action
-
208140
self
-
end
-
-
23
def once(type, &block)
-
82623
on(type) do |*args, &callback|
-
81732
block.call(*args, &callback)
-
81684
:delete
-
end
-
82623
self
-
end
-
-
23
def only(type, &block)
-
15381
callbacks(type).clear
-
15381
on(type, &block)
-
end
-
-
23
def emit(type, *args)
-
230405
callbacks(type).delete_if { |pr| :delete == pr.call(*args) } # rubocop:disable Style/YodaCondition
-
end
-
-
23
def callbacks_for?(type)
-
2270
@callbacks.key?(type) && @callbacks[type].any?
-
end
-
-
23
protected
-
-
23
def callbacks(type = nil)
-
324790
return @callbacks unless type
-
-
468615
@callbacks ||= Hash.new { |h, k| h[k] = [] }
-
324707
@callbacks[type]
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
# Session mixin, implements most of the APIs that the users call.
-
# delegates to a default session when extended.
-
23
module Chainable
-
23
%w[head get post put delete trace options connect patch].each do |meth|
-
207
class_eval(<<-MOD, __FILE__, __LINE__ + 1)
-
9
def #{meth}(*uri, **options) # def get(*uri, **options)
-
9
request("#{meth.upcase}", uri, **options) # request("GET", uri, **options)
-
end # end
-
MOD
-
end
-
-
# delegates to the default session (see HTTPX::Session#request).
-
23
def request(*args, **options)
-
1827
branch(default_options).request(*args, **options)
-
end
-
-
23
def accept(type)
-
12
with(headers: { "accept" => String(type) })
-
end
-
-
# delegates to the default session (see HTTPX::Session#wrap).
-
23
def wrap(&blk)
-
73
branch(default_options).wrap(&blk)
-
end
-
-
# returns a new instance loaded with the +pl+ plugin and +options+.
-
23
def plugin(pl, options = nil, &blk)
-
3376
klass = is_a?(S) ? self.class : Session
-
3376
klass = Class.new(klass)
-
3376
klass.instance_variable_set(:@default_options, klass.default_options.merge(default_options))
-
3376
klass.plugin(pl, options, &blk).new
-
end
-
-
# returns a new instance loaded with +options+.
-
23
def with(options, &blk)
-
1843
branch(default_options.merge(options), &blk)
-
end
-
-
23
private
-
-
# returns default instance of HTTPX::Options.
-
23
def default_options
-
7161
@options || Session.default_options
-
end
-
-
# returns a default instance of HTTPX::Session.
-
23
def branch(options, &blk)
-
3743
return self.class.new(options, &blk) if is_a?(S)
-
-
2170
Session.new(options, &blk)
-
end
-
-
23
def method_missing(meth, *args, **options, &blk)
-
462
case meth
-
when /\Awith_(.+)/
-
-
539
option = Regexp.last_match(1)
-
-
539
return super unless option
-
-
539
with(option.to_sym => args.first || options)
-
when /\Aon_(.+)/
-
7
callback = Regexp.last_match(1)
-
-
7
return super unless %w[
-
connection_opened connection_closed
-
request_error
-
request_started request_body_chunk request_completed
-
response_started response_body_chunk response_completed
-
].include?(callback)
-
-
7
warn "DEPRECATION WARNING: calling `.#{meth}` on plain HTTPX sessions is deprecated. " \
-
1
"Use HTTPX.plugin(:callbacks).#{meth} instead."
-
-
7
plugin(:callbacks).__send__(meth, *args, **options, &blk)
-
else
-
super
-
end
-
end
-
-
23
def respond_to_missing?(meth, *)
-
35
case meth
-
when /\Awith_(.+)/
-
30
option = Regexp.last_match(1)
-
-
30
default_options.respond_to?(option) || super
-
when /\Aon_(.+)/
-
12
callback = Regexp.last_match(1)
-
-
12
%w[
-
connection_opened connection_closed
-
request_error
-
request_started request_body_chunk request_completed
-
response_started response_body_chunk response_completed
-
].include?(callback) || super
-
else
-
super
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "resolv"
-
23
require "forwardable"
-
23
require "httpx/io"
-
23
require "httpx/buffer"
-
-
23
module HTTPX
-
# The Connection can be watched for IO events.
-
#
-
# It contains the +io+ object to read/write from, and knows what to do when it can.
-
#
-
# It defers connecting until absolutely necessary. Connection should be triggered from
-
# the IO selector (until then, any request will be queued).
-
#
-
# A connection boots up its parser after connection is established. All pending requests
-
# will be redirected there after connection.
-
#
-
# A connection can be prevented from closing by the parser, that is, if there are pending
-
# requests. This will signal that the connection was prematurely closed, due to a possible
-
# number of conditions:
-
#
-
# * Remote peer closed the connection ("Connection: close");
-
# * Remote peer doesn't support pipelining;
-
#
-
# A connection may also route requests for a different host for which the +io+ was connected
-
# to, provided that the IP is the same and the port and scheme as well. This will allow to
-
# share the same socket to send HTTP/2 requests to different hosts.
-
#
-
23
class Connection
-
23
extend Forwardable
-
23
include Loggable
-
23
include Callbacks
-
-
23
using URIExtensions
-
-
23
require "httpx/connection/http2"
-
23
require "httpx/connection/http1"
-
-
23
def_delegator :@io, :closed?
-
-
23
def_delegator :@write_buffer, :empty?
-
-
23
attr_reader :type, :io, :origin, :origins, :state, :pending, :options, :ssl_session
-
-
23
attr_writer :timers
-
-
23
attr_accessor :family
-
-
23
def initialize(uri, options)
-
5117
@origins = [uri.origin]
-
5117
@origin = Utils.to_uri(uri.origin)
-
5117
@options = Options.new(options)
-
5117
@type = initialize_type(uri, @options)
-
5117
@window_size = @options.window_size
-
5117
@read_buffer = Buffer.new(@options.buffer_size)
-
5117
@write_buffer = Buffer.new(@options.buffer_size)
-
5117
@pending = []
-
5117
on(:error, &method(:on_error))
-
5117
if @options.io
-
# if there's an already open IO, get its
-
# peer address, and force-initiate the parser
-
52
transition(:already_open)
-
52
@io = build_socket
-
52
parser
-
else
-
5065
transition(:idle)
-
end
-
-
5117
@inflight = 0
-
5117
@keep_alive_timeout = @options.timeout[:keep_alive_timeout]
-
-
5117
@intervals = []
-
-
5117
self.addresses = @options.addresses if @options.addresses
-
end
-
-
# this is a semi-private method, to be used by the resolver
-
# to initiate the io object.
-
23
def addresses=(addrs)
-
4949
if @io
-
173
@io.add_addresses(addrs)
-
else
-
4776
@io = build_socket(addrs)
-
end
-
end
-
-
23
def addresses
-
23543
@io && @io.addresses
-
end
-
-
23
def match?(uri, options)
-
12153
return false if !used? && (@state == :closing || @state == :closed)
-
-
476
(
-
12153
@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
-
2564
(@origins.size == 1 || @origin == uri.origin || (@io.is_a?(SSL) && @io.verify_hostname(uri.host)))
-
) && @options == options
-
end
-
-
23
def expired?
-
return false unless @io
-
-
@io.expired?
-
end
-
-
23
def mergeable?(connection)
-
9333
return false if @state == :closing || @state == :closed || !@io
-
-
6787
return false unless connection.addresses
-
-
285
(
-
6787
(open? && @origin == connection.origin) ||
-
6607
!(@io.addresses & (connection.addresses || [])).empty?
-
) && @options == connection.options
-
end
-
-
# coalescable connections need to be mergeable!
-
# but internally, #mergeable? is called before #coalescable?
-
23
def coalescable?(connection)
-
13
if @io.protocol == "h2" &&
-
@origin.scheme == "https" &&
-
connection.origin.scheme == "https" &&
-
@io.can_verify_peer?
-
6
@io.verify_hostname(connection.origin.host)
-
else
-
7
@origin == connection.origin
-
end
-
end
-
-
23
def create_idle(options = {})
-
6
self.class.new(@origin, @options.merge(options))
-
end
-
-
23
def merge(connection)
-
21
@origins |= connection.instance_variable_get(:@origins)
-
23
if connection.ssl_session
-
6
@ssl_session = connection.ssl_session
-
@io.session_new_cb do |sess|
-
@ssl_session = sess
-
6
end if @io
-
end
-
23
connection.purge_pending do |req|
-
6
send(req)
-
end
-
end
-
-
23
def purge_pending(&block)
-
23
pendings = []
-
23
if @parser
-
10
@inflight -= @parser.pending.size
-
12
pendings << @parser.pending
-
end
-
23
pendings << @pending
-
23
pendings.each do |pending|
-
35
pending.reject!(&block)
-
end
-
end
-
-
23
def connecting?
-
2022814
@state == :idle
-
end
-
-
23
def inflight?
-
4892
@parser && !@parser.empty? && !@write_buffer.empty?
-
end
-
-
23
def interests
-
# connecting
-
2014859
if connecting?
-
7701
connect
-
-
7701
return @io.interests if connecting?
-
end
-
-
# if the write buffer is full, we drain it
-
2008111
return :w unless @write_buffer.empty?
-
-
1977474
return @parser.interests if @parser
-
-
6
nil
-
end
-
-
23
def to_io
-
17291
@io.to_io
-
end
-
-
23
def call
-
12755
case @state
-
when :idle
-
6622
connect
-
6610
consume
-
when :closed
-
return
-
when :closing
-
consume
-
transition(:closed)
-
when :open
-
7504
consume
-
end
-
1515
nil
-
end
-
-
23
def close
-
4921
transition(:active) if @state == :inactive
-
-
4921
@parser.close if @parser
-
end
-
-
23
def terminate
-
4921
@connected_at = nil if @state == :closed
-
-
4921
close
-
end
-
-
# bypasses the state machine to force closing of connections still connecting.
-
# **only** used for Happy Eyeballs v2.
-
23
def force_reset
-
118
@state = :closing
-
118
transition(:closed)
-
end
-
-
23
def reset
-
7860
return if @state == :closing || @state == :closed
-
-
5359
transition(:closing)
-
-
5359
transition(:closed)
-
end
-
-
23
def send(request)
-
6292
if @parser && !@write_buffer.full?
-
302
if @response_received_at && @keep_alive_timeout &&
-
Utils.elapsed_time(@response_received_at) > @keep_alive_timeout
-
# when pushing a request into an existing connection, we have to check whether there
-
# is the possibility that the connection might have extended the keep alive timeout.
-
# for such cases, we want to ping for availability before deciding to shovel requests.
-
6
log(level: 3) { "keep alive timeout expired, pinging connection..." }
-
6
@pending << request
-
6
transition(:active) if @state == :inactive
-
6
parser.ping
-
5
return
-
end
-
-
296
send_request_to_parser(request)
-
else
-
5990
@pending << request
-
end
-
end
-
-
23
def timeout
-
11692674
return @timeout if @timeout
-
-
5930505
return @options.timeout[:connect_timeout] if @state == :idle
-
-
5930505
@options.timeout[:operation_timeout]
-
end
-
-
23
def idling
-
497
purge_after_closed
-
497
@write_buffer.clear
-
497
transition(:idle)
-
497
@parser = nil if @parser
-
end
-
-
23
def used?
-
18029
@connected_at
-
end
-
-
23
def deactivate
-
809
transition(:inactive)
-
end
-
-
23
def open?
-
11750
@state == :open || @state == :inactive
-
end
-
-
23
def handle_socket_timeout(interval)
-
340
@intervals.delete_if(&:elapsed?)
-
-
340
unless @intervals.empty?
-
# remove the intervals which will elapse
-
-
264
return
-
end
-
-
24
error = HTTPX::TimeoutError.new(interval, "timed out while waiting on select")
-
24
error.set_backtrace(caller)
-
24
on_error(error)
-
end
-
-
23
private
-
-
23
def connect
-
13517
transition(:open)
-
end
-
-
23
def consume
-
16363
return unless @io
-
-
16363
catch(:called) do
-
16363
epiped = false
-
16363
loop do
-
# connection may have
-
31115
return if @state == :idle
-
-
28961
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)
-
28949
if @pending.empty? && @inflight.zero? && @write_buffer.empty?
-
2053
log(level: 3) { "NO MORE REQUESTS..." }
-
2041
return
-
end
-
-
26908
@timeout = @current_timeout
-
-
26908
read_drained = false
-
26908
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.
-
#
-
2057
loop do
-
34358
siz = @io.read(@window_size, @read_buffer)
-
34449
log(level: 3, color: :cyan) { "IO READ: #{siz} bytes..." }
-
34358
unless siz
-
10
ex = EOFError.new("descriptor closed")
-
10
ex.set_backtrace(caller)
-
10
on_error(ex)
-
10
return
-
end
-
-
# socket has been drained. mark and exit the read loop.
-
34348
if siz.zero?
-
6416
read_drained = @read_buffer.empty?
-
6416
epiped = false
-
6416
break
-
end
-
-
27932
parser << @read_buffer.to_s
-
-
# continue reading if possible.
-
24978
break if interests == :w && !epiped
-
-
# exit the read loop if connection is preparing to be closed
-
19435
break if @state == :closing || @state == :closed
-
-
# exit #consume altogether if all outstanding requests have been dealt with
-
19429
return if @pending.empty? && @inflight.zero?
-
26908
end unless ((ints = interests).nil? || ints == :w || @state == :closing) && !epiped
-
-
#
-
# tight write loop.
-
#
-
# flush as many bytes as the sockets allow.
-
#
-
2170
loop do
-
# buffer has been drainned, mark and exit the write loop.
-
17882
if @write_buffer.empty?
-
# we only mark as drained on the first loop
-
2497
write_drained = write_drained.nil? && @inflight.positive?
-
-
2497
break
-
end
-
-
begin
-
15385
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.
-
14
log(level: 2) { "pipe broken, could not flush buffer..." }
-
14
epiped = true
-
14
read_drained = false
-
14
break
-
end
-
15431
log(level: 3, color: :cyan) { "IO WRITE: #{siz} bytes..." }
-
15365
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.
-
15365
if siz.zero?
-
22
write_drained = !@write_buffer.empty?
-
22
break
-
end
-
-
# exit write loop if marked to consume from peer, or is closing.
-
15343
break if interests == :r || @state == :closing || @state == :closed
-
-
2462
write_drained = false
-
21823
end unless (ints = interests) == :r
-
-
21817
send_pending if @state == :open
-
-
# return if socket is drained
-
21817
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;
-
7093
log(level: 3) { "(#{ints}): WAITING FOR EVENTS..." }
-
7065
return
-
end
-
end
-
end
-
-
23
def send_pending
-
61845
while !@write_buffer.full? && (request = @pending.shift)
-
16210
send_request_to_parser(request)
-
end
-
end
-
-
23
def parser
-
79341
@parser ||= build_parser
-
end
-
-
23
def send_request_to_parser(request)
-
15681
@inflight += 1
-
16506
request.peer_address = @io.ip
-
16506
parser.send(request)
-
-
16506
set_request_timeouts(request)
-
-
16506
return unless @state == :inactive
-
-
53
transition(:active)
-
end
-
-
23
def build_parser(protocol = @io.protocol)
-
5056
parser = self.class.parser_type(protocol).new(@write_buffer, @options)
-
5056
set_parser_callbacks(parser)
-
5056
parser
-
end
-
-
23
def set_parser_callbacks(parser)
-
5152
parser.on(:response) do |request, response|
-
5549
AltSvc.emit(request, response) do |alt_origin, origin, alt_params|
-
6
emit(:altsvc, alt_origin, origin, alt_params)
-
end
-
5549
@response_received_at = Utils.now
-
4798
@inflight -= 1
-
5549
request.emit(:response, response)
-
end
-
5152
parser.on(:altsvc) do |alt_origin, origin, alt_params|
-
emit(:altsvc, alt_origin, origin, alt_params)
-
end
-
-
5152
parser.on(:pong, &method(:send_pending))
-
-
5152
parser.on(:promise) do |request, stream|
-
18
request.emit(:promise, parser, stream)
-
end
-
5152
parser.on(:exhausted) do
-
6
@pending.concat(parser.pending)
-
6
emit(:exhausted)
-
end
-
5152
parser.on(:origin) do |origin|
-
@origins |= [origin]
-
end
-
5152
parser.on(:close) do |force|
-
4562
if force
-
4562
reset
-
4556
emit(:terminate)
-
end
-
end
-
5152
parser.on(:close_handshake) do
-
6
consume
-
end
-
5152
parser.on(:reset) do
-
2671
@pending.concat(parser.pending) unless parser.empty?
-
2671
reset
-
2665
idling unless @pending.empty?
-
end
-
5152
parser.on(:current_timeout) do
-
2189
@current_timeout = @timeout = parser.timeout
-
end
-
5152
parser.on(:timeout) do |tout|
-
2074
@timeout = tout
-
end
-
5152
parser.on(:error) do |request, ex|
-
285
case ex
-
when MisdirectedRequestError
-
6
emit(:misdirected, request)
-
else
-
334
response = ErrorResponse.new(request, ex, @options)
-
334
request.response = response
-
334
request.emit(:response, response)
-
end
-
end
-
end
-
-
23
def transition(nextstate)
-
32394
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
-
60
error = ConnectionError.new(e.message)
-
60
error.set_backtrace(e.backtrace)
-
60
connecting? && callbacks_for?(:connect_error) ? emit(:connect_error, error) : handle_error(error)
-
60
@state = :closed
-
60
emit(:close)
-
rescue TLSError, HTTP2Next::Error::ProtocolError, HTTP2Next::Error::HandshakeError => e
-
# connect errors, exit gracefully
-
19
handle_error(e)
-
19
connecting? && callbacks_for?(:connect_error) ? emit(:connect_error, e) : handle_error(e)
-
19
@state = :closed
-
19
emit(:close)
-
end
-
-
23
def handle_transition(nextstate)
-
27507
case nextstate
-
when :idle
-
5574
@timeout = @current_timeout = @options.timeout[:connect_timeout]
-
-
5574
@connected_at = nil
-
when :open
-
13761
return if @state == :closed
-
-
13761
@io.connect
-
13683
emit(:tcp_open, self) if @io.state == :connected
-
-
13683
return unless @io.connected?
-
-
5070
@connected_at = Utils.now
-
-
5070
send_pending
-
-
5070
@timeout = @current_timeout = parser.timeout
-
5070
emit(:open)
-
when :inactive
-
809
return unless @state == :open
-
when :closing
-
5409
return unless @state == :idle || @state == :open
-
-
5384
unless @write_buffer.empty?
-
# preset state before handshake, as error callbacks
-
# may take it back here.
-
1971
@state = nextstate
-
# handshakes, try sending
-
1971
consume
-
1970
@write_buffer.clear
-
1970
return
-
end
-
when :closed
-
5483
return unless @state == :closing
-
5463
return unless @write_buffer.empty?
-
-
5445
purge_after_closed
-
5445
emit(:close) if @pending.empty?
-
when :already_open
-
52
nextstate = :open
-
# the first check for given io readiness must still use a timeout.
-
# connect is the reasonable choice in such a case.
-
52
@timeout = @options.timeout[:connect_timeout]
-
52
send_pending
-
when :active
-
460
return unless @state == :inactive
-
-
460
nextstate = :open
-
460
emit(:activate)
-
end
-
20935
@state = nextstate
-
end
-
-
23
def purge_after_closed
-
5948
@io.close if @io
-
5948
@read_buffer.clear
-
5948
@timeout = nil
-
end
-
-
23
def initialize_type(uri, options)
-
4834
options.transport || begin
-
4109
case uri.scheme
-
when "http"
-
2633
"tcp"
-
when "https"
-
2177
"ssl"
-
else
-
raise UnsupportedSchemeError, "#{uri}: #{uri.scheme}: unsupported URI scheme"
-
end
-
end
-
end
-
-
23
def build_socket(addrs = nil)
-
4096
case @type
-
when "tcp"
-
2709
TCP.new(@origin, addrs, @options)
-
when "ssl"
-
2095
SSL.new(@origin, addrs, @options) do |sock|
-
2078
sock.ssl_session = @ssl_session
-
2078
sock.session_new_cb do |sess|
-
3999
@ssl_session = sess
-
-
3999
sock.ssl_session = sess
-
end
-
end
-
when "unix"
-
24
UNIX.new(@origin, addrs, @options)
-
else
-
raise Error, "unsupported transport (#{@type})"
-
end
-
end
-
-
23
def on_error(error)
-
615
if error.instance_of?(TimeoutError)
-
-
# inactive connections do not contribute to the select loop, therefore
-
# they should not fail due to such errors.
-
24
return if @state == :inactive
-
-
24
if @timeout
-
20
@timeout -= error.timeout
-
24
return unless @timeout <= 0
-
end
-
-
24
error = error.to_connection_error if connecting?
-
end
-
615
handle_error(error)
-
615
reset
-
end
-
-
23
def handle_error(error)
-
713
parser.handle_error(error) if @parser && parser.respond_to?(:handle_error)
-
1666
while (request = @pending.shift)
-
333
response = ErrorResponse.new(request, error, request.options)
-
333
request.response = response
-
333
request.emit(:response, response)
-
end
-
end
-
-
23
def set_request_timeouts(request)
-
16506
write_timeout = request.write_timeout
-
16506
read_timeout = request.read_timeout
-
16506
request_timeout = request.request_timeout
-
-
16506
unless write_timeout.nil? || write_timeout.infinite?
-
16506
set_request_timeout(request, write_timeout, :headers, %i[done response]) do
-
18
write_timeout_callback(request, write_timeout)
-
end
-
end
-
-
16506
unless read_timeout.nil? || read_timeout.infinite?
-
16293
set_request_timeout(request, read_timeout, :done, :response) do
-
18
read_timeout_callback(request, read_timeout)
-
end
-
end
-
-
16506
return if request_timeout.nil? || request_timeout.infinite?
-
-
348
set_request_timeout(request, request_timeout, :headers, :response) do
-
260
read_timeout_callback(request, request_timeout, RequestTimeoutError)
-
end
-
end
-
-
23
def write_timeout_callback(request, write_timeout)
-
18
return if request.state == :done
-
-
18
@write_buffer.clear
-
18
error = WriteTimeoutError.new(request, nil, write_timeout)
-
18
on_error(error)
-
end
-
-
23
def read_timeout_callback(request, read_timeout, error_type = ReadTimeoutError)
-
278
response = request.response
-
-
278
return if response && response.finished?
-
-
278
@write_buffer.clear
-
278
error = error_type.new(request, request.response, read_timeout)
-
278
on_error(error)
-
end
-
-
23
def set_request_timeout(request, timeout, start_event, finish_events, &callback)
-
33207
request.once(start_event) do
-
32685
interval = @timers.after(timeout, callback)
-
-
32685
Array(finish_events).each do |event|
-
# clean up request timeouts if the connection errors out
-
49002
request.once(event) do
-
48888
if @intervals.include?(interval)
-
48589
interval.delete(callback)
-
48589
@intervals.delete(interval) if interval.no_callbacks?
-
end
-
end
-
end
-
-
32685
@intervals << interval
-
end
-
end
-
-
23
class << self
-
23
def parser_type(protocol)
-
4403
case protocol
-
2194
when "h2" then HTTP2
-
2984
when "http/1.1" then HTTP1
-
else
-
raise Error, "unsupported protocol (##{protocol})"
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "httpx/parser/http1"
-
-
23
module HTTPX
-
23
class Connection::HTTP1
-
23
include Callbacks
-
23
include Loggable
-
-
23
MAX_REQUESTS = 200
-
23
CRLF = "\r\n"
-
-
23
attr_reader :pending, :requests
-
-
23
attr_accessor :max_concurrent_requests
-
-
23
def initialize(buffer, options)
-
2984
@options = Options.new(options)
-
2984
@max_concurrent_requests = @options.max_concurrent_requests || MAX_REQUESTS
-
2984
@max_requests = @options.max_requests
-
2984
@parser = Parser::HTTP1.new(self)
-
2984
@buffer = buffer
-
2984
@version = [1, 1]
-
2984
@pending = []
-
2984
@requests = []
-
2984
@handshake_completed = false
-
end
-
-
23
def timeout
-
2891
@options.timeout[:operation_timeout]
-
end
-
-
23
def interests
-
# this means we're processing incoming response already
-
453232
return :r if @request
-
-
450635
return if @requests.empty?
-
-
18733
request = @requests.first
-
-
18733
return unless request
-
-
18733
return :w if request.interests == :w || !@buffer.empty?
-
-
15848
:r
-
end
-
-
23
def reset
-
5210
@max_requests = @options.max_requests || MAX_REQUESTS
-
5210
@parser.reset!
-
5210
@handshake_completed = false
-
5210
@pending.concat(@requests) unless @requests.empty?
-
end
-
-
23
def close
-
2503
reset
-
2503
emit(:close, true)
-
end
-
-
23
def exhausted?
-
539
!@max_requests.positive?
-
end
-
-
23
def empty?
-
# this means that for every request there's an available
-
# partial response, so there are no in-flight requests waiting.
-
5148
@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.
-
276
!@requests.first.response.nil? &&
-
97
(@requests.size == 1 || !@requests.last.response.nil?)
-
)
-
end
-
-
23
def <<(data)
-
4903
@parser << data
-
end
-
-
23
def send(request)
-
14031
unless @max_requests.positive?
-
@pending << request
-
return
-
end
-
-
14031
return if @requests.include?(request)
-
-
14031
@requests << request
-
14031
@pipelining = true if @requests.size > 1
-
end
-
-
23
def consume
-
11459
requests_limit = [@max_requests, @requests.size].min
-
11459
concurrent_requests_limit = [@max_concurrent_requests, requests_limit].min
-
11459
@requests.each_with_index do |request, idx|
-
13572
break if idx >= concurrent_requests_limit
-
11403
next if request.state == :done
-
-
4691
handle(request)
-
end
-
end
-
-
# HTTP Parser callbacks
-
#
-
# must be public methods, or else they won't be reachable
-
-
23
def on_start
-
3374
log(level: 2) { "parsing begins" }
-
end
-
-
23
def on_headers(h)
-
3356
@request = @requests.first
-
-
3356
return if @request.response
-
-
3374
log(level: 2) { "headers received" }
-
3356
headers = @request.options.headers_class.new(h)
-
3356
response = @request.options.response_class.new(@request,
-
@parser.status_code,
-
@parser.http_version.join("."),
-
headers)
-
3374
log(color: :yellow) { "-> HEADLINE: #{response.status} HTTP/#{@parser.http_version.join(".")}" }
-
3518
log(color: :yellow) { response.headers.each.map { |f, v| "-> HEADER: #{f}: #{v}" }.join("\n") }
-
-
3356
@request.response = response
-
3350
on_complete if response.finished?
-
end
-
-
23
def on_trailers(h)
-
6
return unless @request
-
-
6
response = @request.response
-
6
log(level: 2) { "trailer headers received" }
-
-
6
log(color: :yellow) { h.each.map { |f, v| "-> HEADER: #{f}: #{v.join(", ")}" }.join("\n") }
-
6
response.merge_headers(h)
-
end
-
-
23
def on_data(chunk)
-
3789
request = @request
-
-
3789
return unless request
-
-
3807
log(color: :green) { "-> DATA: #{chunk.bytesize} bytes..." }
-
3807
log(level: 2, color: :green) { "-> #{chunk.inspect}" }
-
3789
response = request.response
-
-
3789
response << chunk
-
rescue StandardError => e
-
11
error_response = ErrorResponse.new(request, e, request.options)
-
11
request.response = error_response
-
11
dispatch
-
end
-
-
23
def on_complete
-
3333
request = @request
-
-
3333
return unless request
-
-
3351
log(level: 2) { "parsing complete" }
-
3333
dispatch
-
end
-
-
23
def dispatch
-
3344
request = @request
-
-
3344
if request.expects?
-
54
@parser.reset!
-
45
return handle(request)
-
end
-
-
3290
@request = nil
-
3290
@requests.shift
-
3290
response = request.response
-
3290
response.finish! unless response.is_a?(ErrorResponse)
-
3290
emit(:response, request, response)
-
-
3246
if @parser.upgrade?
-
24
response << @parser.upgrade_data
-
24
throw(:called)
-
end
-
-
3222
@parser.reset!
-
2810
@max_requests -= 1
-
3222
if response.is_a?(ErrorResponse)
-
11
disable
-
else
-
3211
manage_connection(request, response)
-
end
-
-
539
if exhausted?
-
@pending.concat(@requests)
-
@requests.clear
-
-
emit(:exhausted)
-
else
-
539
send(@pending.shift) unless @pending.empty?
-
end
-
end
-
-
23
def handle_error(ex)
-
158
if (ex.is_a?(EOFError) || ex.is_a?(TimeoutError)) && @request && @request.response &&
-
!@request.response.headers.key?("content-length") &&
-
!@request.response.headers.key?("transfer-encoding")
-
# if the response does not contain a content-length header, the server closing the
-
# connnection is the indicator of response consumed.
-
# https://greenbytes.de/tech/webdav/rfc2616.html#rfc.section.4.4
-
12
catch(:called) { on_complete }
-
5
return
-
end
-
-
152
if @pipelining
-
catch(:called) { disable }
-
else
-
152
@requests.each do |request|
-
146
emit(:error, request, ex)
-
end
-
152
@pending.each do |request|
-
emit(:error, request, ex)
-
end
-
end
-
end
-
-
23
def ping
-
reset
-
emit(:reset)
-
emit(:exhausted)
-
end
-
-
23
private
-
-
23
def manage_connection(request, response)
-
3211
connection = response.headers["connection"]
-
2800
case connection
-
when /keep-alive/i
-
539
if @handshake_completed
-
if @max_requests.zero?
-
@pending.concat(@requests)
-
@requests.clear
-
emit(:exhausted)
-
end
-
return
-
end
-
-
539
keep_alive = response.headers["keep-alive"]
-
539
return unless keep_alive
-
-
112
parameters = Hash[keep_alive.split(/ *, */).map do |pair|
-
112
pair.split(/ *= */)
-
end]
-
112
@max_requests = parameters["max"].to_i - 1 if parameters.key?("max")
-
-
112
if parameters.key?("timeout")
-
keep_alive_timeout = parameters["timeout"].to_i
-
emit(:timeout, keep_alive_timeout)
-
end
-
112
@handshake_completed = true
-
when /close/i
-
2672
disable
-
when nil
-
# In HTTP/1.1, it's keep alive by default
-
return if response.version == "1.1" && request.headers["connection"] != "close"
-
-
disable
-
end
-
end
-
-
23
def disable
-
2683
disable_pipelining
-
2683
reset
-
2683
emit(:reset)
-
2677
throw(:called)
-
end
-
-
23
def disable_pipelining
-
2683
return if @requests.empty?
-
# do not disable pipelining if already set to 1 request at a time
-
161
return if @max_concurrent_requests == 1
-
-
17
@requests.each do |r|
-
17
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.
-
17
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.
-
17
@max_concurrent_requests = 1
-
17
@pipelining = false
-
end
-
-
23
def set_protocol_headers(request)
-
3471
if !request.headers.key?("content-length") &&
-
request.body.bytesize == Float::INFINITY
-
24
request.body.chunk!
-
end
-
-
3471
extra_headers = {}
-
-
3471
unless request.headers.key?("connection")
-
3453
connection_value = if request.persistent?
-
# when in a persistent connection, the request can't be at
-
# the edge of a renegotiation
-
803
if @requests.index(request) + 1 < @max_requests
-
693
"keep-alive"
-
else
-
110
"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)
-
2650
requests_limit = [@max_requests, @requests.size].min
-
2650
if request == @requests[requests_limit - 1]
-
2615
"close"
-
else
-
35
"keep-alive"
-
end
-
end
-
-
3005
extra_headers["connection"] = connection_value
-
end
-
3471
extra_headers["host"] = request.authority unless request.headers.key?("host")
-
3471
extra_headers
-
end
-
-
23
def handle(request)
-
4745
catch(:buffer_full) do
-
4745
request.transition(:headers)
-
4739
join_headers(request) if request.state == :headers
-
4739
request.transition(:body)
-
4739
join_body(request) if request.state == :body
-
3611
request.transition(:trailers)
-
# HTTP/1.1 trailers should only work for chunked encoding
-
3611
join_trailers(request) if request.body.chunked? && request.state == :trailers
-
3611
request.transition(:done)
-
end
-
end
-
-
23
def join_headline(request)
-
2969
"#{request.verb} #{request.path} HTTP/#{@version.join(".")}"
-
end
-
-
23
def join_headers(request)
-
3471
headline = join_headline(request)
-
3471
@buffer << headline << CRLF
-
3489
log(color: :yellow) { "<- HEADLINE: #{headline.chomp.inspect}" }
-
3471
extra_headers = set_protocol_headers(request)
-
3471
join_headers2(request.headers.each(extra_headers))
-
3489
log { "<- " }
-
3471
@buffer << CRLF
-
end
-
-
23
def join_body(request)
-
4581
return if request.body.empty?
-
-
5596
while (chunk = request.drain_body)
-
2679
log(color: :green) { "<- DATA: #{chunk.bytesize} bytes..." }
-
2679
log(level: 2, color: :green) { "<- #{chunk.inspect}" }
-
2679
@buffer << chunk
-
2679
throw(:buffer_full, request) if @buffer.full?
-
end
-
-
1077
return unless (error = request.drain_error)
-
-
raise error
-
end
-
-
23
def join_trailers(request)
-
72
return unless request.trailers? && request.callbacks_for?(:trailers)
-
-
24
join_headers2(request.trailers)
-
24
log { "<- " }
-
24
@buffer << CRLF
-
end
-
-
23
def join_headers2(headers)
-
3495
headers.each do |field, value|
-
20928
buffer = "#{capitalized(field)}: #{value}#{CRLF}"
-
21018
log(color: :yellow) { "<- HEADER: #{buffer.chomp}" }
-
20928
@buffer << buffer
-
end
-
end
-
-
23
UPCASED = {
-
"www-authenticate" => "WWW-Authenticate",
-
"http2-settings" => "HTTP2-Settings",
-
}.freeze
-
-
23
def capitalized(field)
-
20928
UPCASED[field] || field.split("-").map(&:capitalize).join("-")
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "securerandom"
-
23
require "http/2/next"
-
-
23
module HTTPX
-
23
class Connection::HTTP2
-
23
include Callbacks
-
23
include Loggable
-
-
23
MAX_CONCURRENT_REQUESTS = HTTP2Next::DEFAULT_MAX_CONCURRENT_STREAMS
-
-
23
class Error < Error
-
23
def initialize(id, code)
-
28
super("stream #{id} closed with error: #{code}")
-
end
-
end
-
-
23
class GoawayError < Error
-
23
def initialize
-
12
super(0, :no_error)
-
end
-
end
-
-
23
attr_reader :streams, :pending
-
-
23
def initialize(buffer, options)
-
2212
@options = Options.new(options)
-
2212
@settings = @options.http2_settings
-
2212
@pending = []
-
2212
@streams = {}
-
2212
@drains = {}
-
2212
@pings = []
-
2212
@buffer = buffer
-
2212
@handshake_completed = false
-
2212
@wait_for_handshake = @settings.key?(:wait_for_handshake) ? @settings.delete(:wait_for_handshake) : true
-
2212
@max_concurrent_requests = @options.max_concurrent_requests || MAX_CONCURRENT_REQUESTS
-
2212
@max_requests = @options.max_requests
-
2212
init_connection
-
end
-
-
23
def timeout
-
4368
return @options.timeout[:operation_timeout] if @handshake_completed
-
-
2179
@options.timeout[:settings_timeout]
-
end
-
-
23
def interests
-
# waiting for WINDOW_UPDATE frames
-
1524182
return :r if @buffer.full?
-
-
1524182
if @connection.state == :closed
-
2084
return unless @handshake_completed
-
-
1750
return :w
-
end
-
-
1522098
unless @connection.state == :connected && @handshake_completed
-
7705
return @buffer.empty? ? :r : :rw
-
end
-
-
1513072
return :w if !@pending.empty? && can_buffer_more_requests?
-
-
1513072
return :w unless @drains.empty?
-
-
1512424
if @buffer.empty?
-
1512424
return if @streams.empty? && @pings.empty?
-
-
25125
return :r
-
end
-
-
:rw
-
end
-
-
23
def close
-
2085
unless @connection.state == :closed
-
2074
@connection.goaway
-
2074
emit(:timeout, @options.timeout[:close_handshake_timeout])
-
end
-
2085
emit(:close, true)
-
end
-
-
23
def empty?
-
2050
@connection.state == :closed || @streams.empty?
-
end
-
-
23
def exhausted?
-
2203
!@max_requests.positive?
-
end
-
-
23
def <<(data)
-
22801
@connection << data
-
end
-
-
23
def can_buffer_more_requests?
-
5218
(@handshake_completed || !@wait_for_handshake) &&
-
@streams.size < @max_concurrent_requests &&
-
@streams.size < @max_requests
-
end
-
-
23
def send(request)
-
4854
unless can_buffer_more_requests?
-
2360
@pending << request
-
2360
return
-
end
-
2494
unless (stream = @streams[request])
-
2494
stream = @connection.new_stream
-
2494
handle_stream(stream, request)
-
2128
@streams[request] = stream
-
2128
@max_requests -= 1
-
end
-
2494
handle(request, stream)
-
2482
true
-
rescue HTTP2Next::Error::StreamLimitExceeded
-
@pending.unshift(request)
-
end
-
-
23
def consume
-
16917
@streams.each do |request, stream|
-
6403
next if request.state == :done
-
-
739
handle(request, stream)
-
end
-
end
-
-
23
def handle_error(ex)
-
207
if ex.instance_of?(TimeoutError) && !@handshake_completed && @connection.state != :closed
-
6
@connection.goaway(:settings_timeout, "closing due to settings timeout")
-
6
emit(:close_handshake)
-
6
settings_ex = SettingsTimeoutError.new(ex.timeout, ex.message)
-
6
settings_ex.set_backtrace(ex.backtrace)
-
6
ex = settings_ex
-
end
-
207
@streams.each_key do |request|
-
161
emit(:error, request, ex)
-
end
-
207
@pending.each do |request|
-
27
emit(:error, request, ex)
-
end
-
end
-
-
23
def ping
-
6
ping = SecureRandom.gen_random(8)
-
6
@connection.ping(ping)
-
ensure
-
6
@pings << ping
-
end
-
-
23
private
-
-
23
def send_pending
-
6258
while (request = @pending.shift)
-
# TODO: this request should go back to top of stack
-
2269
break unless send(request)
-
end
-
end
-
-
23
def handle(request, stream)
-
3275
catch(:buffer_full) do
-
3275
request.transition(:headers)
-
3269
join_headers(stream, request) if request.state == :headers
-
3269
request.transition(:body)
-
3269
join_body(stream, request) if request.state == :body
-
2615
request.transition(:trailers)
-
2615
join_trailers(stream, request) if request.state == :trailers && !request.body.empty?
-
2615
request.transition(:done)
-
end
-
end
-
-
23
def init_connection
-
2212
@connection = HTTP2Next::Client.new(@settings)
-
2212
@connection.on(:frame, &method(:on_frame))
-
2212
@connection.on(:frame_sent, &method(:on_frame_sent))
-
2212
@connection.on(:frame_received, &method(:on_frame_received))
-
2212
@connection.on(:origin, &method(:on_origin))
-
2212
@connection.on(:promise, &method(:on_promise))
-
2212
@connection.on(:altsvc) { |frame| on_altsvc(frame[:origin], frame) }
-
2212
@connection.on(:settings_ack, &method(:on_settings))
-
2212
@connection.on(:ack, &method(:on_pong))
-
2212
@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.
-
#
-
2212
@connection.send_connection_preface
-
end
-
-
23
alias_method :reset, :init_connection
-
23
public :reset
-
-
23
def handle_stream(stream, request)
-
2506
request.on(:refuse, &method(:on_stream_refuse).curry(3)[stream, request])
-
2506
stream.on(:close, &method(:on_stream_close).curry(3)[stream, request])
-
2506
stream.on(:half_close) do
-
2488
log(level: 2) { "#{stream.id}: waiting for response..." }
-
end
-
2506
stream.on(:altsvc, &method(:on_altsvc).curry(2)[request.origin])
-
2506
stream.on(:headers, &method(:on_stream_headers).curry(3)[stream, request])
-
2506
stream.on(:data, &method(:on_stream_data).curry(3)[stream, request])
-
end
-
-
23
def set_protocol_headers(request)
-
365
{
-
2123
":scheme" => request.scheme,
-
":method" => request.verb,
-
":path" => request.path,
-
":authority" => request.authority,
-
}
-
end
-
-
23
def join_headers(stream, request)
-
2488
extra_headers = set_protocol_headers(request)
-
-
2488
if request.headers.key?("host")
-
6
log { "forbidden \"host\" header found (#{request.headers["host"]}), will use it as authority..." }
-
5
extra_headers[":authority"] = request.headers["host"]
-
end
-
-
2488
log(level: 1, color: :yellow) do
-
92
request.headers.merge(extra_headers).each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{v}" }.join("\n")
-
end
-
2488
stream.headers(request.headers.each(extra_headers), end_stream: request.body.empty?)
-
end
-
-
23
def join_trailers(stream, request)
-
1024
unless request.trailers?
-
1018
stream.data("", end_stream: true) if request.callbacks_for?(:trailers)
-
877
return
-
end
-
-
6
log(level: 1, color: :yellow) do
-
11
request.trailers.each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{v}" }.join("\n")
-
end
-
6
stream.headers(request.trailers.each, end_stream: true)
-
end
-
-
23
def join_body(stream, request)
-
3142
return if request.body.empty?
-
-
1678
chunk = @drains.delete(request) || request.drain_body
-
1850
while chunk
-
1848
next_chunk = request.drain_body
-
1863
log(level: 1, color: :green) { "#{stream.id}: -> DATA: #{chunk.bytesize} bytes..." }
-
1863
log(level: 2, color: :green) { "#{stream.id}: -> #{chunk.inspect}" }
-
1848
stream.data(chunk, end_stream: !(next_chunk || request.trailers? || request.callbacks_for?(:trailers)))
-
1848
if next_chunk && (@buffer.full? || request.body.unbounded_body?)
-
550
@drains[request] = next_chunk
-
654
throw(:buffer_full)
-
end
-
1194
chunk = next_chunk
-
end
-
-
1024
return unless (error = request.drain_error)
-
-
10
on_stream_refuse(stream, request, error)
-
end
-
-
######
-
# HTTP/2 Callbacks
-
######
-
-
23
def on_stream_headers(stream, request, h)
-
2476
response = request.response
-
-
2476
if response.is_a?(Response) && response.version == "2.0"
-
95
on_stream_trailers(stream, response, h)
-
95
return
-
end
-
-
2381
log(color: :yellow) do
-
92
h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{v}" }.join("\n")
-
end
-
2381
_, status = h.shift
-
2381
headers = request.options.headers_class.new(h)
-
2381
response = request.options.response_class.new(request, status, "2.0", headers)
-
2381
request.response = response
-
2027
@streams[request] = stream
-
-
2375
handle(request, stream) if request.expects?
-
end
-
-
23
def on_stream_trailers(stream, response, h)
-
95
log(color: :yellow) do
-
h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{v}" }.join("\n")
-
end
-
95
response.merge_headers(h)
-
end
-
-
23
def on_stream_data(stream, request, data)
-
4219
log(level: 1, color: :green) { "#{stream.id}: <- DATA: #{data.bytesize} bytes..." }
-
4219
log(level: 2, color: :green) { "#{stream.id}: <- #{data.inspect}" }
-
4204
request.response << data
-
end
-
-
23
def on_stream_refuse(stream, request, error)
-
10
on_stream_close(stream, request, error)
-
10
stream.close
-
end
-
-
23
def on_stream_close(stream, request, error)
-
2325
return if error == :stream_closed && !@streams.key?(request)
-
-
2325
log(level: 2) { "#{stream.id}: closing stream" }
-
2315
@drains.delete(request)
-
2315
@streams.delete(request)
-
-
2315
if error
-
10
ex = Error.new(stream.id, error)
-
10
ex.set_backtrace(caller)
-
10
response = ErrorResponse.new(request, ex, request.options)
-
10
request.response = response
-
10
emit(:response, request, response)
-
else
-
2305
response = request.response
-
2305
if response && response.is_a?(Response) && response.status == 421
-
6
ex = MisdirectedRequestError.new(response)
-
6
ex.set_backtrace(caller)
-
6
emit(:error, request, ex)
-
else
-
2299
emit(:response, request, response)
-
end
-
end
-
2309
send(@pending.shift) unless @pending.empty?
-
2309
return unless @streams.empty? && exhausted?
-
-
6
close
-
6
emit(:exhausted) unless @pending.empty?
-
end
-
-
23
def on_frame(bytes)
-
13921
@buffer << bytes
-
end
-
-
23
def on_settings(*)
-
2189
@handshake_completed = true
-
2189
emit(:current_timeout)
-
2189
@max_concurrent_requests = [@max_concurrent_requests, @connection.remote_settings[:settings_max_concurrent_streams]].min
-
2189
send_pending
-
end
-
-
23
def on_close(_last_frame, error, _payload)
-
18
is_connection_closed = @connection.state == :closed
-
18
if error
-
18
@buffer.clear if is_connection_closed
-
18
if error == :no_error
-
12
ex = GoawayError.new
-
12
@pending.unshift(*@streams.keys)
-
12
@drains.clear
-
12
@streams.clear
-
else
-
6
ex = Error.new(0, error)
-
end
-
18
ex.set_backtrace(caller)
-
18
handle_error(ex)
-
end
-
18
return unless is_connection_closed && @streams.empty?
-
-
18
emit(:close, is_connection_closed)
-
end
-
-
23
def on_frame_sent(frame)
-
11763
log(level: 2) { "#{frame[:stream]}: frame was sent!" }
-
11703
log(level: 2, color: :blue) do
-
72
payload = frame
-
72
payload = payload.merge(payload: frame[:payload].bytesize) if frame[:type] == :data
-
60
"#{frame[:stream]}: #{payload}"
-
end
-
end
-
-
23
def on_frame_received(frame)
-
12124
log(level: 2) { "#{frame[:stream]}: frame was received!" }
-
12079
log(level: 2, color: :magenta) do
-
54
payload = frame
-
54
payload = payload.merge(payload: frame[:payload].bytesize) if frame[:type] == :data
-
45
"#{frame[:stream]}: #{payload}"
-
end
-
end
-
-
23
def on_altsvc(origin, frame)
-
log(level: 2) { "#{frame[:stream]}: altsvc frame was received" }
-
log(level: 2) { "#{frame[:stream]}: #{frame.inspect}" }
-
alt_origin = URI.parse("#{frame[:proto]}://#{frame[:host]}:#{frame[:port]}")
-
params = { "ma" => frame[:max_age] }
-
emit(:altsvc, origin, alt_origin, origin, params)
-
end
-
-
23
def on_promise(stream)
-
18
emit(:promise, @streams.key(stream.parent), stream)
-
end
-
-
23
def on_origin(origin)
-
emit(:origin, origin)
-
end
-
-
23
def on_pong(ping)
-
6
if @pings.delete(ping.to_s)
-
6
emit(:pong)
-
else
-
close(:protocol_error, "ping payload did not match")
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
#
-
# domain_name.rb - Domain Name manipulation library for Ruby
-
#
-
# Copyright (C) 2011-2017 Akinori MUSHA, All rights reserved.
-
#
-
# Redistribution and use in source and binary forms, with or without
-
# modification, are permitted provided that the following conditions
-
# are met:
-
# 1. Redistributions of source code must retain the above copyright
-
# notice, this list of conditions and the following disclaimer.
-
# 2. Redistributions in binary form must reproduce the above copyright
-
# notice, this list of conditions and the following disclaimer in the
-
# documentation and/or other materials provided with the distribution.
-
#
-
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
-
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
-
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-
# SUCH DAMAGE.
-
-
23
require "ipaddr"
-
-
23
module HTTPX
-
# Represents a domain name ready for extracting its registered domain
-
# and TLD.
-
23
class DomainName
-
23
include Comparable
-
-
# The full host name normalized, ASCII-ized and downcased using the
-
# Unicode NFC rules and the Punycode algorithm. If initialized with
-
# an IP address, the string representation of the IP address
-
# suitable for opening a connection to.
-
23
attr_reader :hostname
-
-
# The Unicode representation of the #hostname property.
-
#
-
# :attr_reader: hostname_idn
-
-
# The least "universally original" domain part of this domain name.
-
# For example, "example.co.uk" for "www.sub.example.co.uk". This
-
# may be nil if the hostname does not have one, like when it is an
-
# IP address, an effective TLD or higher itself, or of a
-
# non-canonical domain.
-
23
attr_reader :domain
-
-
23
class << self
-
23
def new(domain)
-
642
return domain if domain.is_a?(self)
-
-
594
super(domain)
-
end
-
-
# Normalizes a _domain_ using the Punycode algorithm as necessary.
-
# The result will be a downcased, ASCII-only string.
-
23
def normalize(domain)
-
570
unless domain.ascii_only?
-
domain = domain.chomp(".").unicode_normalize(:nfc)
-
domain = Punycode.encode_hostname(domain)
-
end
-
-
570
domain.downcase
-
end
-
end
-
-
# Parses _hostname_ into a DomainName object. An IP address is also
-
# accepted. An IPv6 address may be enclosed in square brackets.
-
23
def initialize(hostname)
-
594
hostname = String(hostname)
-
-
594
raise ArgumentError, "domain name must not start with a dot: #{hostname}" if hostname.start_with?(".")
-
-
begin
-
594
@ipaddr = IPAddr.new(hostname)
-
24
@hostname = @ipaddr.to_s
-
24
return
-
rescue IPAddr::Error
-
570
nil
-
end
-
-
570
@hostname = DomainName.normalize(hostname)
-
570
tld = if (last_dot = @hostname.rindex("."))
-
138
@hostname[(last_dot + 1)..-1]
-
else
-
432
@hostname
-
end
-
-
# unknown/local TLD
-
570
@domain = if last_dot
-
# fallback - accept cookies down to second level
-
# cf. http://www.dkim-reputation.org/regdom-libs/
-
138
if (penultimate_dot = @hostname.rindex(".", last_dot - 1))
-
36
@hostname[(penultimate_dot + 1)..-1]
-
else
-
102
@hostname
-
end
-
else
-
# no domain part - must be a local hostname
-
432
tld
-
end
-
end
-
-
# Checks if the server represented by this domain is qualified to
-
# send and receive cookies with a domain attribute value of
-
# _domain_. A true value given as the second argument represents
-
# cookies without a domain attribute value, in which case only
-
# hostname equality is checked.
-
23
def cookie_domain?(domain, host_only = false)
-
# RFC 6265 #5.3
-
# When the user agent "receives a cookie":
-
24
return self == @domain if host_only
-
-
24
domain = DomainName.new(domain)
-
-
# RFC 6265 #5.1.3
-
# Do not perform subdomain matching against IP addresses.
-
24
@hostname == domain.hostname if @ipaddr
-
-
# RFC 6265 #4.1.1
-
# Domain-value must be a subdomain.
-
24
@domain && self <= domain && domain <= @domain
-
end
-
-
23
def <=>(other)
-
36
other = DomainName.new(other)
-
36
othername = other.hostname
-
36
if othername == @hostname
-
12
0
-
24
elsif @hostname.end_with?(othername) && @hostname[-othername.size - 1, 1] == "."
-
# The other is higher
-
12
-1
-
else
-
# The other is lower
-
12
1
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
# the default exception class for exceptions raised by HTTPX.
-
23
class Error < StandardError; end
-
-
23
class UnsupportedSchemeError < Error; end
-
-
23
class ConnectionError < Error; end
-
-
# Error raised when there was a timeout. Its subclasses allow for finer-grained
-
# control of which timeout happened.
-
23
class TimeoutError < Error
-
# The timeout value which caused this error to be raised.
-
23
attr_reader :timeout
-
-
# initializes the timeout exception with the +timeout+ causing the error, and the
-
# error +message+ for it.
-
23
def initialize(timeout, message)
-
370
@timeout = timeout
-
370
super(message)
-
end
-
-
# clones this error into a HTTPX::ConnectionTimeoutError.
-
23
def to_connection_error
-
18
ex = ConnectTimeoutError.new(@timeout, message)
-
18
ex.set_backtrace(backtrace)
-
18
ex
-
end
-
end
-
-
# Error raised when there was a timeout establishing the connection to a server.
-
# This may be raised due to timeouts during TCP and TLS (when applicable) connection
-
# establishment.
-
23
class ConnectTimeoutError < TimeoutError; end
-
-
# Error raised when there was a timeout while sending a request, or receiving a response
-
# from the server.
-
23
class RequestTimeoutError < TimeoutError
-
# The HTTPX::Request request object this exception refers to.
-
23
attr_reader :request
-
-
# initializes the exception with the +request+ and +response+ it refers to, and the
-
# +timeout+ causing the error, and the
-
23
def initialize(request, response, timeout)
-
296
@request = request
-
296
@response = response
-
296
super(timeout, "Timed out after #{timeout} seconds")
-
end
-
-
23
def marshal_dump
-
[message]
-
end
-
end
-
-
# Error raised when there was a timeout while receiving a response from the server.
-
23
class ReadTimeoutError < RequestTimeoutError; end
-
-
# Error raised when there was a timeout while sending a request from the server.
-
23
class WriteTimeoutError < RequestTimeoutError; end
-
-
# Error raised when there was a timeout while waiting for the HTTP/2 settings frame from the server.
-
23
class SettingsTimeoutError < TimeoutError; end
-
-
# Error raised when there was a timeout while resolving a domain to an IP.
-
23
class ResolveTimeoutError < TimeoutError; end
-
-
# Error raised when there was an error while resolving a domain to an IP.
-
23
class ResolveError < Error; end
-
-
# Error raised when there was an error while resolving a domain to an IP
-
# using a HTTPX::Resolver::Native resolver.
-
23
class NativeResolveError < ResolveError
-
23
attr_reader :connection, :host
-
-
# initializes the exception with the +connection+ it refers to, the +host+ domain
-
# which failed to resolve, and the error +message+.
-
23
def initialize(connection, host, message = "Can't resolve #{host}")
-
94
@connection = connection
-
94
@host = host
-
94
super(message)
-
end
-
end
-
-
# The exception class for HTTP responses with 4xx or 5xx status.
-
23
class HTTPError < Error
-
# The HTTPX::Response response object this exception refers to.
-
23
attr_reader :response
-
-
# Creates the instance and assigns the HTTPX::Response +response+.
-
23
def initialize(response)
-
73
@response = response
-
73
super("HTTP Error: #{@response.status} #{@response.headers}\n#{@response.body}")
-
end
-
-
# The HTTP response status.
-
#
-
# error.status #=> 404
-
23
def status
-
12
@response.status
-
end
-
end
-
-
# error raised when a request was sent a server which can't reproduce a response, and
-
# has therefore returned an HTTP response using the 421 status code.
-
23
class MisdirectedRequestError < HTTPError; end
-
end
-
# frozen_string_literal: true
-
-
23
require "uri"
-
-
23
module HTTPX
-
23
module ArrayExtensions
-
23
module FilterMap
-
refine Array do
-
# Ruby 2.7 backport
-
def filter_map
-
return to_enum(:filter_map) unless block_given?
-
-
each_with_object([]) do |item, res|
-
processed = yield(item)
-
res << processed if processed
-
end
-
end
-
23
end unless Array.method_defined?(:filter_map)
-
end
-
-
23
module Intersect
-
refine Array do
-
# Ruby 3.1 backport
-
4
def intersect?(arr)
-
if size < arr.size
-
smaller = self
-
else
-
smaller, arr = arr, self
-
end
-
(arr & smaller).size > 0
-
end
-
23
end unless Array.method_defined?(:intersect?)
-
end
-
end
-
-
23
module URIExtensions
-
# uri 0.11 backport, ships with ruby 3.1
-
23
refine URI::Generic do
-
-
23
def non_ascii_hostname
-
335
@non_ascii_hostname
-
end
-
-
23
def non_ascii_hostname=(hostname)
-
24
@non_ascii_hostname = hostname
-
end
-
-
def authority
-
5176
return host if port == default_port
-
-
333
"#{host}:#{port}"
-
23
end unless URI::HTTP.method_defined?(:authority)
-
-
def origin
-
4232
"#{scheme}://#{authority}"
-
23
end unless URI::HTTP.method_defined?(:origin)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
class Headers
-
23
class << self
-
23
def new(headers = nil)
-
18449
return headers if headers.is_a?(self)
-
-
8981
super
-
end
-
end
-
-
23
def initialize(headers = nil)
-
8981
@headers = {}
-
8981
return unless headers
-
-
8847
headers.each do |field, value|
-
43601
array_value(value).each do |v|
-
43859
add(downcased(field), v)
-
end
-
end
-
end
-
-
# cloned initialization
-
23
def initialize_clone(orig)
-
6
super
-
6
@headers = orig.instance_variable_get(:@headers).clone
-
end
-
-
# dupped initialization
-
23
def initialize_dup(orig)
-
10124
super
-
10124
@headers = orig.instance_variable_get(:@headers).dup
-
end
-
-
# freezes the headers hash
-
23
def freeze
-
11264
@headers.freeze
-
11264
super
-
end
-
-
23
def same_headers?(headers)
-
24
@headers.empty? || begin
-
24
headers.each do |k, v|
-
54
next unless key?(k)
-
-
54
return false unless v == self[k]
-
end
-
12
true
-
end
-
end
-
-
# merges headers with another header-quack.
-
# the merge rule is, if the header already exists,
-
# ignore what the +other+ headers has. Otherwise, set
-
#
-
23
def merge(other)
-
3197
headers = dup
-
3197
other.each do |field, value|
-
2336
headers[downcased(field)] = value
-
end
-
3197
headers
-
end
-
-
# returns the comma-separated values of the header field
-
# identified by +field+, or nil otherwise.
-
#
-
23
def [](field)
-
63060
a = @headers[downcased(field)] || return
-
18802
a.join(", ")
-
end
-
-
# sets +value+ (if not nil) as single value for the +field+ header.
-
#
-
23
def []=(field, value)
-
27691
return unless value
-
-
23984
@headers[downcased(field)] = array_value(value)
-
end
-
-
# deletes all values associated with +field+ header.
-
#
-
23
def delete(field)
-
118
canonical = downcased(field)
-
118
@headers.delete(canonical) if @headers.key?(canonical)
-
end
-
-
# adds additional +value+ to the existing, for header +field+.
-
#
-
23
def add(field, value)
-
44183
(@headers[downcased(field)] ||= []) << String(value)
-
end
-
-
# helper to be used when adding an header field as a value to another field
-
#
-
# h2_headers.add_header("vary", "accept-encoding")
-
# h2_headers["vary"] #=> "accept-encoding"
-
# h1_headers.add_header("vary", "accept-encoding")
-
# h1_headers["vary"] #=> "Accept-Encoding"
-
#
-
23
alias_method :add_header, :add
-
-
# returns the enumerable headers store in pairs of header field + the values in
-
# the comma-separated string format
-
#
-
23
def each(extra_headers = nil)
-
46332
return enum_for(__method__, extra_headers) { @headers.size } unless block_given?
-
-
24949
@headers.each do |field, value|
-
31912
yield(field, value.join(", ")) unless value.empty?
-
end
-
-
5959
extra_headers.each do |field, value|
-
16943
yield(field, value) unless value.empty?
-
24937
end if extra_headers
-
end
-
-
23
def ==(other)
-
14388
other == to_hash
-
end
-
-
# the headers store in Hash format
-
23
def to_hash
-
15263
Hash[to_a]
-
end
-
23
alias_method :to_h, :to_hash
-
-
# the headers store in array of pairs format
-
23
def to_a
-
15280
Array(each)
-
end
-
-
# headers as string
-
23
def to_s
-
1427
@headers.to_s
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
to_hash.inspect
-
skipped
end
-
skipped
# :nocov:
-
-
# this is internal API and doesn't abide to other public API
-
# guarantees, like downcasing strings.
-
# Please do not use this outside of core!
-
#
-
23
def key?(downcased_key)
-
43836
@headers.key?(downcased_key)
-
end
-
-
# returns the values for the +field+ header in array format.
-
# This method is more internal, and for this reason doesn't try
-
# to "correct" the user input, i.e. it doesn't downcase the key.
-
#
-
23
def get(field)
-
198
@headers[field] || EMPTY
-
end
-
-
23
private
-
-
23
def array_value(value)
-
61446
case value
-
when Array
-
67758
value.map { |val| String(val).strip }
-
else
-
40916
[String(value).strip]
-
end
-
end
-
-
23
def downcased(field)
-
181554
String(field).downcase
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "socket"
-
23
require "httpx/io/udp"
-
23
require "httpx/io/tcp"
-
23
require "httpx/io/unix"
-
-
begin
-
23
require "httpx/io/ssl"
-
rescue LoadError
-
end
-
# frozen_string_literal: true
-
-
23
require "openssl"
-
-
23
module HTTPX
-
23
TLSError = OpenSSL::SSL::SSLError
-
-
23
class SSL < TCP
-
# rubocop:disable Style/MutableConstant
-
23
TLS_OPTIONS = { alpn_protocols: %w[h2 http/1.1].freeze }
-
# https://github.com/jruby/jruby-openssl/issues/284
-
23
TLS_OPTIONS[:verify_hostname] = true if RUBY_ENGINE == "jruby"
-
# rubocop:enable Style/MutableConstant
-
23
TLS_OPTIONS.freeze
-
-
23
attr_writer :ssl_session
-
-
23
def initialize(_, _, options)
-
2163
super
-
-
2163
ctx_options = TLS_OPTIONS.merge(options.ssl)
-
2163
@sni_hostname = ctx_options.delete(:hostname) || @hostname
-
-
2163
if @keep_open && @io.is_a?(OpenSSL::SSL::SSLSocket)
-
# externally initiated ssl socket
-
17
@ctx = @io.context
-
17
@state = :negotiated
-
else
-
2146
@ctx = OpenSSL::SSL::SSLContext.new
-
2146
@ctx.set_params(ctx_options) unless ctx_options.empty?
-
2146
unless @ctx.session_cache_mode.nil? # a dummy method on JRuby
-
2146
@ctx.session_cache_mode =
-
OpenSSL::SSL::SSLContext::SESSION_CACHE_CLIENT | OpenSSL::SSL::SSLContext::SESSION_CACHE_NO_INTERNAL_STORE
-
end
-
-
2146
yield(self) if block_given?
-
end
-
-
2163
@verify_hostname = @ctx.verify_hostname
-
end
-
-
23
if OpenSSL::SSL::SSLContext.method_defined?(:session_new_cb=)
-
23
def session_new_cb(&pr)
-
6077
@ctx.session_new_cb = proc { |_, sess| pr.call(sess) }
-
end
-
else
-
# session_new_cb not implemented under JRuby
-
def session_new_cb; end
-
end
-
-
23
def protocol
-
2231
@io.alpn_protocol || super
-
rescue StandardError
-
8
super
-
end
-
-
23
if RUBY_ENGINE == "jruby"
-
# in jruby, alpn_protocol may return ""
-
# https://github.com/jruby/jruby-openssl/issues/287
-
def protocol
-
proto = @io.alpn_protocol
-
-
return super if proto.nil? || proto.empty?
-
-
proto
-
rescue StandardError
-
super
-
end
-
end
-
-
23
def can_verify_peer?
-
11
@ctx.verify_mode == OpenSSL::SSL::VERIFY_PEER
-
end
-
-
23
def verify_hostname(host)
-
13
return false if @ctx.verify_mode == OpenSSL::SSL::VERIFY_NONE
-
13
return false if !@io.respond_to?(:peer_cert) || @io.peer_cert.nil?
-
-
13
OpenSSL::SSL.verify_certificate_identity(@io.peer_cert, host)
-
end
-
-
23
def connected?
-
7929
@state == :negotiated
-
end
-
-
23
def expired?
-
super || ssl_session_expired?
-
end
-
-
23
def ssl_session_expired?
-
2197
@ssl_session.nil? || Process.clock_gettime(Process::CLOCK_REALTIME) >= (@ssl_session.time.to_f + @ssl_session.timeout)
-
end
-
-
23
def connect
-
7968
super
-
7947
return if @state == :negotiated ||
-
@state != :connected
-
-
5549
unless @io.is_a?(OpenSSL::SSL::SSLSocket)
-
2197
if (hostname_is_ip = (@ip == @sni_hostname))
-
# IPv6 address would be "[::1]", must turn to "0000:0000:0000:0000:0000:0000:0000:0001" for cert SAN check
-
24
@sni_hostname = @ip.to_string
-
# IP addresses in SNI is not valid per RFC 6066, section 3.
-
24
@ctx.verify_hostname = false
-
end
-
-
2197
@io = OpenSSL::SSL::SSLSocket.new(@io, @ctx)
-
-
2197
@io.hostname = @sni_hostname unless hostname_is_ip
-
2197
@io.session = @ssl_session unless ssl_session_expired?
-
2197
@io.sync_close = true
-
end
-
5549
try_ssl_connect
-
end
-
-
23
def try_ssl_connect
-
5549
ret = @io.connect_nonblock(exception: false)
-
5559
log(level: 3, color: :cyan) { "TLS CONNECT: #{ret}..." }
-
4899
case ret
-
when :wait_readable
-
3370
@interests = :r
-
3370
return
-
when :wait_writable
-
@interests = :w
-
return
-
end
-
2161
@io.post_connection_check(@sni_hostname) if @ctx.verify_mode != OpenSSL::SSL::VERIFY_NONE && @verify_hostname
-
2161
transition(:negotiated)
-
2161
@interests = :w
-
end
-
-
23
private
-
-
23
def transition(nextstate)
-
7286
case nextstate
-
when :negotiated
-
2161
return unless @state == :connected
-
-
when :closed
-
2144
return unless @state == :negotiated ||
-
@state == :connected
-
end
-
8584
do_transition(nextstate)
-
end
-
-
23
def log_transition_state(nextstate)
-
53
return super unless nextstate == :negotiated
-
-
12
server_cert = @io.peer_cert
-
-
10
"#{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
-
-
23
require "resolv"
-
23
require "ipaddr"
-
-
23
module HTTPX
-
23
class TCP
-
23
include Loggable
-
-
23
using URIExtensions
-
-
23
attr_reader :ip, :port, :addresses, :state, :interests
-
-
23
alias_method :host, :ip
-
-
23
def initialize(origin, addresses, options)
-
4887
@state = :idle
-
4887
@addresses = []
-
4887
@hostname = origin.host
-
4887
@options = Options.new(options)
-
4887
@fallback_protocol = @options.fallback_protocol
-
4887
@port = origin.port
-
4887
@interests = :w
-
4887
if @options.io
-
40
@io = case @options.io
-
when Hash
-
12
@options.io[origin.authority]
-
else
-
28
@options.io
-
end
-
40
raise Error, "Given IO objects do not match the request authority" unless @io
-
-
40
_, _, _, @ip = @io.addr
-
40
@addresses << @ip
-
40
@keep_open = true
-
40
@state = :connected
-
else
-
4847
add_addresses(addresses)
-
end
-
4887
@ip_index = @addresses.size - 1
-
end
-
-
23
def socket
-
147
@io
-
end
-
-
23
def add_addresses(addrs)
-
5020
return if addrs.empty?
-
-
14874
addrs = addrs.map { |addr| addr.is_a?(IPAddr) ? addr : IPAddr.new(addr) }
-
-
5020
ip_index = @ip_index || (@addresses.size - 1)
-
5020
if addrs.first.ipv6?
-
# should be the next in line
-
173
@addresses = [*@addresses[0, ip_index], *addrs, *@addresses[ip_index..-1]]
-
else
-
4847
@addresses.unshift(*addrs)
-
4847
@ip_index += addrs.size if @ip_index
-
end
-
end
-
-
23
def to_io
-
17394
@io.to_io
-
end
-
-
23
def protocol
-
3008
@fallback_protocol
-
end
-
-
23
def connect
-
17396
return unless closed?
-
-
13868
if !@io || @io.closed?
-
5271
transition(:idle)
-
5271
@io = build_socket
-
end
-
13868
try_connect
-
rescue Errno::ECONNREFUSED,
-
Errno::EADDRNOTAVAIL,
-
Errno::EHOSTUNREACH,
-
SocketError,
-
IOError => e
-
312
raise e if @ip_index <= 0
-
-
273
log { "failed connecting to #{@ip} (#{e.message}), trying next..." }
-
255
@ip_index -= 1
-
263
@io = build_socket
-
263
retry
-
rescue Errno::ETIMEDOUT => e
-
raise ConnectTimeoutError.new(@options.timeout[:connect_timeout], e.message) if @ip_index <= 0
-
-
log { "failed connecting to #{@ip} (#{e.message}), trying next..." }
-
@ip_index -= 1
-
@io = build_socket
-
retry
-
end
-
-
23
def try_connect
-
13868
ret = @io.connect_nonblock(Socket.sockaddr_in(@port, @ip.to_s), exception: false)
-
10816
log(level: 3, color: :cyan) { "TCP CONNECT: #{ret}..." }
-
9158
case ret
-
when :wait_readable
-
@interests = :r
-
return
-
when :wait_writable
-
5519
@interests = :w
-
5519
return
-
end
-
5217
transition(:connected)
-
5217
@interests = :w
-
rescue Errno::EALREADY
-
2815
@interests = :w
-
end
-
23
private :try_connect
-
-
23
def read(size, buffer)
-
34383
ret = @io.read_nonblock(size, buffer, exception: false)
-
34383
if ret == :wait_readable
-
6416
buffer.clear
-
5864
return 0
-
end
-
27967
return if ret.nil?
-
-
28020
log { "READ: #{buffer.bytesize} bytes..." }
-
27957
buffer.bytesize
-
end
-
-
23
def write(buffer)
-
15398
siz = @io.write_nonblock(buffer, exception: false)
-
15380
return 0 if siz == :wait_writable
-
15358
return if siz.nil?
-
-
15424
log { "WRITE: #{siz} bytes..." }
-
-
15358
buffer.shift!(siz)
-
15358
siz
-
end
-
-
23
def close
-
5787
return if @keep_open || closed?
-
-
begin
-
5148
@io.close
-
ensure
-
5148
transition(:closed)
-
end
-
end
-
-
23
def connected?
-
9144
@state == :connected
-
end
-
-
23
def closed?
-
23149
@state == :idle || @state == :closed
-
end
-
-
23
def expired?
-
# do not mess with external sockets
-
return false if @options.io
-
-
return true unless @addresses
-
-
resolver_addresses = Resolver.nolookup_resolve(@hostname)
-
-
(Array(resolver_addresses) & @addresses).empty?
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}: #{@ip}:#{@port} (state: #{@state})>"
-
skipped
end
-
skipped
# :nocov:
-
-
23
private
-
-
23
def build_socket
-
5534
@ip = @addresses[@ip_index]
-
5534
Socket.new(@ip.family, :STREAM, 0)
-
end
-
-
23
def transition(nextstate)
-
7852
case nextstate
-
# when :idle
-
when :connected
-
3100
return unless @state == :idle
-
when :closed
-
3004
return unless @state == :connected
-
end
-
9231
do_transition(nextstate)
-
end
-
-
23
def do_transition(nextstate)
-
17927
log(level: 1) { log_transition_state(nextstate) }
-
17815
@state = nextstate
-
end
-
-
23
def log_transition_state(nextstate)
-
95
case nextstate
-
when :connected
-
30
"Connected to #{host} (##{@io.fileno})"
-
else
-
70
"#{host} #{@state} -> #{nextstate}"
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "ipaddr"
-
-
23
module HTTPX
-
23
class UDP
-
23
include Loggable
-
-
23
def initialize(ip, port, options)
-
499
@host = ip
-
499
@port = port
-
499
@io = UDPSocket.new(IPAddr.new(ip).family)
-
499
@options = options
-
end
-
-
23
def to_io
-
984
@io.to_io
-
end
-
-
23
def connect; end
-
-
23
def connected?
-
499
true
-
end
-
-
23
def close
-
729
@io.close
-
end
-
-
23
if RUBY_ENGINE == "jruby"
-
# In JRuby, sendmsg_nonblock is not implemented
-
def write(buffer)
-
siz = @io.send(buffer.to_s, 0, @host, @port)
-
log { "WRITE: #{siz} bytes..." }
-
buffer.shift!(siz)
-
siz
-
end
-
else
-
23
def write(buffer)
-
538
siz = @io.sendmsg_nonblock(buffer.to_s, 0, Socket.sockaddr_in(@port, @host.to_s), exception: false)
-
538
return 0 if siz == :wait_writable
-
538
return if siz.nil?
-
-
538
log { "WRITE: #{siz} bytes..." }
-
-
538
buffer.shift!(siz)
-
538
siz
-
end
-
end
-
-
23
def read(size, buffer)
-
725
ret = @io.recvfrom_nonblock(size, 0, buffer, exception: false)
-
725
return 0 if ret == :wait_readable
-
491
return if ret.nil?
-
-
491
log { "READ: #{buffer.bytesize} bytes..." }
-
-
491
buffer.bytesize
-
rescue IOError
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
class UNIX < TCP
-
23
using URIExtensions
-
-
23
attr_reader :path
-
-
23
alias_method :host, :path
-
-
23
def initialize(origin, addresses, options)
-
24
@addresses = []
-
24
@hostname = origin.host
-
24
@state = :idle
-
24
@options = Options.new(options)
-
24
@fallback_protocol = @options.fallback_protocol
-
24
if @options.io
-
12
@io = case @options.io
-
when Hash
-
6
@options.io[origin.authority]
-
else
-
6
@options.io
-
end
-
12
raise Error, "Given IO objects do not match the request authority" unless @io
-
-
12
@path = @io.path
-
12
@keep_open = true
-
12
@state = :connected
-
else
-
12
@path = addresses.first
-
end
-
24
@io ||= build_socket
-
end
-
-
23
def connect
-
18
return unless closed?
-
-
begin
-
18
if @io.closed?
-
6
transition(:idle)
-
6
@io = build_socket
-
end
-
18
@io.connect_nonblock(Socket.sockaddr_un(@path))
-
rescue Errno::EISCONN
-
end
-
12
transition(:connected)
-
rescue Errno::EINPROGRESS,
-
Errno::EALREADY,
-
::IO::WaitReadable
-
end
-
-
23
def expired?
-
false
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}(path: #{@path}): (state: #{@state})>"
-
skipped
end
-
skipped
# :nocov:
-
-
23
private
-
-
23
def build_socket
-
18
Socket.new(Socket::PF_UNIX, :STREAM, 0)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Loggable
-
23
COLORS = {
-
black: 30,
-
red: 31,
-
green: 32,
-
yellow: 33,
-
blue: 34,
-
magenta: 35,
-
cyan: 36,
-
white: 37,
-
}.freeze
-
-
23
def log(level: @options.debug_level, color: nil, &msg)
-
272256
return unless @options.debug
-
1255
return unless @options.debug_level >= level
-
-
1255
debug_stream = @options.debug
-
-
1255
message = (+"" << msg.call << "\n")
-
1255
message = "\e[#{COLORS[color]}m#{message}\e[0m" if color && debug_stream.respond_to?(:isatty) && debug_stream.isatty
-
1255
debug_stream << message
-
end
-
-
23
def log_exception(ex, level: @options.debug_level, color: nil)
-
818
return unless @options.debug
-
10
return unless @options.debug_level >= level
-
-
20
log(level: level, color: color) { ex.full_message }
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "socket"
-
-
23
module HTTPX
-
# Contains a set of options which are passed and shared across from session to its requests or
-
# responses.
-
23
class Options
-
23
BUFFER_SIZE = 1 << 14
-
23
WINDOW_SIZE = 1 << 14 # 16K
-
23
MAX_BODY_THRESHOLD_SIZE = (1 << 10) * 112 # 112K
-
23
KEEP_ALIVE_TIMEOUT = 20
-
23
SETTINGS_TIMEOUT = 10
-
23
CLOSE_HANDSHAKE_TIMEOUT = 10
-
23
CONNECT_TIMEOUT = READ_TIMEOUT = WRITE_TIMEOUT = 60
-
23
REQUEST_TIMEOUT = OPERATION_TIMEOUT = nil
-
-
# https://github.com/ruby/resolv/blob/095f1c003f6073730500f02acbdbc55f83d70987/lib/resolv.rb#L408
-
1
ip_address_families = begin
-
23
list = Socket.ip_address_list
-
116
if list.any? { |a| a.ipv6? && !a.ipv6_loopback? && !a.ipv6_linklocal? && !a.ipv6_unique_local? }
-
[Socket::AF_INET6, Socket::AF_INET]
-
else
-
23
[Socket::AF_INET]
-
end
-
rescue NotImplementedError
-
[Socket::AF_INET]
-
end
-
-
1
DEFAULT_OPTIONS = {
-
22
:max_requests => Float::INFINITY,
-
23
:debug => ENV.key?("HTTPX_DEBUG") ? $stderr : nil,
-
23
:debug_level => (ENV["HTTPX_DEBUG"] || 1).to_i,
-
:ssl => {},
-
:http2_settings => { settings_enable_push: 0 },
-
:fallback_protocol => "http/1.1",
-
:supported_compression_formats => %w[gzip deflate],
-
:decompress_response_body => true,
-
:compress_request_body => true,
-
:timeout => {
-
connect_timeout: CONNECT_TIMEOUT,
-
settings_timeout: SETTINGS_TIMEOUT,
-
close_handshake_timeout: CLOSE_HANDSHAKE_TIMEOUT,
-
operation_timeout: OPERATION_TIMEOUT,
-
keep_alive_timeout: KEEP_ALIVE_TIMEOUT,
-
read_timeout: READ_TIMEOUT,
-
write_timeout: WRITE_TIMEOUT,
-
request_timeout: REQUEST_TIMEOUT,
-
},
-
:headers_class => Class.new(Headers),
-
:headers => {},
-
:window_size => WINDOW_SIZE,
-
:buffer_size => BUFFER_SIZE,
-
:body_threshold_size => MAX_BODY_THRESHOLD_SIZE,
-
:request_class => Class.new(Request),
-
:response_class => Class.new(Response),
-
:request_body_class => Class.new(Request::Body),
-
:response_body_class => Class.new(Response::Body),
-
:connection_class => Class.new(Connection),
-
:options_class => Class.new(self),
-
:transport => nil,
-
:addresses => nil,
-
:persistent => false,
-
23
:resolver_class => (ENV["HTTPX_RESOLVER"] || :native).to_sym,
-
:resolver_options => { cache: true },
-
:ip_families => ip_address_families,
-
}.freeze
-
-
23
class << self
-
23
def new(options = {})
-
# let enhanced options go through
-
26100
return options if self == Options && options.class < self
-
17478
return options if options.is_a?(self)
-
-
3147
super
-
end
-
-
23
def method_added(meth)
-
13348
super
-
-
13348
return unless meth =~ /^option_(.+)$/
-
-
6192
optname = Regexp.last_match(1).to_sym
-
-
6192
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 HTTP2Next::Connection (ex: <tt>{ max_concurrent_streams: 2 }</tt>)
-
# :fallback_protocol :: version of HTTP protocol to use by default in the absence of protocol negotiation
-
# like ALPN (defaults to <tt>"http/1.1"</tt>)
-
# :supported_compression_formats :: list of compressions supported by the transcoder layer (defaults to <tt>%w[gzip deflate]</tt>).
-
# :decompress_response_body :: whether to auto-decompress response body (defaults to <tt>true</tt>).
-
# :compress_request_body :: whether to auto-decompress response body (defaults to <tt>true</tt>)
-
# :timeout :: hash of timeout configurations (supports <tt>:connect_timeout</tt>, <tt>:settings_timeout</tt>,
-
# <tt>:operation_timeout</tt>, <tt>:keep_alive_timeout</tt>, <tt>:read_timeout</tt>, <tt>:write_timeout</tt>
-
# and <tt>:request_timeout</tt>
-
# :headers :: hash of HTTP headers (ex: <tt>{ "x-custom-foo" => "bar" }</tt>)
-
# :window_size :: number of bytes to read from a socket
-
# :buffer_size :: internal read and write buffer size in bytes
-
# :body_threshold_size :: maximum size in bytes of response payload that is buffered in memory.
-
# :request_class :: class used to instantiate a request
-
# :response_class :: class used to instantiate a response
-
# :headers_class :: class used to instantiate headers
-
# :request_body_class :: class used to instantiate a request body
-
# :response_body_class :: class used to instantiate a response body
-
# :connection_class :: class used to instantiate connections
-
# :options_class :: class used to instantiate options
-
# :transport :: type of transport to use (set to "unix" for UNIX sockets)
-
# :addresses :: bucket of peer addresses (can be a list of IP addresses, a hash of domain to list of adddresses;
-
# paths should be used for UNIX sockets instead)
-
# :io :: open socket, or domain/ip-to-socket hash, which requests should be sent to
-
# :persistent :: whether to persist connections in between requests (defaults to <tt>true</tt>)
-
# :resolver_class :: which resolver to use (defaults to <tt>:native</tt>, can also be <tt>:system<tt> for
-
# using getaddrinfo or <tt>:https</tt> for DoH resolver, or a custom class)
-
# :resolver_options :: hash of options passed to the resolver
-
# :ip_families :: which socket families are supported (system-dependent)
-
# :origin :: HTTP origin to set on requests with relative path (ex: "https://api.serv.com")
-
# :base_path :: path to prefix given relative paths with (ex: "/v2")
-
# :max_concurrent_requests :: max number of requests which can be set concurrently
-
# :max_requests :: max number of requests which can be made on socket before it reconnects.
-
# :params :: hash or array of key-values which will be encoded and set in the query string of request uris.
-
# :form :: hash of array of key-values which will be form-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.
-
#
-
# This list of options are enhanced with each loaded plugin, see the plugin docs for details.
-
23
def initialize(options = {})
-
3147
do_initialize(options)
-
3135
freeze
-
end
-
-
23
def freeze
-
7985
super
-
7985
@origin.freeze
-
7985
@base_path.freeze
-
7985
@timeout.freeze
-
7985
@headers.freeze
-
7985
@addresses.freeze
-
7985
@supported_compression_formats.freeze
-
end
-
-
23
def option_origin(value)
-
480
URI(value)
-
end
-
-
23
def option_base_path(value)
-
24
String(value)
-
end
-
-
23
def option_headers(value)
-
6159
headers_class.new(value)
-
end
-
-
23
def option_timeout(value)
-
5775
Hash[value]
-
end
-
-
23
def option_supported_compression_formats(value)
-
5190
Array(value).map(&:to_s)
-
end
-
-
23
def option_max_concurrent_requests(value)
-
672
raise TypeError, ":max_concurrent_requests must be positive" unless value.positive?
-
-
672
value
-
end
-
-
23
def option_max_requests(value)
-
5178
raise TypeError, ":max_requests must be positive" unless value.positive?
-
-
5178
value
-
end
-
-
23
def option_window_size(value)
-
5182
value = Integer(value)
-
-
5182
raise TypeError, ":window_size must be positive" unless value.positive?
-
-
5182
value
-
end
-
-
23
def option_buffer_size(value)
-
5182
value = Integer(value)
-
-
5182
raise TypeError, ":buffer_size must be positive" unless value.positive?
-
-
5182
value
-
end
-
-
23
def option_body_threshold_size(value)
-
5170
bytes = Integer(value)
-
5170
raise TypeError, ":body_threshold_size must be positive" unless bytes.positive?
-
-
5170
bytes
-
end
-
-
23
def option_transport(value)
-
42
transport = value.to_s
-
42
raise TypeError, "#{transport} is an unsupported transport type" unless %w[unix].include?(transport)
-
-
42
transport
-
end
-
-
23
def option_addresses(value)
-
35
Array(value)
-
end
-
-
23
def option_ip_families(value)
-
5170
Array(value)
-
end
-
-
23
%i[
-
params form json xml body ssl http2_settings
-
request_class response_class headers_class request_body_class
-
response_body_class connection_class options_class
-
io fallback_protocol debug debug_level resolver_class resolver_options
-
compress_request_body decompress_response_body
-
persistent
-
].each do |method_name|
-
529
class_eval(<<-OUT, __FILE__, __LINE__ + 1)
-
23
def option_#{method_name}(v); v; end # def option_smth(v); v; end
-
OUT
-
end
-
-
23
REQUEST_BODY_IVARS = %i[@headers @params @form @xml @json @body].freeze
-
-
23
def ==(other)
-
3576
super || options_equals?(other)
-
end
-
-
23
def options_equals?(other, ignore_ivars = REQUEST_BODY_IVARS)
-
# headers and other request options do not play a role, as they are
-
# relevant only for the request.
-
2302
ivars = instance_variables - ignore_ivars
-
2302
other_ivars = other.instance_variables - ignore_ivars
-
-
2302
return false if ivars.size != other_ivars.size
-
-
1188
return false if ivars.sort != other_ivars.sort
-
-
1144
ivars.all? do |ivar|
-
13966
instance_variable_get(ivar) == other.instance_variable_get(ivar)
-
end
-
end
-
-
23
OTHER_LOOKUP = ->(obj, k, ivar_map) {
-
201271
case obj
-
when Hash
-
23171
obj[ivar_map[k]]
-
else
-
209318
obj.instance_variable_get(k)
-
end
-
}
-
23
def merge(other)
-
27235
ivar_map = nil
-
27235
other_ivars = case other
-
when Hash
-
33819
ivar_map = other.keys.to_h { |k| [:"@#{k}", k] }
-
19940
ivar_map.keys
-
else
-
7295
other.instance_variables
-
end
-
-
27235
return self if other_ivars.empty?
-
-
184721
return self if other_ivars.all? { |ivar| instance_variable_get(ivar) == OTHER_LOOKUP[other, ivar, ivar_map] }
-
-
10999
opts = dup
-
-
10999
other_ivars.each do |ivar|
-
64165
v = OTHER_LOOKUP[other, ivar, ivar_map]
-
-
64165
unless v
-
2488
opts.instance_variable_set(ivar, v)
-
2488
next
-
end
-
-
61677
v = opts.__send__(:"option_#{ivar[1..-1]}", v)
-
-
61677
orig_v = instance_variable_get(ivar)
-
-
61677
v = orig_v.merge(v) if orig_v.respond_to?(:merge) && v.respond_to?(:merge)
-
-
61677
opts.instance_variable_set(ivar, v)
-
end
-
-
10999
opts
-
end
-
-
23
def to_hash
-
2143
instance_variables.each_with_object({}) do |ivar, hs|
-
44534
hs[ivar[1..-1].to_sym] = instance_variable_get(ivar)
-
end
-
end
-
-
23
def extend_with_plugin_classes(pl)
-
4815
if defined?(pl::RequestMethods) || defined?(pl::RequestClassMethods)
-
1403
@request_class = @request_class.dup
-
1403
@request_class.__send__(:include, pl::RequestMethods) if defined?(pl::RequestMethods)
-
1403
@request_class.extend(pl::RequestClassMethods) if defined?(pl::RequestClassMethods)
-
end
-
4815
if defined?(pl::ResponseMethods) || defined?(pl::ResponseClassMethods)
-
1489
@response_class = @response_class.dup
-
1489
@response_class.__send__(:include, pl::ResponseMethods) if defined?(pl::ResponseMethods)
-
1489
@response_class.extend(pl::ResponseClassMethods) if defined?(pl::ResponseClassMethods)
-
end
-
4815
if defined?(pl::HeadersMethods) || defined?(pl::HeadersClassMethods)
-
114
@headers_class = @headers_class.dup
-
114
@headers_class.__send__(:include, pl::HeadersMethods) if defined?(pl::HeadersMethods)
-
114
@headers_class.extend(pl::HeadersClassMethods) if defined?(pl::HeadersClassMethods)
-
end
-
4815
if defined?(pl::RequestBodyMethods) || defined?(pl::RequestBodyClassMethods)
-
141
@request_body_class = @request_body_class.dup
-
141
@request_body_class.__send__(:include, pl::RequestBodyMethods) if defined?(pl::RequestBodyMethods)
-
141
@request_body_class.extend(pl::RequestBodyClassMethods) if defined?(pl::RequestBodyClassMethods)
-
end
-
4815
if defined?(pl::ResponseBodyMethods) || defined?(pl::ResponseBodyClassMethods)
-
402
@response_body_class = @response_body_class.dup
-
402
@response_body_class.__send__(:include, pl::ResponseBodyMethods) if defined?(pl::ResponseBodyMethods)
-
402
@response_body_class.extend(pl::ResponseBodyClassMethods) if defined?(pl::ResponseBodyClassMethods)
-
end
-
4815
if defined?(pl::ConnectionMethods)
-
1994
@connection_class = @connection_class.dup
-
1994
@connection_class.__send__(:include, pl::ConnectionMethods)
-
end
-
4815
return unless defined?(pl::OptionsMethods)
-
-
1815
@options_class = @options_class.dup
-
1815
@options_class.__send__(:include, pl::OptionsMethods)
-
end
-
-
23
private
-
-
23
def do_initialize(options = {})
-
3147
defaults = DEFAULT_OPTIONS.merge(options)
-
3147
defaults.each do |k, v|
-
86000
next if v.nil?
-
-
76559
option_method_name = :"option_#{k}"
-
76559
raise Error, "unknown option: #{k}" unless respond_to?(option_method_name)
-
-
76553
value = __send__(option_method_name, v)
-
76547
instance_variable_set(:"@#{k}", value)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Parser
-
23
class Error < Error; end
-
-
23
class HTTP1
-
23
VERSIONS = %w[1.0 1.1].freeze
-
-
23
attr_reader :status_code, :http_version, :headers
-
-
23
def initialize(observer)
-
3134
@observer = observer
-
3134
@state = :idle
-
3134
@buffer = "".b
-
3134
@headers = {}
-
end
-
-
23
def <<(chunk)
-
5053
@buffer << chunk
-
5053
parse
-
end
-
-
23
def reset!
-
9065
@state = :idle
-
9065
@headers.clear
-
9065
@content_length = nil
-
9065
@_has_trailers = nil
-
end
-
-
23
def upgrade?
-
3246
@upgrade
-
end
-
-
23
def upgrade_data
-
24
@buffer
-
end
-
-
23
private
-
-
23
def parse
-
5053
loop do
-
10902
state = @state
-
9455
case @state
-
when :idle
-
3506
parse_headline
-
when :headers, :trailers
-
3573
parse_headers
-
when :data
-
3823
parse_data
-
end
-
8115
return if @buffer.empty? || state == @state
-
end
-
end
-
-
23
def parse_headline
-
3506
idx = @buffer.index("\n")
-
3506
return unless idx
-
-
3506
(m = %r{\AHTTP(?:/(\d+\.\d+))?\s+(\d\d\d)(?:\s+(.*))?}in.match(@buffer)) ||
-
raise(Error, "wrong head line format")
-
3500
version, code, _ = m.captures
-
3500
raise(Error, "unsupported HTTP version (HTTP/#{version})") unless version && VERSIONS.include?(version)
-
-
3494
@http_version = version.split(".").map(&:to_i)
-
3494
@status_code = code.to_i
-
3494
raise(Error, "wrong status code (#{@status_code})") unless (100..599).cover?(@status_code)
-
-
3488
@buffer = @buffer.byteslice((idx + 1)..-1)
-
3488
nextstate(:headers)
-
end
-
-
23
def parse_headers
-
3573
headers = @headers
-
3573
buffer = @buffer
-
-
30294
while (idx = buffer.index("\n"))
-
27117
line = buffer.byteslice(0..idx)
-
27117
raise Error, "wrong header format" if line.start_with?("\s", "\t")
-
-
27111
line.lstrip!
-
27111
buffer = @buffer = buffer.byteslice((idx + 1)..-1)
-
27111
if line.empty?
-
3033
case @state
-
when :headers
-
3476
prepare_data(headers)
-
3476
@observer.on_headers(headers)
-
3007
return unless @state == :headers
-
-
# state might have been reset
-
# in the :headers callback
-
2951
nextstate(:data)
-
2951
headers.clear
-
when :trailers
-
12
@observer.on_trailers(headers)
-
12
headers.clear
-
12
nextstate(:complete)
-
end
-
2963
return
-
end
-
23623
separator_index = line.index(":")
-
23623
raise Error, "wrong header format" unless separator_index
-
-
23617
key = line.byteslice(0..(separator_index - 1))
-
-
23617
key.rstrip! # was lstripped previously!
-
23617
value = line.byteslice((separator_index + 1)..-1)
-
23617
value.strip!
-
23617
raise Error, "wrong header format" if value.nil?
-
-
23617
(headers[key.downcase] ||= []) << value
-
end
-
end
-
-
23
def parse_data
-
3823
if @buffer.respond_to?(:each)
-
144
@buffer.each do |chunk|
-
158
@observer.on_data(chunk)
-
end
-
3679
elsif @content_length
-
3655
data = @buffer.byteslice(0, @content_length)
-
3655
@buffer = @buffer.byteslice(@content_length..-1) || "".b
-
3162
@content_length -= data.bytesize
-
3655
@observer.on_data(data)
-
3644
data.clear
-
else
-
24
@observer.on_data(@buffer)
-
24
@buffer.clear
-
end
-
3806
return unless no_more_data?
-
-
2850
@buffer = @buffer.to_s
-
2850
if @_has_trailers
-
12
nextstate(:trailers)
-
else
-
2838
nextstate(:complete)
-
end
-
end
-
-
23
def prepare_data(headers)
-
3476
@upgrade = headers.key?("upgrade")
-
-
3476
@_has_trailers = headers.key?("trailer")
-
-
3476
if (tr_encodings = headers["transfer-encoding"])
-
80
tr_encodings.reverse_each do |tr_encoding|
-
80
tr_encoding.split(/ *, */).each do |encoding|
-
67
case encoding
-
when "chunked"
-
80
@buffer = Transcoder::Chunker::Decoder.new(@buffer, @_has_trailers)
-
end
-
end
-
end
-
else
-
3396
@content_length = headers["content-length"][0].to_i if headers.key?("content-length")
-
end
-
end
-
-
23
def no_more_data?
-
3806
if @content_length
-
3644
@content_length <= 0
-
162
elsif @buffer.respond_to?(:finished?)
-
138
@buffer.finished?
-
else
-
24
false
-
end
-
end
-
-
23
def nextstate(state)
-
9301
@state = state
-
8100
case state
-
when :headers
-
3488
@observer.on_start
-
when :complete
-
2850
@observer.on_complete
-
579
reset!
-
579
nextstate(:idle) unless @buffer.empty?
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds a shim +authorization+ method to the session, which will fill
-
# the HTTP Authorization header, and another, +bearer_auth+, which fill the "Bearer " prefix
-
# in its value.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Auth#auth
-
#
-
6
module Auth
-
6
module InstanceMethods
-
6
def authorization(token)
-
108
with(headers: { "authorization" => token })
-
end
-
-
6
def bearer_auth(token)
-
12
authorization("Bearer #{token}")
-
end
-
end
-
end
-
6
register_plugin :auth, Auth
-
end
-
end
-
# frozen_string_literal: true
-
-
7
require "httpx/base64"
-
-
7
module HTTPX
-
7
module Plugins
-
7
module Authentication
-
7
class Basic
-
7
def initialize(user, password, **)
-
205
@user = user
-
205
@password = password
-
end
-
-
7
def authenticate(*)
-
181
"Basic #{Base64.strict_encode64("#{@user}:#{@password}")}"
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
require "time"
-
6
require "securerandom"
-
6
require "digest"
-
-
6
module HTTPX
-
6
module Plugins
-
6
module Authentication
-
6
class Digest
-
6
def initialize(user, password, hashed: false, **)
-
144
@user = user
-
144
@password = password
-
144
@nonce = 0
-
144
@hashed = hashed
-
end
-
-
6
def can_authenticate?(authenticate)
-
120
authenticate && /Digest .*/.match?(authenticate)
-
end
-
-
6
def authenticate(request, authenticate)
-
120
"Digest #{generate_header(request.verb, request.path, authenticate)}"
-
end
-
-
6
private
-
-
6
def generate_header(meth, uri, authenticate)
-
# discard first token, it's Digest
-
120
auth_info = authenticate[/^(\w+) (.*)/, 2]
-
-
120
params = auth_info.split(/ *, */)
-
1248
.to_h { |val| val.split("=") }.transform_values { |v| v.delete("\"") }
-
120
nonce = params["nonce"]
-
120
nc = next_nonce
-
-
# verify qop
-
120
qop = params["qop"]
-
-
120
if params["algorithm"] =~ /(.*?)(-sess)?$/
-
108
alg = Regexp.last_match(1)
-
108
algorithm = ::Digest.const_get(alg)
-
108
raise DigestError, "unknown algorithm \"#{alg}\"" unless algorithm
-
-
108
sess = Regexp.last_match(2)
-
else
-
12
algorithm = ::Digest::MD5
-
end
-
-
120
if qop || sess
-
120
cnonce = make_cnonce
-
120
nc = format("%<nonce>08x", nonce: nc)
-
end
-
-
120
a1 = if sess
-
4
[
-
24
(@hashed ? @password : algorithm.hexdigest("#{@user}:#{params["realm"]}:#{@password}")),
-
nonce,
-
cnonce,
-
].join ":"
-
else
-
96
@hashed ? @password : "#{@user}:#{params["realm"]}:#{@password}"
-
end
-
-
120
ha1 = algorithm.hexdigest(a1)
-
120
ha2 = algorithm.hexdigest("#{meth}:#{uri}")
-
120
request_digest = [ha1, nonce]
-
120
request_digest.push(nc, cnonce, qop) if qop
-
120
request_digest << ha2
-
120
request_digest = request_digest.join(":")
-
-
20
header = [
-
120
%(username="#{@user}"),
-
20
%(nonce="#{nonce}"),
-
20
%(uri="#{uri}"),
-
20
%(response="#{algorithm.hexdigest(request_digest)}"),
-
]
-
120
header << %(realm="#{params["realm"]}") if params.key?("realm")
-
120
header << %(algorithm=#{params["algorithm"]}) if params.key?("algorithm")
-
120
header << %(cnonce="#{cnonce}") if cnonce
-
120
header << %(nc=#{nc})
-
120
header << %(qop=#{qop}) if qop
-
120
header << %(opaque="#{params["opaque"]}") if params.key?("opaque")
-
120
header.join ", "
-
end
-
-
6
def make_cnonce
-
120
::Digest::MD5.hexdigest [
-
Time.now.to_i,
-
Process.pid,
-
SecureRandom.random_number(2**32),
-
].join ":"
-
end
-
-
6
def next_nonce
-
100
@nonce += 1
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
5
require "httpx/base64"
-
5
require "ntlm"
-
-
5
module HTTPX
-
5
module Plugins
-
5
module Authentication
-
5
class Ntlm
-
5
def initialize(user, password, domain: nil)
-
4
@user = user
-
4
@password = password
-
4
@domain = domain
-
end
-
-
5
def can_authenticate?(authenticate)
-
2
authenticate && /NTLM .*/.match?(authenticate)
-
end
-
-
5
def negotiate
-
4
"NTLM #{NTLM.negotiate(domain: @domain).to_base64}"
-
end
-
-
5
def authenticate(_req, www)
-
2
challenge = www[/NTLM (.*)/, 1]
-
-
2
challenge = Base64.decode64(challenge)
-
2
ntlm_challenge = NTLM.authenticate(challenge, @user, @domain, @password).to_base64
-
-
2
"NTLM #{ntlm_challenge}"
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
module Plugins
-
8
module Authentication
-
8
class Socks5
-
8
def initialize(user, password, **)
-
36
@user = user
-
36
@password = password
-
end
-
-
8
def can_authenticate?(*)
-
36
@user && @password
-
end
-
-
8
def authenticate(*)
-
36
[0x01, @user.bytesize, @user, @password.bytesize, @password].pack("CCA*CA*")
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin applies AWS Sigv4 to requests, using the AWS SDK credentials and configuration.
-
#
-
# It requires the "aws-sdk-core" gem.
-
#
-
6
module AwsSdkAuthentication
-
# Mock configuration, to be used only when resolving credentials
-
6
class Configuration
-
6
attr_reader :profile
-
-
6
def initialize(profile)
-
24
@profile = profile
-
end
-
-
6
def respond_to_missing?(*)
-
12
true
-
end
-
-
6
def method_missing(*); end
-
end
-
-
#
-
# encapsulates access to an AWS SDK credentials store.
-
#
-
6
class Credentials
-
6
def initialize(aws_credentials)
-
12
@aws_credentials = aws_credentials
-
end
-
-
6
def username
-
12
@aws_credentials.access_key_id
-
end
-
-
6
def password
-
12
@aws_credentials.secret_access_key
-
end
-
-
6
def security_token
-
12
@aws_credentials.session_token
-
end
-
end
-
-
6
class << self
-
6
def load_dependencies(_klass)
-
12
require "aws-sdk-core"
-
end
-
-
6
def configure(klass)
-
12
klass.plugin(:aws_sigv4)
-
end
-
-
6
def extra_options(options)
-
12
options.merge(max_concurrent_requests: 1)
-
end
-
-
6
def credentials(profile)
-
12
mock_configuration = Configuration.new(profile)
-
12
Credentials.new(Aws::CredentialProviderChain.new(mock_configuration).resolve)
-
end
-
-
6
def region(profile)
-
# https://github.com/aws/aws-sdk-ruby/blob/version-3/gems/aws-sdk-core/lib/aws-sdk-core/plugins/regional_endpoint.rb#L62
-
12
keys = %w[AWS_REGION AMAZON_REGION AWS_DEFAULT_REGION]
-
12
env_region = ENV.values_at(*keys).compact.first
-
12
env_region = nil if env_region == ""
-
12
cfg_region = Aws.shared_config.region(profile: profile)
-
12
env_region || cfg_region
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_aws_profile(value)
-
60
String(value)
-
end
-
end
-
-
6
module InstanceMethods
-
#
-
# aws_authentication
-
# aws_authentication(credentials: Aws::Credentials.new('akid', 'secret'))
-
# aws_authentication()
-
#
-
6
def aws_sdk_authentication(
-
credentials: AwsSdkAuthentication.credentials(@options.aws_profile),
-
region: AwsSdkAuthentication.region(@options.aws_profile),
-
**options
-
)
-
-
12
aws_sigv4_authentication(
-
credentials: credentials,
-
region: region,
-
provider_prefix: "aws",
-
header_provider_field: "amz",
-
**options
-
)
-
end
-
6
alias_method :aws_auth, :aws_sdk_authentication
-
end
-
end
-
6
register_plugin :aws_sdk_authentication, AwsSdkAuthentication
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds AWS Sigv4 authentication.
-
#
-
# https://docs.aws.amazon.com/IAM/latest/UserGuide/signing-elements.html
-
#
-
# https://gitlab.com/os85/httpx/wikis/AWS-SigV4
-
#
-
6
module AWSSigV4
-
6
Credentials = Struct.new(:username, :password, :security_token)
-
-
6
class Signer
-
6
def initialize(
-
service:,
-
region:,
-
credentials: nil,
-
username: nil,
-
password: nil,
-
security_token: nil,
-
provider_prefix: "aws",
-
header_provider_field: "amz",
-
unsigned_headers: [],
-
apply_checksum_header: true,
-
algorithm: "SHA256"
-
)
-
96
@credentials = credentials || Credentials.new(username, password, security_token)
-
96
@service = service
-
96
@region = region
-
-
96
@unsigned_headers = Set.new(unsigned_headers.map(&:downcase))
-
96
@unsigned_headers << "authorization"
-
96
@unsigned_headers << "x-amzn-trace-id"
-
96
@unsigned_headers << "expect"
-
-
96
@apply_checksum_header = apply_checksum_header
-
96
@provider_prefix = provider_prefix
-
96
@header_provider_field = header_provider_field
-
-
96
@algorithm = algorithm
-
end
-
-
6
def sign!(request)
-
96
lower_provider_prefix = "#{@provider_prefix}4"
-
96
upper_provider_prefix = lower_provider_prefix.upcase
-
-
96
downcased_algorithm = @algorithm.downcase
-
-
96
datetime = (request.headers["x-#{@header_provider_field}-date"] ||= Time.now.utc.strftime("%Y%m%dT%H%M%SZ"))
-
96
date = datetime[0, 8]
-
-
96
content_hashed = request.headers["x-#{@header_provider_field}-content-#{downcased_algorithm}"] || hexdigest(request.body)
-
-
96
request.headers["x-#{@header_provider_field}-content-#{downcased_algorithm}"] ||= content_hashed if @apply_checksum_header
-
96
request.headers["x-#{@header_provider_field}-security-token"] ||= @credentials.security_token if @credentials.security_token
-
-
96
signature_headers = request.headers.each.reject do |k, _|
-
636
@unsigned_headers.include?(k)
-
end
-
# aws sigv4 needs to declare the host, regardless of protocol version
-
96
signature_headers << ["host", request.authority] unless request.headers.key?("host")
-
96
signature_headers.sort_by!(&:first)
-
-
96
signed_headers = signature_headers.map(&:first).join(";")
-
-
96
canonical_headers = signature_headers.map do |k, v|
-
# eliminate whitespace between value fields, unless it's a quoted value
-
520
"#{k}:#{v.start_with?("\"") && v.end_with?("\"") ? v : v.gsub(/\s+/, " ").strip}\n"
-
end.join
-
-
# canonical request
-
96
creq = "#{request.verb}" \
-
16
"\n#{request.canonical_path}" \
-
16
"\n#{request.canonical_query}" \
-
16
"\n#{canonical_headers}" \
-
16
"\n#{signed_headers}" \
-
16
"\n#{content_hashed}"
-
-
96
credential_scope = "#{date}" \
-
16
"/#{@region}" \
-
16
"/#{@service}" \
-
16
"/#{lower_provider_prefix}_request"
-
-
96
algo_line = "#{upper_provider_prefix}-HMAC-#{@algorithm}"
-
# string to sign
-
96
sts = "#{algo_line}" \
-
16
"\n#{datetime}" \
-
16
"\n#{credential_scope}" \
-
16
"\n#{hexdigest(creq)}"
-
-
# signature
-
96
k_date = hmac("#{upper_provider_prefix}#{@credentials.password}", date)
-
96
k_region = hmac(k_date, @region)
-
96
k_service = hmac(k_region, @service)
-
96
k_credentials = hmac(k_service, "#{lower_provider_prefix}_request")
-
96
sig = hexhmac(k_credentials, sts)
-
-
96
credential = "#{@credentials.username}/#{credential_scope}"
-
# apply signature
-
80
request.headers["authorization"] =
-
16
"#{algo_line} " \
-
16
"Credential=#{credential}, " \
-
16
"SignedHeaders=#{signed_headers}, " \
-
16
"Signature=#{sig}"
-
end
-
-
6
private
-
-
6
def hexdigest(value)
-
186
if value.respond_to?(:to_path)
-
# files, pathnames
-
6
OpenSSL::Digest.new(@algorithm).file(value.to_path).hexdigest
-
180
elsif value.respond_to?(:each)
-
84
digest = OpenSSL::Digest.new(@algorithm)
-
-
84
mb_buffer = value.each.with_object("".b) do |chunk, buffer|
-
30
buffer << chunk
-
30
break if buffer.bytesize >= 1024 * 1024
-
end
-
-
84
digest.update(mb_buffer)
-
84
value.rewind
-
84
digest.hexdigest
-
else
-
96
OpenSSL::Digest.new(@algorithm).hexdigest(value)
-
end
-
end
-
-
6
def hmac(key, value)
-
384
OpenSSL::HMAC.digest(OpenSSL::Digest.new(@algorithm), key, value)
-
end
-
-
6
def hexhmac(key, value)
-
96
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new(@algorithm), key, value)
-
end
-
end
-
-
6
class << self
-
6
def load_dependencies(*)
-
96
require "set"
-
96
require "digest/sha2"
-
96
require "openssl"
-
end
-
-
6
def configure(klass)
-
96
klass.plugin(:expect)
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_sigv4_signer(value)
-
204
value.is_a?(Signer) ? value : Signer.new(value)
-
end
-
end
-
-
6
module InstanceMethods
-
6
def aws_sigv4_authentication(**options)
-
96
with(sigv4_signer: Signer.new(**options))
-
end
-
-
6
def build_request(*, _)
-
96
request = super
-
-
96
return request if request.headers.key?("authorization")
-
-
96
signer = request.options.sigv4_signer
-
-
96
return request unless signer
-
-
96
signer.sign!(request)
-
-
96
request
-
end
-
end
-
-
6
module RequestMethods
-
6
def canonical_path
-
96
path = uri.path.dup
-
96
path << "/" if path.empty?
-
120
path.gsub(%r{[^/]+}) { |part| CGI.escape(part.encode("UTF-8")).gsub("+", "%20").gsub("%7E", "~") }
-
end
-
-
6
def canonical_query
-
120
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
-
120
params.each.with_index.sort do |a, b|
-
48
a, a_offset = a
-
48
b, b_offset = b
-
48
a_name, a_value = a.split("=")
-
48
b_name, b_value = b.split("=")
-
48
if a_name == b_name
-
24
if a_value == b_value
-
12
a_offset <=> b_offset
-
else
-
12
a_value <=> b_value
-
end
-
else
-
24
a_name <=> b_name
-
end
-
end.map(&:first).join("&")
-
end
-
end
-
end
-
6
register_plugin :aws_sigv4, AWSSigV4
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds helper methods to implement HTTP Basic Auth (https://datatracker.ietf.org/doc/html/rfc7617)
-
#
-
# https://gitlab.com/os85/httpx/wikis/Auth#basic-auth
-
#
-
6
module BasicAuth
-
6
class << self
-
6
def load_dependencies(_klass)
-
84
require_relative "auth/basic"
-
end
-
-
6
def configure(klass)
-
84
klass.plugin(:auth)
-
end
-
end
-
-
6
module InstanceMethods
-
6
def basic_auth(user, password)
-
96
authorization(Authentication::Basic.new(user, password).authenticate)
-
end
-
end
-
end
-
6
register_plugin :basic_auth, BasicAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
5
module HTTPX
-
5
module Plugins
-
5
module Brotli
-
5
class Deflater < Transcoder::Deflater
-
5
def deflate(chunk)
-
20
return unless chunk
-
-
10
::Brotli.deflate(chunk)
-
end
-
end
-
-
5
module RequestBodyClassMethods
-
5
def initialize_deflater_body(body, encoding)
-
20
return Brotli.encode(body) if encoding == "br"
-
-
10
super
-
end
-
end
-
-
5
module ResponseBodyClassMethods
-
5
def initialize_inflater_by_encoding(encoding, response, **kwargs)
-
20
return Brotli.decode(response, **kwargs) if encoding == "br"
-
-
10
super
-
end
-
end
-
-
5
module_function
-
-
5
def load_dependencies(*)
-
20
require "brotli"
-
end
-
-
5
def self.extra_options(options)
-
20
options.merge(supported_compression_formats: %w[br] + options.supported_compression_formats)
-
end
-
-
5
def encode(body)
-
10
Deflater.new(body)
-
end
-
-
5
def decode(_response, **)
-
10
::Brotli.method(:inflate)
-
end
-
end
-
5
register_plugin :brotli, Brotli
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Plugins
-
#
-
# This plugin adds suppoort for callbacks around the request/response lifecycle.
-
#
-
# https://gitlab.com/os85/httpx/-/wikis/Events
-
#
-
23
module Callbacks
-
# connection closed user-space errors happen after errors can be surfaced to requests,
-
# so they need to pierce through the scheduler, which is only possible by simulating an
-
# interrupt.
-
23
class CallbackError < Exception; end # rubocop:disable Lint/InheritException
-
-
23
module InstanceMethods
-
23
include HTTPX::Callbacks
-
-
23
%i[
-
connection_opened connection_closed
-
request_error
-
request_started request_body_chunk request_completed
-
response_started response_body_chunk response_completed
-
].each do |meth|
-
207
class_eval(<<-MOD, __FILE__, __LINE__ + 1)
-
9
def on_#{meth}(&blk) # def on_connection_opened(&blk)
-
9
on(:#{meth}, &blk) # on(:connection_opened, &blk)
-
end # end
-
MOD
-
end
-
-
23
private
-
-
23
def init_connection(uri, options)
-
157
connection = super
-
157
connection.on(:open) do
-
147
emit_or_callback_error(:connection_opened, connection.origin, connection.io.socket)
-
end
-
157
connection.on(:close) do
-
147
emit_or_callback_error(:connection_closed, connection.origin) if connection.used?
-
end
-
-
157
connection
-
end
-
-
23
def set_request_callbacks(request)
-
159
super
-
-
159
request.on(:headers) do
-
135
emit_or_callback_error(:request_started, request)
-
end
-
159
request.on(:body_chunk) do |chunk|
-
12
emit_or_callback_error(:request_body_chunk, request, chunk)
-
end
-
159
request.on(:done) do
-
123
emit_or_callback_error(:request_completed, request)
-
end
-
-
159
request.on(:response_started) do |res|
-
123
if res.is_a?(Response)
-
111
emit_or_callback_error(:response_started, request, res)
-
99
res.on(:chunk_received) do |chunk|
-
121
emit_or_callback_error(:response_body_chunk, request, res, chunk)
-
end
-
else
-
12
emit_or_callback_error(:request_error, request, res.error)
-
end
-
end
-
159
request.on(:response) do |res|
-
99
emit_or_callback_error(:response_completed, request, res)
-
end
-
end
-
-
23
def emit_or_callback_error(*args)
-
895
emit(*args)
-
rescue StandardError => e
-
90
ex = CallbackError.new(e.message)
-
90
ex.set_backtrace(e.backtrace)
-
90
raise ex
-
end
-
-
23
def receive_requests(*)
-
159
super
-
rescue CallbackError => e
-
84
raise e.cause
-
end
-
end
-
end
-
23
register_plugin :callbacks, Callbacks
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin implements a circuit breaker around connection errors.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Circuit-Breaker
-
#
-
6
module CircuitBreaker
-
6
using URIExtensions
-
-
6
def self.load_dependencies(*)
-
42
require_relative "circuit_breaker/circuit"
-
42
require_relative "circuit_breaker/circuit_store"
-
end
-
-
6
def self.extra_options(options)
-
42
options.merge(
-
circuit_breaker_max_attempts: 3,
-
circuit_breaker_reset_attempts_in: 60,
-
circuit_breaker_break_in: 60,
-
circuit_breaker_half_open_drip_rate: 1
-
)
-
end
-
-
6
module InstanceMethods
-
6
include HTTPX::Callbacks
-
-
6
def initialize(*)
-
42
super
-
42
@circuit_store = CircuitStore.new(@options)
-
end
-
-
6
def initialize_dup(orig)
-
super
-
@circuit_store = orig.instance_variable_get(:@circuit_store).dup
-
end
-
-
6
%i[circuit_open].each do |meth|
-
6
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
-
-
6
private
-
-
6
def send_requests(*requests)
-
# @type var short_circuit_responses: Array[response]
-
168
short_circuit_responses = []
-
-
# run all requests through the circuit breaker, see if the circuit is
-
# open for any of them.
-
168
real_requests = requests.each_with_index.with_object([]) do |(req, idx), real_reqs|
-
168
short_circuit_response = @circuit_store.try_respond(req)
-
168
if short_circuit_response.nil?
-
132
real_reqs << req
-
132
next
-
end
-
30
short_circuit_responses[idx] = short_circuit_response
-
end
-
-
# run requests for the remainder
-
168
unless real_requests.empty?
-
132
responses = super(*real_requests)
-
-
132
real_requests.each_with_index do |request, idx|
-
110
short_circuit_responses[requests.index(request)] = responses[idx]
-
end
-
end
-
-
168
short_circuit_responses
-
end
-
-
6
def on_response(request, response)
-
132
emit(:circuit_open, request) if try_circuit_open(request, response)
-
-
132
super
-
end
-
-
6
def try_circuit_open(request, response)
-
132
if response.is_a?(ErrorResponse)
-
80
case response.error
-
when RequestTimeoutError
-
60
@circuit_store.try_open(request.uri, response)
-
else
-
36
@circuit_store.try_open(request.origin, response)
-
end
-
36
elsif (break_on = request.options.circuit_breaker_break_on) && break_on.call(response)
-
12
@circuit_store.try_open(request.uri, response)
-
else
-
24
@circuit_store.try_close(request.uri)
-
4
nil
-
end
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_circuit_breaker_max_attempts(value)
-
84
attempts = Integer(value)
-
84
raise TypeError, ":circuit_breaker_max_attempts must be positive" unless attempts.positive?
-
-
84
attempts
-
end
-
-
6
def option_circuit_breaker_reset_attempts_in(value)
-
48
timeout = Float(value)
-
48
raise TypeError, ":circuit_breaker_reset_attempts_in must be positive" unless timeout.positive?
-
-
48
timeout
-
end
-
-
6
def option_circuit_breaker_break_in(value)
-
66
timeout = Float(value)
-
66
raise TypeError, ":circuit_breaker_break_in must be positive" unless timeout.positive?
-
-
66
timeout
-
end
-
-
6
def option_circuit_breaker_half_open_drip_rate(value)
-
66
ratio = Float(value)
-
66
raise TypeError, ":circuit_breaker_half_open_drip_rate must be a number between 0 and 1" unless (0..1).cover?(ratio)
-
-
66
ratio
-
end
-
-
6
def option_circuit_breaker_break_on(value)
-
12
raise TypeError, ":circuit_breaker_break_on must be called with the response" unless value.respond_to?(:call)
-
-
12
value
-
end
-
end
-
end
-
6
register_plugin :circuit_breaker, CircuitBreaker
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins::CircuitBreaker
-
#
-
# A circuit is assigned to a given absoolute url or origin.
-
#
-
# It sets +max_attempts+, the number of attempts the circuit allows, before it is opened.
-
# It sets +reset_attempts_in+, the time a circuit stays open at most, before it resets.
-
# It sets +break_in+, the time that must elapse before an open circuit can transit to the half-open state.
-
# It sets +circuit_breaker_half_open_drip_rate+, the rate of requests a circuit allows to be performed when in an half-open state.
-
#
-
6
class Circuit
-
6
def initialize(max_attempts, reset_attempts_in, break_in, circuit_breaker_half_open_drip_rate)
-
42
@max_attempts = max_attempts
-
42
@reset_attempts_in = reset_attempts_in
-
42
@break_in = break_in
-
42
@circuit_breaker_half_open_drip_rate = circuit_breaker_half_open_drip_rate
-
42
@attempts = 0
-
-
42
total_real_attempts = @max_attempts * @circuit_breaker_half_open_drip_rate
-
42
@drip_factor = (@max_attempts / total_real_attempts).round
-
42
@state = :closed
-
end
-
-
6
def respond
-
168
try_close
-
-
140
case @state
-
when :closed
-
17
nil
-
when :half_open
-
35
@attempts += 1
-
-
# do real requests while drip rate valid
-
42
if (@real_attempts % @drip_factor).zero?
-
25
@real_attempts += 1
-
25
return
-
end
-
-
12
@response
-
when :open
-
-
24
@response
-
end
-
end
-
-
6
def try_open(response)
-
90
case @state
-
when :closed
-
90
now = Utils.now
-
-
90
if @attempts.positive?
-
# reset if error happened long ago
-
36
@attempts = 0 if now - @attempted_at > @reset_attempts_in
-
else
-
54
@attempted_at = now
-
end
-
-
75
@attempts += 1
-
-
90
return unless @attempts >= @max_attempts
-
-
48
@state = :open
-
48
@opened_at = now
-
48
@response = response
-
when :half_open
-
# open immediately
-
-
18
@state = :open
-
18
@attempted_at = @opened_at = Utils.now
-
18
@response = response
-
end
-
end
-
-
6
def try_close
-
160
case @state
-
when :closed
-
17
nil
-
when :half_open
-
-
# do not close circuit unless attempts exhausted
-
36
return unless @attempts >= @max_attempts
-
-
# reset!
-
12
@attempts = 0
-
12
@opened_at = @attempted_at = @response = nil
-
12
@state = :closed
-
-
when :open
-
54
if Utils.elapsed_time(@opened_at) > @break_in
-
30
@state = :half_open
-
30
@attempts = 0
-
30
@real_attempts = 0
-
end
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX::Plugins::CircuitBreaker
-
6
using HTTPX::URIExtensions
-
-
6
class CircuitStore
-
6
def initialize(options)
-
42
@circuits = Hash.new do |h, k|
-
35
h[k] = Circuit.new(
-
options.circuit_breaker_max_attempts,
-
options.circuit_breaker_reset_attempts_in,
-
options.circuit_breaker_break_in,
-
options.circuit_breaker_half_open_drip_rate
-
)
-
end
-
42
@circuits_mutex = Thread::Mutex.new
-
end
-
-
6
def try_open(uri, response)
-
216
circuit = @circuits_mutex.synchronize { get_circuit_for_uri(uri) }
-
-
108
circuit.try_open(response)
-
end
-
-
6
def try_close(uri)
-
24
circuit = @circuits_mutex.synchronize do
-
24
return unless @circuits.key?(uri.origin) || @circuits.key?(uri.to_s)
-
-
24
get_circuit_for_uri(uri)
-
end
-
-
24
circuit.try_close
-
end
-
-
# if circuit is open, it'll respond with the stored response.
-
# if not, nil.
-
6
def try_respond(request)
-
336
circuit = @circuits_mutex.synchronize { get_circuit_for_uri(request.uri) }
-
-
168
circuit.respond
-
end
-
-
6
private
-
-
6
def get_circuit_for_uri(uri)
-
300
if uri.respond_to?(:origin) && @circuits.key?(uri.origin)
-
216
@circuits[uri.origin]
-
else
-
84
@circuits[uri.to_s]
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
require "forwardable"
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin implements a persistent cookie jar for the duration of a session.
-
#
-
# It also adds a *#cookies* helper, so that you can pre-fill the cookies of a session.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Cookies
-
#
-
6
module Cookies
-
6
def self.load_dependencies(*)
-
108
require "httpx/plugins/cookies/jar"
-
108
require "httpx/plugins/cookies/cookie"
-
108
require "httpx/plugins/cookies/set_cookie_parser"
-
end
-
-
6
module InstanceMethods
-
6
extend Forwardable
-
-
6
def_delegator :@options, :cookies
-
-
6
def initialize(options = {}, &blk)
-
216
super({ cookies: Jar.new }.merge(options), &blk)
-
end
-
-
6
def wrap
-
12
return super unless block_given?
-
-
12
super do |session|
-
12
old_cookies_jar = @options.cookies.dup
-
begin
-
12
yield session
-
ensure
-
12
@options = @options.merge(cookies: old_cookies_jar)
-
end
-
end
-
end
-
-
6
private
-
-
6
def on_response(_request, response)
-
240
if response && response.respond_to?(:headers) && (set_cookie = response.headers["set-cookie"])
-
-
48
log { "cookies: set-cookie is over #{Cookie::MAX_LENGTH}" } if set_cookie.bytesize > Cookie::MAX_LENGTH
-
-
48
@options.cookies.parse(set_cookie)
-
end
-
-
240
super
-
end
-
-
6
def build_request(*, _)
-
240
request = super
-
240
request.headers.set_cookie(request.options.cookies[request.uri])
-
240
request
-
end
-
end
-
-
6
module HeadersMethods
-
6
def set_cookie(cookies)
-
240
return if cookies.empty?
-
-
204
header_value = cookies.sort.join("; ")
-
-
204
add("cookie", header_value)
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_headers(*)
-
240
value = super
-
-
240
merge_cookie_in_jar(value.delete("cookie"), @cookies) if defined?(@cookies) && value.key?("cookie")
-
-
240
value
-
end
-
-
6
def option_cookies(value)
-
360
jar = value.is_a?(Jar) ? value : Jar.new(value)
-
-
360
merge_cookie_in_jar(@headers.delete("cookie"), jar) if defined?(@headers) && @headers.key?("cookie")
-
-
360
jar
-
end
-
-
6
private
-
-
6
def merge_cookie_in_jar(cookies, jar)
-
12
cookies.each do |ck|
-
12
ck.split(/ *; */).each do |cookie|
-
24
name, value = cookie.split("=", 2)
-
24
jar.add(Cookie.new(name, value))
-
end
-
end
-
end
-
end
-
end
-
6
register_plugin :cookies, Cookies
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins::Cookies
-
# The HTTP Cookie.
-
#
-
# Contains the single cookie info: name, value and attributes.
-
6
class Cookie
-
6
include Comparable
-
# Maximum number of bytes per cookie (RFC 6265 6.1 requires 4096 at
-
# least)
-
6
MAX_LENGTH = 4096
-
-
6
attr_reader :domain, :path, :name, :value, :created_at
-
-
6
def path=(path)
-
138
path = String(path)
-
138
@path = path.start_with?("/") ? path : "/"
-
end
-
-
# See #domain.
-
6
def domain=(domain)
-
30
domain = String(domain)
-
-
30
if domain.start_with?(".")
-
12
@for_domain = true
-
12
domain = domain[1..-1]
-
end
-
-
30
return if domain.empty?
-
-
30
@domain_name = DomainName.new(domain)
-
# RFC 6265 5.3 5.
-
30
@for_domain = false if @domain_name.domain.nil? # a public suffix or IP address
-
-
30
@domain = @domain_name.hostname
-
end
-
-
# Compares the cookie with another. When there are many cookies with
-
# the same name for a URL, the value of the smallest must be used.
-
6
def <=>(other)
-
# RFC 6265 5.4
-
# Precedence: 1. longer path 2. older creation
-
532
(@name <=> other.name).nonzero? ||
-
43
(other.path.length <=> @path.length).nonzero? ||
-
25
(@created_at <=> other.created_at).nonzero? || 0
-
end
-
-
6
class << self
-
6
def new(cookie, *args)
-
378
return cookie if cookie.is_a?(self)
-
-
378
super
-
end
-
-
# Tests if +target_path+ is under +base_path+ as described in RFC
-
# 6265 5.1.4. +base_path+ must be an absolute path.
-
# +target_path+ may be empty, in which case it is treated as the
-
# root path.
-
#
-
# e.g.
-
#
-
# path_match?('/admin/', '/admin/index') == true
-
# path_match?('/admin/', '/Admin/index') == false
-
# path_match?('/admin/', '/admin/') == true
-
# path_match?('/admin/', '/admin') == false
-
#
-
# path_match?('/admin', '/admin') == true
-
# path_match?('/admin', '/Admin') == false
-
# path_match?('/admin', '/admins') == false
-
# path_match?('/admin', '/admin/') == true
-
# path_match?('/admin', '/admin/index') == true
-
6
def path_match?(base_path, target_path)
-
1014
base_path.start_with?("/") || (return false)
-
# RFC 6265 5.1.4
-
1014
bsize = base_path.size
-
1014
tsize = target_path.size
-
1014
return bsize == 1 if tsize.zero? # treat empty target_path as "/"
-
1014
return false unless target_path.start_with?(base_path)
-
1008
return true if bsize == tsize || base_path.end_with?("/")
-
-
12
target_path[bsize] == "/"
-
end
-
end
-
-
6
def initialize(arg, *attrs)
-
378
@created_at = Time.now
-
-
378
if attrs.empty?
-
18
attr_hash = Hash.try_convert(arg)
-
else
-
360
@name = arg
-
360
@value, attr_hash = attrs
-
360
attr_hash = Hash.try_convert(attr_hash)
-
end
-
-
33
attr_hash.each do |key, val|
-
234
key = key.downcase.tr("-", "_").to_sym unless key.is_a?(Symbol)
-
-
195
case key
-
when :domain, :path
-
168
__send__(:"#{key}=", val)
-
else
-
66
instance_variable_set(:"@#{key}", val)
-
end
-
378
end if attr_hash
-
-
378
@path ||= "/"
-
378
raise ArgumentError, "name must be specified" if @name.nil?
-
-
378
@name = @name.to_s
-
end
-
-
6
def expires
-
570
@expires || (@created_at && @max_age ? @created_at + @max_age : nil)
-
end
-
-
6
def expired?(time = Time.now)
-
546
return false unless expires
-
-
24
expires <= time
-
end
-
-
# Returns a string for use in the Cookie header, i.e. `name=value`
-
# or `name="value"`.
-
6
def cookie_value
-
345
"#{@name}=#{Scanner.quote(@value.to_s)}"
-
end
-
6
alias_method :to_s, :cookie_value
-
-
# Tests if it is OK to send this cookie to a given `uri`. A
-
# RuntimeError is raised if the cookie's domain is unknown.
-
6
def valid_for_uri?(uri)
-
534
uri = URI(uri)
-
# RFC 6265 5.4
-
-
534
return false if @secure && uri.scheme != "https"
-
-
528
acceptable_from_uri?(uri) && Cookie.path_match?(@path, uri.path)
-
end
-
-
6
private
-
-
# Tests if it is OK to accept this cookie if it is sent from a given
-
# URI/URL, `uri`.
-
6
def acceptable_from_uri?(uri)
-
552
uri = URI(uri)
-
-
552
host = DomainName.new(uri.host)
-
-
# RFC 6265 5.3
-
552
if host.hostname == @domain
-
12
true
-
540
elsif @for_domain # !host-only-flag
-
24
host.cookie_domain?(@domain_name)
-
else
-
516
@domain.nil?
-
end
-
end
-
-
6
module Scanner
-
6
RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/.freeze
-
-
6
module_function
-
-
6
def quote(s)
-
414
return s unless s.match(RE_BAD_CHAR)
-
-
6
"\"#{s.gsub(/([\\"])/, "\\\\\\1")}\""
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins::Cookies
-
# The Cookie Jar
-
#
-
# It holds a bunch of cookies.
-
6
class Jar
-
6
using URIExtensions
-
-
6
include Enumerable
-
-
6
def initialize_dup(orig)
-
162
super
-
162
@cookies = orig.instance_variable_get(:@cookies).dup
-
end
-
-
6
def initialize(cookies = nil)
-
402
@cookies = []
-
-
120
cookies.each do |elem|
-
132
cookie = case elem
-
when Cookie
-
12
elem
-
when Array
-
108
Cookie.new(*elem)
-
else
-
12
Cookie.new(elem)
-
end
-
-
132
@cookies << cookie
-
402
end if cookies
-
end
-
-
6
def parse(set_cookie)
-
108
SetCookieParser.call(set_cookie) do |name, value, attrs|
-
156
add(Cookie.new(name, value, attrs))
-
end
-
end
-
-
6
def add(cookie, path = nil)
-
342
c = cookie.dup
-
-
342
c.path = path if path && c.path == "/"
-
-
# If the user agent receives a new cookie with the same cookie-name, domain-value, and path-value
-
# as a cookie that it has already stored, the existing cookie is evicted and replaced with the new cookie.
-
648
@cookies.delete_if { |ck| ck.name == c.name && ck.domain == c.domain && ck.path == c.path }
-
-
342
@cookies << c
-
end
-
-
6
def [](uri)
-
354
each(uri).sort
-
end
-
-
6
def each(uri = nil, &blk)
-
888
return enum_for(__method__, uri) unless blk
-
-
510
return @cookies.each(&blk) unless uri
-
-
354
uri = URI(uri)
-
-
354
now = Time.now
-
354
tpath = uri.path
-
-
354
@cookies.delete_if do |cookie|
-
546
if cookie.expired?(now)
-
12
true
-
else
-
534
yield cookie if cookie.valid_for_uri?(uri) && Cookie.path_match?(cookie.path, tpath)
-
534
false
-
end
-
end
-
end
-
-
6
def merge(other)
-
150
cookies_dup = dup
-
-
150
other.each do |elem|
-
162
cookie = case elem
-
when Cookie
-
150
elem
-
when Array
-
6
Cookie.new(*elem)
-
else
-
6
Cookie.new(elem)
-
end
-
-
162
cookies_dup.add(cookie)
-
end
-
-
150
cookies_dup
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
require "strscan"
-
6
require "time"
-
-
6
module HTTPX
-
6
module Plugins::Cookies
-
6
module SetCookieParser
-
# Whitespace.
-
6
RE_WSP = /[ \t]+/.freeze
-
-
# A pattern that matches a cookie name or attribute name which may
-
# be empty, capturing trailing whitespace.
-
6
RE_NAME = /(?!#{RE_WSP})[^,;\\"=]*/.freeze
-
-
6
RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/.freeze
-
-
# A pattern that matches the comma in a (typically date) value.
-
6
RE_COOKIE_COMMA = /,(?=#{RE_WSP}?#{RE_NAME}=)/.freeze
-
-
6
module_function
-
-
6
def scan_dquoted(scanner)
-
12
s = +""
-
-
18
until scanner.eos?
-
48
break if scanner.skip(/"/)
-
-
36
if scanner.skip(/\\/)
-
12
s << scanner.getch
-
24
elsif scanner.scan(/[^"\\]+/)
-
24
s << scanner.matched
-
end
-
end
-
-
12
s
-
end
-
-
6
def scan_value(scanner, comma_as_separator = false)
-
330
value = +""
-
-
388
until scanner.eos?
-
570
if scanner.scan(/[^,;"]+/)
-
324
value << scanner.matched
-
246
elsif scanner.skip(/"/)
-
# RFC 6265 2.2
-
# A cookie-value may be DQUOTE'd.
-
12
value << scan_dquoted(scanner)
-
234
elsif scanner.check(/;/)
-
174
break
-
60
elsif comma_as_separator && scanner.check(RE_COOKIE_COMMA)
-
48
break
-
else
-
12
value << scanner.getch
-
end
-
end
-
-
330
value.rstrip!
-
330
value
-
end
-
-
6
def scan_name_value(scanner, comma_as_separator = false)
-
330
name = scanner.scan(RE_NAME)
-
330
name.rstrip! if name
-
-
330
if scanner.skip(/=/)
-
324
value = scan_value(scanner, comma_as_separator)
-
else
-
6
scan_value(scanner, comma_as_separator)
-
6
value = nil
-
end
-
330
[name, value]
-
end
-
-
6
def call(set_cookie)
-
108
scanner = StringScanner.new(set_cookie)
-
-
# RFC 6265 4.1.1 & 5.2
-
134
until scanner.eos?
-
156
start = scanner.pos
-
156
len = nil
-
-
156
scanner.skip(RE_WSP)
-
-
156
name, value = scan_name_value(scanner, true)
-
156
value = nil if name.empty?
-
-
156
attrs = {}
-
-
185
until scanner.eos?
-
222
if scanner.skip(/,/)
-
# The comma is used as separator for concatenating multiple
-
# values of a header.
-
48
len = (scanner.pos - 1) - start
-
48
break
-
174
elsif scanner.skip(/;/)
-
174
scanner.skip(RE_WSP)
-
-
174
aname, avalue = scan_name_value(scanner, true)
-
-
174
next if aname.empty? || value.nil?
-
-
174
aname.downcase!
-
-
145
case aname
-
when "expires"
-
# RFC 6265 5.2.1
-
12
(avalue &&= Time.parse(avalue)) || next
-
when "max-age"
-
# RFC 6265 5.2.2
-
6
next unless /\A-?\d+\z/.match?(avalue)
-
-
6
avalue = Integer(avalue)
-
when "domain"
-
# RFC 6265 5.2.3
-
# An empty value SHOULD be ignored.
-
18
next if avalue.nil? || avalue.empty?
-
when "path"
-
# RFC 6265 5.2.4
-
# A relative path must be ignored rather than normalizing it
-
# to "/".
-
132
next unless avalue.start_with?("/")
-
when "secure", "httponly"
-
# RFC 6265 5.2.5, 5.2.6
-
6
avalue = true
-
end
-
145
attrs[aname] = avalue
-
end
-
end
-
-
156
len ||= scanner.pos - start
-
-
156
next if len > Cookie::MAX_LENGTH
-
-
156
yield(name, value, attrs) if name && !name.empty? && value
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds helper methods to implement HTTP Digest Auth (https://datatracker.ietf.org/doc/html/rfc7616)
-
#
-
# https://gitlab.com/os85/httpx/wikis/Auth#digest-auth
-
#
-
6
module DigestAuth
-
6
DigestError = Class.new(Error)
-
-
6
class << self
-
6
def extra_options(options)
-
120
options.merge(max_concurrent_requests: 1)
-
end
-
-
6
def load_dependencies(*)
-
120
require_relative "auth/digest"
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_digest(value)
-
240
raise TypeError, ":digest must be a #{Authentication::Digest}" unless value.is_a?(Authentication::Digest)
-
-
240
value
-
end
-
end
-
-
6
module InstanceMethods
-
6
def digest_auth(user, password, hashed: false)
-
120
with(digest: Authentication::Digest.new(user, password, hashed: hashed))
-
end
-
-
6
private
-
-
6
def send_requests(*requests)
-
144
requests.flat_map do |request|
-
144
digest = request.options.digest
-
-
144
next super(request) unless digest
-
-
240
probe_response = wrap { super(request).first }
-
-
120
return probe_response unless probe_response.is_a?(Response)
-
-
120
if probe_response.status == 401 && digest.can_authenticate?(probe_response.headers["www-authenticate"])
-
108
request.transition(:idle)
-
90
request.headers["authorization"] = digest.authenticate(request, probe_response.headers["www-authenticate"])
-
108
super(request)
-
else
-
12
probe_response
-
end
-
end
-
end
-
end
-
end
-
-
6
register_plugin :digest_auth, DigestAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin makes all HTTP/1.1 requests with a body send the "Expect: 100-continue".
-
#
-
# https://gitlab.com/os85/httpx/wikis/Expect#expect
-
#
-
6
module Expect
-
6
EXPECT_TIMEOUT = 2
-
-
6
class << self
-
6
def no_expect_store
-
124
@no_expect_store ||= []
-
end
-
-
6
def extra_options(options)
-
144
options.merge(expect_timeout: EXPECT_TIMEOUT)
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_expect_timeout(value)
-
252
seconds = Float(value)
-
252
raise TypeError, ":expect_timeout must be positive" unless seconds.positive?
-
-
252
seconds
-
end
-
-
6
def option_expect_threshold_size(value)
-
12
bytes = Integer(value)
-
12
raise TypeError, ":expect_threshold_size must be positive" unless bytes.positive?
-
-
12
bytes
-
end
-
end
-
-
6
module RequestMethods
-
6
def initialize(*)
-
168
super
-
168
return if @body.empty?
-
-
108
threshold = @options.expect_threshold_size
-
108
return if threshold && !@body.unbounded_body? && @body.bytesize < threshold
-
-
96
return if Expect.no_expect_store.include?(origin)
-
-
75
@headers["expect"] = "100-continue"
-
end
-
-
6
def response=(response)
-
132
if response.is_a?(Response) &&
-
response.status == 100 &&
-
!@headers.key?("expect") &&
-
2
(@state == :body || @state == :done)
-
-
# if we're past this point, this means that we just received a 100-Continue response,
-
# but the request doesn't have the expect flag, and is already flushing (or flushed) the body.
-
#
-
# this means that expect was deactivated for this request too soon, i.e. response took longer.
-
#
-
# so we have to reactivate it again.
-
7
@headers["expect"] = "100-continue"
-
8
@informational_status = 100
-
8
Expect.no_expect_store.delete(origin)
-
end
-
132
super
-
end
-
end
-
-
6
module ConnectionMethods
-
6
def send_request_to_parser(request)
-
84
super
-
-
84
return unless request.headers["expect"] == "100-continue"
-
-
60
expect_timeout = request.options.expect_timeout
-
-
60
return if expect_timeout.nil? || expect_timeout.infinite?
-
-
60
set_request_timeout(request, expect_timeout, :expect, %i[body response]) do
-
# expect timeout expired
-
20
if request.state == :expect && !request.expects?
-
20
Expect.no_expect_store << request.origin
-
20
request.headers.delete("expect")
-
20
consume
-
end
-
end
-
end
-
end
-
-
6
module InstanceMethods
-
6
def fetch_response(request, connections, options)
-
316
response = @responses.delete(request)
-
316
return unless response
-
-
84
if response.is_a?(Response) && response.status == 417 && request.headers.key?("expect")
-
12
response.close
-
12
request.headers.delete("expect")
-
12
request.transition(:idle)
-
12
send_request(request, connections, options)
-
10
return
-
end
-
-
72
response
-
end
-
end
-
end
-
6
register_plugin :expect, Expect
-
end
-
end
-
# frozen_string_literal: true
-
-
12
module HTTPX
-
12
InsecureRedirectError = Class.new(Error)
-
12
module Plugins
-
#
-
# This plugin adds support for following redirect (status 30X) responses.
-
#
-
# It has an upper bound of followed redirects (see *MAX_REDIRECTS*), after which it
-
# will return the last redirect response. It will **not** raise an exception.
-
#
-
# It also doesn't follow insecure redirects (https -> http) by default (see *follow_insecure_redirects*).
-
#
-
# https://gitlab.com/os85/httpx/wikis/Follow-Redirects
-
#
-
12
module FollowRedirects
-
12
MAX_REDIRECTS = 3
-
12
REDIRECT_STATUS = (300..399).freeze
-
-
12
using URIExtensions
-
-
12
module OptionsMethods
-
12
def option_max_redirects(value)
-
292
num = Integer(value)
-
292
raise TypeError, ":max_redirects must be positive" if num.negative?
-
-
292
num
-
end
-
-
12
def option_follow_insecure_redirects(value)
-
18
value
-
end
-
-
12
def option_allow_auth_to_other_origins(value)
-
18
value
-
end
-
-
12
def option_redirect_on(value)
-
36
raise TypeError, ":redirect_on must be callable" unless value.respond_to?(:call)
-
-
36
value
-
end
-
end
-
-
12
module InstanceMethods
-
12
def max_redirects(n)
-
36
with(max_redirects: n.to_i)
-
end
-
-
12
private
-
-
12
def fetch_response(request, connections, options)
-
439733
redirect_request = request.redirect_request
-
439733
response = super(redirect_request, connections, options)
-
439733
return unless response
-
-
381
max_redirects = redirect_request.max_redirects
-
-
381
return response unless response.is_a?(Response)
-
381
return response unless REDIRECT_STATUS.include?(response.status) && response.headers.key?("location")
-
249
return response unless max_redirects.positive?
-
-
# build redirect request
-
225
redirect_uri = __get_location_from_response(response)
-
-
225
if options.redirect_on
-
24
redirect_allowed = options.redirect_on.call(redirect_uri)
-
24
return response unless redirect_allowed
-
end
-
-
213
if response.status == 305 && options.respond_to?(:proxy)
-
# The requested resource MUST be accessed through the proxy given by
-
# the Location field. The Location field gives the URI of the proxy.
-
6
retry_options = options.merge(headers: redirect_request.headers,
-
proxy: { uri: redirect_uri },
-
body: redirect_request.body,
-
max_redirects: max_redirects - 1)
-
6
redirect_uri = redirect_request.uri
-
6
options = retry_options
-
else
-
207
redirect_headers = redirect_request_headers(redirect_request.uri, redirect_uri, request.headers, options)
-
-
# redirects are **ALWAYS** GET
-
207
retry_opts = Hash[options].merge(
-
headers: redirect_headers.to_h,
-
body: redirect_request.body,
-
max_redirects: max_redirects - 1
-
)
-
207
retry_options = options.class.new(retry_opts)
-
end
-
-
213
redirect_uri = Utils.to_uri(redirect_uri)
-
-
213
if !options.follow_insecure_redirects &&
-
response.uri.scheme == "https" &&
-
redirect_uri.scheme == "http"
-
6
error = InsecureRedirectError.new(redirect_uri.to_s)
-
6
error.set_backtrace(caller)
-
5
return ErrorResponse.new(request, error, options)
-
end
-
-
207
retry_request = build_request("GET", redirect_uri, retry_options)
-
-
207
request.redirect_request = retry_request
-
-
207
retry_after = response.headers["retry-after"]
-
-
207
if retry_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.
-
#
-
12
retry_after = Utils.parse_retry_after(retry_after)
-
-
12
log { "redirecting after #{retry_after} secs..." }
-
12
pool.after(retry_after) do
-
12
send_request(retry_request, connections, options)
-
end
-
else
-
195
send_request(retry_request, connections, options)
-
end
-
33
nil
-
end
-
-
12
def redirect_request_headers(original_uri, redirect_uri, headers, options)
-
207
return headers if options.allow_auth_to_other_origins
-
-
201
return headers unless headers.key?("authorization")
-
-
12
unless original_uri.origin == redirect_uri.origin
-
6
headers = headers.dup
-
6
headers.delete("authorization")
-
end
-
-
12
headers
-
end
-
-
12
def __get_location_from_response(response)
-
225
location_uri = URI(response.headers["location"])
-
225
location_uri = response.uri.merge(location_uri) if location_uri.relative?
-
225
location_uri
-
end
-
end
-
-
12
module RequestMethods
-
12
attr_accessor :root_request
-
-
12
def redirect_request
-
439733
@redirect_request || self
-
end
-
-
12
def redirect_request=(req)
-
207
@redirect_request = req
-
207
req.root_request = @root_request || self
-
207
@response = nil
-
end
-
-
12
def response
-
1169
return super unless @redirect_request
-
-
10
@redirect_request.response
-
end
-
-
12
def max_redirects
-
381
@options.max_redirects || MAX_REDIRECTS
-
end
-
end
-
end
-
12
register_plugin :follow_redirects, FollowRedirects
-
end
-
end
-
# frozen_string_literal: true
-
-
5
module HTTPX
-
5
GRPCError = Class.new(Error) do
-
5
attr_reader :status, :details, :metadata
-
-
5
def initialize(status, details, metadata)
-
20
@status = status
-
20
@details = details
-
20
@metadata = metadata
-
20
super("GRPC error, code=#{status}, details=#{details}, metadata=#{metadata}")
-
end
-
end
-
-
5
module Plugins
-
#
-
# This plugin adds DSL to build GRPC interfaces.
-
#
-
# https://gitlab.com/os85/httpx/wikis/GRPC
-
#
-
5
module GRPC
-
5
unless String.method_defined?(:underscore)
-
5
module StringExtensions
-
5
refine String do
-
5
def underscore
-
260
s = dup # Avoid mutating the argument, as it might be frozen.
-
260
s.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
-
260
s.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
-
260
s.tr!("-", "_")
-
260
s.downcase!
-
260
s
-
end
-
end
-
end
-
5
using StringExtensions
-
end
-
-
5
DEADLINE = 60
-
5
MARSHAL_METHOD = :encode
-
5
UNMARSHAL_METHOD = :decode
-
5
HEADERS = {
-
"content-type" => "application/grpc",
-
"te" => "trailers",
-
"accept" => "application/grpc",
-
# metadata fits here
-
# ex "foo-bin" => base64("bar")
-
}.freeze
-
-
5
class << self
-
5
def load_dependencies(*)
-
115
require "stringio"
-
115
require "httpx/plugins/grpc/grpc_encoding"
-
115
require "httpx/plugins/grpc/message"
-
115
require "httpx/plugins/grpc/call"
-
end
-
-
5
def configure(klass)
-
115
klass.plugin(:persistent)
-
115
klass.plugin(:stream)
-
end
-
-
5
def extra_options(options)
-
115
options.merge(
-
fallback_protocol: "h2",
-
grpc_rpcs: {}.freeze,
-
grpc_compression: false,
-
grpc_deadline: DEADLINE
-
)
-
end
-
end
-
-
5
module OptionsMethods
-
5
def option_grpc_service(value)
-
100
String(value)
-
end
-
-
5
def option_grpc_compression(value)
-
135
case value
-
when true, false
-
115
value
-
else
-
20
value.to_s
-
end
-
end
-
-
5
def option_grpc_rpcs(value)
-
930
Hash[value]
-
end
-
-
5
def option_grpc_deadline(value)
-
670
raise TypeError, ":grpc_deadline must be positive" unless value.positive?
-
-
670
value
-
end
-
-
5
def option_call_credentials(value)
-
15
raise TypeError, ":call_credentials must respond to #call" unless value.respond_to?(:call)
-
-
15
value
-
end
-
end
-
-
5
module ResponseMethods
-
5
attr_reader :trailing_metadata
-
-
5
def merge_headers(trailers)
-
95
@trailing_metadata = Hash[trailers]
-
95
super
-
end
-
end
-
-
5
module RequestBodyMethods
-
5
def initialize(headers, _)
-
105
super
-
-
105
if (compression = headers["grpc-encoding"])
-
10
deflater_body = self.class.initialize_deflater_body(@body, compression)
-
10
@body = Transcoder::GRPCEncoding.encode(deflater_body || @body, compressed: !deflater_body.nil?)
-
else
-
95
@body = Transcoder::GRPCEncoding.encode(@body, compressed: false)
-
end
-
end
-
end
-
-
5
module InstanceMethods
-
5
def with_channel_credentials(ca_path, key = nil, cert = nil, **ssl_opts)
-
60
ssl_params = {
-
**ssl_opts,
-
ca_file: ca_path,
-
}
-
60
if key
-
60
key = File.read(key) if File.file?(key)
-
60
ssl_params[:key] = OpenSSL::PKey.read(key)
-
end
-
-
60
if cert
-
60
cert = File.read(cert) if File.file?(cert)
-
60
ssl_params[:cert] = OpenSSL::X509::Certificate.new(cert)
-
end
-
-
60
with(ssl: ssl_params)
-
end
-
-
5
def rpc(rpc_name, input, output, **opts)
-
260
rpc_name = rpc_name.to_s
-
260
raise Error, "rpc #{rpc_name} already defined" if @options.grpc_rpcs.key?(rpc_name)
-
-
rpc_opts = {
-
260
deadline: @options.grpc_deadline,
-
}.merge(opts)
-
-
260
local_rpc_name = rpc_name.underscore
-
-
260
session_class = Class.new(self.class) do
-
# define rpc method with ruby style name
-
260
class_eval(<<-OUT, __FILE__, __LINE__ + 1)
-
def #{local_rpc_name}(input, **opts) # def grpc_action(input, **opts)
-
rpc_execute("#{local_rpc_name}", input, **opts) # rpc_execute("grpc_action", input, **opts)
-
end # end
-
OUT
-
-
# define rpc method with original name
-
260
unless local_rpc_name == rpc_name
-
10
class_eval(<<-OUT, __FILE__, __LINE__ + 1)
-
def #{rpc_name}(input, **opts) # def grpcAction(input, **opts)
-
rpc_execute("#{local_rpc_name}", input, **opts) # rpc_execute("grpc_action", input, **opts)
-
end # end
-
OUT
-
end
-
end
-
-
260
session_class.new(@options.merge(
-
grpc_rpcs: @options.grpc_rpcs.merge(
-
local_rpc_name => [rpc_name, input, output, rpc_opts]
-
).freeze
-
))
-
end
-
-
5
def build_stub(origin, service: nil, compression: false)
-
115
scheme = @options.ssl.empty? ? "http" : "https"
-
-
115
origin = URI.parse("#{scheme}://#{origin}")
-
-
115
session = self
-
-
115
if service && service.respond_to?(:rpc_descs)
-
# it's a grpc generic service
-
50
service.rpc_descs.each do |rpc_name, rpc_desc|
-
rpc_opts = {
-
250
marshal_method: rpc_desc.marshal_method,
-
unmarshal_method: rpc_desc.unmarshal_method,
-
}
-
-
250
input = rpc_desc.input
-
250
input = input.type if input.respond_to?(:type)
-
-
250
output = rpc_desc.output
-
250
if output.respond_to?(:type)
-
100
rpc_opts[:stream] = true
-
100
output = output.type
-
end
-
-
250
session = session.rpc(rpc_name, input, output, **rpc_opts)
-
end
-
-
50
service = service.service_name
-
end
-
-
115
session.with(origin: origin, grpc_service: service, grpc_compression: compression)
-
end
-
-
5
def execute(rpc_method, input,
-
deadline: DEADLINE,
-
metadata: nil,
-
**opts)
-
105
grpc_request = build_grpc_request(rpc_method, input, deadline: deadline, metadata: metadata, **opts)
-
105
response = request(grpc_request, **opts)
-
105
response.raise_for_status unless opts[:stream]
-
95
GRPC::Call.new(response)
-
end
-
-
5
private
-
-
5
def rpc_execute(rpc_name, input, **opts)
-
50
rpc_name, input_enc, output_enc, rpc_opts = @options.grpc_rpcs[rpc_name]
-
-
50
exec_opts = rpc_opts.merge(opts)
-
-
50
marshal_method ||= exec_opts.delete(:marshal_method) || MARSHAL_METHOD
-
50
unmarshal_method ||= exec_opts.delete(:unmarshal_method) || UNMARSHAL_METHOD
-
-
50
messages = if input.respond_to?(:each)
-
20
Enumerator.new do |y|
-
20
input.each do |message|
-
40
y << input_enc.__send__(marshal_method, message)
-
end
-
end
-
else
-
30
input_enc.__send__(marshal_method, input)
-
end
-
-
50
call = execute(rpc_name, messages, **exec_opts)
-
-
50
call.decoder = output_enc.method(unmarshal_method)
-
-
50
call
-
end
-
-
5
def build_grpc_request(rpc_method, input, deadline:, metadata: nil, **)
-
105
uri = @options.origin.dup
-
105
rpc_method = "/#{rpc_method}" unless rpc_method.start_with?("/")
-
105
rpc_method = "/#{@options.grpc_service}#{rpc_method}" if @options.grpc_service
-
105
uri.path = rpc_method
-
-
105
headers = HEADERS.merge(
-
"grpc-accept-encoding" => ["identity", *@options.supported_compression_formats]
-
)
-
105
unless deadline == Float::INFINITY
-
# convert to milliseconds
-
105
deadline = (deadline * 1000.0).to_i
-
105
headers["grpc-timeout"] = "#{deadline}m"
-
end
-
-
105
headers = headers.merge(metadata.transform_keys(&:to_s)) if metadata
-
-
# prepare compressor
-
105
compression = @options.grpc_compression == true ? "gzip" : @options.grpc_compression
-
-
105
headers["grpc-encoding"] = compression if compression
-
-
105
headers.merge!(@options.call_credentials.call.transform_keys(&:to_s)) if @options.call_credentials
-
-
105
build_request("POST", uri, headers: headers, body: input)
-
end
-
end
-
end
-
5
register_plugin :grpc, GRPC
-
end
-
end
-
# frozen_string_literal: true
-
-
5
module HTTPX
-
5
module Plugins
-
5
module GRPC
-
# Encapsulates call information
-
5
class Call
-
5
attr_writer :decoder
-
-
5
def initialize(response)
-
95
@response = response
-
130
@decoder = ->(z) { z }
-
95
@consumed = false
-
95
@grpc_response = nil
-
end
-
-
5
def inspect
-
"#GRPC::Call(#{grpc_response})"
-
end
-
-
5
def to_s
-
55
grpc_response.to_s
-
end
-
-
5
def metadata
-
response.headers
-
end
-
-
5
def trailing_metadata
-
60
return unless @consumed
-
-
40
@response.trailing_metadata
-
end
-
-
5
private
-
-
5
def grpc_response
-
155
@grpc_response ||= if @response.respond_to?(:each)
-
20
Enumerator.new do |y|
-
20
Message.stream(@response).each do |message|
-
40
y << @decoder.call(message)
-
end
-
20
@consumed = true
-
end
-
else
-
75
@consumed = true
-
75
@decoder.call(Message.unary(@response))
-
end
-
end
-
-
5
def respond_to_missing?(meth, *args, &blk)
-
20
grpc_response.respond_to?(meth, *args) || super
-
end
-
-
5
def method_missing(meth, *args, &blk)
-
40
return grpc_response.__send__(meth, *args, &blk) if grpc_response.respond_to?(meth)
-
-
super
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
5
module HTTPX
-
5
module Transcoder
-
5
module GRPCEncoding
-
5
class Deflater
-
5
extend Forwardable
-
-
5
attr_reader :content_type
-
-
5
def initialize(body, compressed:)
-
105
@content_type = body.content_type
-
105
@body = BodyReader.new(body)
-
105
@compressed = compressed
-
end
-
-
5
def bytesize
-
335
return @body.bytesize if @body.respond_to?(:bytesize)
-
-
Float::INFINITY
-
end
-
-
5
def read(length = nil, outbuf = nil)
-
220
buf = @body.read(length, outbuf)
-
-
210
return unless buf
-
-
115
compressed_flag = @compressed ? 1 : 0
-
-
115
buf = outbuf if outbuf
-
-
115
buf.prepend([compressed_flag, buf.bytesize].pack("CL>"))
-
115
buf
-
end
-
end
-
-
5
class Inflater
-
5
def initialize(response)
-
75
@response = response
-
75
@grpc_encodings = nil
-
end
-
-
5
def call(message, &blk)
-
95
data = "".b
-
-
95
until message.empty?
-
95
compressed, size = message.unpack("CL>")
-
-
95
encoded_data = message.byteslice(5..size + 5 - 1)
-
-
95
if compressed == 1
-
10
grpc_encodings.reverse_each do |encoding|
-
10
decoder = @response.body.class.initialize_inflater_by_encoding(encoding, @response, bytesize: encoded_data.bytesize)
-
10
encoded_data = decoder.call(encoded_data)
-
-
10
blk.call(encoded_data) if blk
-
-
10
data << encoded_data
-
end
-
else
-
85
blk.call(encoded_data) if blk
-
-
85
data << encoded_data
-
end
-
-
95
message = message.byteslice((size + 5)..-1)
-
end
-
-
95
data
-
end
-
-
5
private
-
-
5
def grpc_encodings
-
10
@grpc_encodings ||= @response.headers.get("grpc-encoding")
-
end
-
end
-
-
5
def self.encode(*args, **kwargs)
-
105
Deflater.new(*args, **kwargs)
-
end
-
-
5
def self.decode(response)
-
75
Inflater.new(response)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
5
module HTTPX
-
5
module Plugins
-
5
module GRPC
-
# Encoding module for GRPC responses
-
#
-
# Can encode and decode grpc messages.
-
5
module Message
-
5
module_function
-
-
# decodes a unary grpc response
-
5
def unary(response)
-
75
verify_status(response)
-
-
55
decoder = Transcoder::GRPCEncoding.decode(response)
-
-
55
decoder.call(response.to_s)
-
end
-
-
# lazy decodes a grpc stream response
-
5
def stream(response, &block)
-
40
return enum_for(__method__, response) unless block
-
-
20
decoder = Transcoder::GRPCEncoding.decode(response)
-
-
20
response.each do |frame|
-
40
decoder.call(frame, &block)
-
end
-
-
20
verify_status(response)
-
end
-
-
5
def cancel(request)
-
request.emit(:refuse, :client_cancellation)
-
end
-
-
# interprets the grpc call trailing metadata, and raises an
-
# exception in case of error code
-
5
def verify_status(response)
-
# return standard errors if need be
-
95
response.raise_for_status
-
-
95
status = Integer(response.headers["grpc-status"])
-
95
message = response.headers["grpc-message"]
-
-
95
return if status.zero?
-
-
20
response.close
-
20
raise GRPCError.new(status, message, response.trailing_metadata)
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds support for upgrading a plaintext HTTP/1.1 connection to HTTP/2
-
# (https://datatracker.ietf.org/doc/html/rfc7540#section-3.2)
-
#
-
# https://gitlab.com/os85/httpx/wikis/Connection-Upgrade#h2c
-
#
-
6
module H2C
-
6
VALID_H2C_VERBS = %w[GET OPTIONS HEAD].freeze
-
-
6
class << self
-
6
def load_dependencies(klass)
-
12
klass.plugin(:upgrade)
-
end
-
-
6
def call(connection, request, response)
-
12
connection.upgrade_to_h2c(request, response)
-
end
-
-
6
def extra_options(options)
-
12
options.merge(max_concurrent_requests: 1, upgrade_handlers: options.upgrade_handlers.merge("h2c" => self))
-
end
-
end
-
-
6
module InstanceMethods
-
6
def send_requests(*requests)
-
18
upgrade_request, *remainder = requests
-
-
18
return super unless VALID_H2C_VERBS.include?(upgrade_request.verb) && upgrade_request.scheme == "http"
-
-
18
connection = pool.find_connection(upgrade_request.uri, upgrade_request.options)
-
-
18
return super if connection && connection.upgrade_protocol == "h2c"
-
-
# build upgrade request
-
12
upgrade_request.headers.add("connection", "upgrade")
-
12
upgrade_request.headers.add("connection", "http2-settings")
-
10
upgrade_request.headers["upgrade"] = "h2c"
-
10
upgrade_request.headers["http2-settings"] = HTTP2Next::Client.settings_header(upgrade_request.options.http2_settings)
-
-
12
super(upgrade_request, *remainder)
-
end
-
end
-
-
6
class H2CParser < Connection::HTTP2
-
6
def upgrade(request, response)
-
# skip checks, it is assumed that this is the first
-
# request in the connection
-
12
stream = @connection.upgrade
-
-
# on_settings
-
12
handle_stream(stream, request)
-
10
@streams[request] = stream
-
-
# clean up data left behind in the buffer, if the server started
-
# sending frames
-
12
data = response.read
-
12
@connection << data
-
end
-
end
-
-
6
module ConnectionMethods
-
6
using URIExtensions
-
-
6
def upgrade_to_h2c(request, response)
-
12
prev_parser = @parser
-
-
12
if prev_parser
-
12
prev_parser.reset
-
10
@inflight -= prev_parser.requests.size
-
end
-
-
12
@parser = H2CParser.new(@write_buffer, @options)
-
12
set_parser_callbacks(@parser)
-
10
@inflight += 1
-
12
@parser.upgrade(request, response)
-
12
@upgrade_protocol = "h2c"
-
-
12
prev_parser.requests.each do |req|
-
12
req.transition(:idle)
-
12
send(req)
-
end
-
end
-
-
6
private
-
-
6
def send_request_to_parser(request)
-
42
super
-
-
42
return unless request.headers["upgrade"] == "h2c" && parser.is_a?(Connection::HTTP1)
-
-
12
max_concurrent_requests = parser.max_concurrent_requests
-
-
12
return if max_concurrent_requests == 1
-
-
parser.max_concurrent_requests = 1
-
request.once(:response) do
-
parser.max_concurrent_requests = max_concurrent_requests
-
end
-
end
-
end
-
end
-
6
register_plugin(:h2c, H2C)
-
end
-
end
-
# frozen_string_literal: true
-
-
5
module HTTPX
-
5
module Plugins
-
#
-
# https://gitlab.com/os85/httpx/wikis/Auth#ntlm-auth
-
#
-
5
module NTLMAuth
-
5
class << self
-
5
def load_dependencies(_klass)
-
2
require_relative "auth/ntlm"
-
end
-
-
5
def extra_options(options)
-
2
options.merge(max_concurrent_requests: 1)
-
end
-
end
-
-
5
module OptionsMethods
-
5
def option_ntlm(value)
-
8
raise TypeError, ":ntlm must be a #{Authentication::Ntlm}" unless value.is_a?(Authentication::Ntlm)
-
-
8
value
-
end
-
end
-
-
5
module InstanceMethods
-
5
def ntlm_auth(user, password, domain = nil)
-
4
with(ntlm: Authentication::Ntlm.new(user, password, domain: domain))
-
end
-
-
5
private
-
-
5
def send_requests(*requests)
-
8
requests.flat_map do |request|
-
8
ntlm = request.options.ntlm
-
-
8
if ntlm
-
4
request.headers["authorization"] = ntlm.negotiate
-
8
probe_response = wrap { super(request).first }
-
-
4
return probe_response unless probe_response.is_a?(Response)
-
-
4
if probe_response.status == 401 && ntlm.can_authenticate?(probe_response.headers["www-authenticate"])
-
2
request.transition(:idle)
-
2
request.headers["authorization"] = ntlm.authenticate(request, probe_response.headers["www-authenticate"])
-
2
super(request)
-
else
-
2
probe_response
-
end
-
else
-
4
super(request)
-
end
-
end
-
end
-
end
-
end
-
5
register_plugin :ntlm_auth, NTLMAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# https://gitlab.com/os85/httpx/wikis/OAuth
-
#
-
6
module OAuth
-
6
class << self
-
6
def load_dependencies(_klass)
-
60
require_relative "auth/basic"
-
end
-
end
-
-
6
SUPPORTED_GRANT_TYPES = %w[client_credentials refresh_token].freeze
-
6
SUPPORTED_AUTH_METHODS = %w[client_secret_basic client_secret_post].freeze
-
-
6
class OAuthSession
-
6
attr_reader :grant_type, :client_id, :client_secret, :access_token, :refresh_token, :scope
-
-
6
def initialize(
-
issuer:,
-
client_id:,
-
client_secret:,
-
access_token: nil,
-
refresh_token: nil,
-
scope: nil,
-
token_endpoint: nil,
-
response_type: nil,
-
grant_type: nil,
-
token_endpoint_auth_method: nil
-
)
-
60
@issuer = URI(issuer)
-
60
@client_id = client_id
-
60
@client_secret = client_secret
-
60
@token_endpoint = URI(token_endpoint) if token_endpoint
-
60
@response_type = response_type
-
60
@scope = case scope
-
when String
-
24
scope.split
-
when Array
-
24
scope
-
end
-
60
@access_token = access_token
-
60
@refresh_token = refresh_token
-
60
@token_endpoint_auth_method = String(token_endpoint_auth_method) if token_endpoint_auth_method
-
60
@grant_type = grant_type || (@refresh_token ? "refresh_token" : "client_credentials")
-
-
60
unless @token_endpoint_auth_method.nil? || SUPPORTED_AUTH_METHODS.include?(@token_endpoint_auth_method)
-
12
raise Error, "#{@token_endpoint_auth_method} is not a supported auth method"
-
end
-
-
48
return if SUPPORTED_GRANT_TYPES.include?(@grant_type)
-
-
raise Error, "#{@grant_type} is not a supported grant type"
-
end
-
-
6
def token_endpoint
-
48
@token_endpoint || "#{@issuer}/token"
-
end
-
-
6
def token_endpoint_auth_method
-
72
@token_endpoint_auth_method || "client_secret_basic"
-
end
-
-
6
def load(http)
-
24
return if @grant_type && @scope
-
-
metadata = http.get("#{@issuer}/.well-known/oauth-authorization-server").raise_for_status.json
-
-
@token_endpoint = metadata["token_endpoint"]
-
@scope = metadata["scopes_supported"]
-
@grant_type = Array(metadata["grant_types_supported"]).find { |gr| SUPPORTED_GRANT_TYPES.include?(gr) }
-
@token_endpoint_auth_method = Array(metadata["token_endpoint_auth_methods_supported"]).find do |am|
-
SUPPORTED_AUTH_METHODS.include?(am)
-
end
-
nil
-
end
-
-
6
def merge(other)
-
48
obj = dup
-
-
40
case other
-
when OAuthSession
-
24
other.instance_variables.each do |ivar|
-
204
val = other.instance_variable_get(ivar)
-
204
next unless val
-
-
156
obj.instance_variable_set(ivar, val)
-
end
-
when Hash
-
24
other.each do |k, v|
-
48
obj.instance_variable_set(:"@#{k}", v) if obj.instance_variable_defined?(:"@#{k}")
-
end
-
end
-
48
obj
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_oauth_session(value)
-
120
case value
-
when Hash
-
OAuthSession.new(**value)
-
when OAuthSession
-
144
value
-
else
-
raise TypeError, ":oauth_session must be a #{OAuthSession}"
-
end
-
end
-
end
-
-
6
module InstanceMethods
-
6
def oauth_auth(**args)
-
60
with(oauth_session: OAuthSession.new(**args))
-
end
-
-
6
def with_access_token
-
24
oauth_session = @options.oauth_session
-
-
24
oauth_session.load(self)
-
-
24
grant_type = oauth_session.grant_type
-
-
24
headers = {}
-
24
form_post = { "grant_type" => grant_type, "scope" => Array(oauth_session.scope).join(" ") }.compact
-
-
# auth
-
20
case oauth_session.token_endpoint_auth_method
-
when "client_secret_post"
-
10
form_post["client_id"] = oauth_session.client_id
-
10
form_post["client_secret"] = oauth_session.client_secret
-
when "client_secret_basic"
-
10
headers["authorization"] = Authentication::Basic.new(oauth_session.client_id, oauth_session.client_secret).authenticate
-
end
-
-
20
case grant_type
-
when "client_credentials"
-
# do nothing
-
when "refresh_token"
-
10
form_post["refresh_token"] = oauth_session.refresh_token
-
end
-
-
24
token_request = build_request("POST", oauth_session.token_endpoint, headers: headers, form: form_post)
-
24
token_request.headers.delete("authorization") unless oauth_session.token_endpoint_auth_method == "client_secret_basic"
-
-
24
token_response = request(token_request)
-
24
token_response.raise_for_status
-
-
24
payload = token_response.json
-
-
24
access_token = payload["access_token"]
-
24
refresh_token = payload["refresh_token"]
-
-
24
with(oauth_session: oauth_session.merge(access_token: access_token, refresh_token: refresh_token))
-
end
-
-
6
def build_request(*, _)
-
72
request = super
-
-
72
return request if request.headers.key?("authorization")
-
-
60
oauth_session = @options.oauth_session
-
-
60
return request unless oauth_session && oauth_session.access_token
-
-
40
request.headers["authorization"] = "Bearer #{oauth_session.access_token}"
-
-
48
request
-
end
-
end
-
end
-
6
register_plugin :oauth, OAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
module Plugins
-
# This plugin implements a session that persists connections over the duration of the process.
-
#
-
# This will improve connection reuse in a long-running process.
-
#
-
# One important caveat to note is, although this session might not close connections,
-
# other sessions from the same process that don't have this plugin turned on might.
-
#
-
# This session will still be able to work with it, as if, when expecting a connection
-
# terminated by a different session, it will just retry on a new one and keep it open.
-
#
-
# This plugin is also not recommendable when connecting to >9000 (like, a lot) different origins.
-
# So when you use this, make sure that you don't fall into this trap.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Persistent
-
#
-
8
module Persistent
-
8
def self.load_dependencies(klass)
-
321
max_retries = if klass.default_options.respond_to?(:max_retries)
-
6
[klass.default_options.max_retries, 1].max
-
else
-
315
1
-
end
-
321
klass.plugin(:retries, max_retries: max_retries, retry_change_requests: true)
-
end
-
-
8
def self.extra_options(options)
-
321
options.merge(persistent: true)
-
end
-
end
-
8
register_plugin :persistent, Persistent
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
class HTTPProxyError < ConnectionError; end
-
-
8
module Plugins
-
#
-
# This plugin adds support for proxies. It ships with support for:
-
#
-
# * HTTP proxies
-
# * HTTPS proxies
-
# * Socks4/4a proxies
-
# * Socks5 proxies
-
#
-
# https://gitlab.com/os85/httpx/wikis/Proxy
-
#
-
8
module Proxy
-
8
Error = HTTPProxyError
-
8
PROXY_ERRORS = [TimeoutError, IOError, SystemCallError, Error].freeze
-
-
8
class << self
-
8
def configure(klass)
-
253
klass.plugin(:"proxy/http")
-
253
klass.plugin(:"proxy/socks4")
-
253
klass.plugin(:"proxy/socks5")
-
end
-
-
8
def extra_options(options)
-
253
options.merge(supported_proxy_protocols: [])
-
end
-
end
-
-
8
class Parameters
-
8
attr_reader :uri, :username, :password, :scheme
-
-
8
def initialize(uri:, scheme: nil, username: nil, password: nil, **extra)
-
326
@uri = uri.is_a?(URI::Generic) ? uri : URI(uri)
-
326
@username = username || @uri.user
-
326
@password = password || @uri.password
-
-
326
return unless @username && @password
-
-
193
scheme ||= case @uri.scheme
-
when "socks5"
-
36
@uri.scheme
-
when "http", "https"
-
97
"basic"
-
else
-
36
return
-
end
-
-
157
@scheme = scheme
-
-
157
auth_scheme = scheme.to_s.capitalize
-
-
157
require_relative "auth/#{scheme}" unless defined?(Authentication) && Authentication.const_defined?(auth_scheme, false)
-
-
157
@authenticator = Authentication.const_get(auth_scheme).new(@username, @password, **extra)
-
end
-
-
8
def can_authenticate?(*args)
-
138
return false unless @authenticator
-
-
48
@authenticator.can_authenticate?(*args)
-
end
-
-
8
def authenticate(*args)
-
121
return unless @authenticator
-
-
121
@authenticator.authenticate(*args)
-
end
-
-
8
def ==(other)
-
61
case other
-
when Parameters
-
47
@uri == other.uri &&
-
@username == other.username &&
-
@password == other.password &&
-
@scheme == other.scheme
-
when URI::Generic, String
-
18
proxy_uri = @uri.dup
-
18
proxy_uri.user = @username
-
18
proxy_uri.password = @password
-
18
other_uri = other.is_a?(URI::Generic) ? other : URI.parse(other)
-
18
proxy_uri == other_uri
-
else
-
6
super
-
end
-
end
-
end
-
-
8
module OptionsMethods
-
8
def option_proxy(value)
-
805
value.is_a?(Parameters) ? value : Hash[value]
-
end
-
-
8
def option_supported_proxy_protocols(value)
-
1277
raise TypeError, ":supported_proxy_protocols must be an Array" unless value.is_a?(Array)
-
-
1277
value.map(&:to_s)
-
end
-
end
-
-
8
module InstanceMethods
-
8
private
-
-
8
def find_connection(request, connections, options)
-
333
return super unless options.respond_to?(:proxy)
-
-
333
uri = URI(request.uri)
-
-
333
proxy_opts = if (next_proxy = uri.find_proxy)
-
4
{ uri: next_proxy }
-
else
-
329
proxy = options.proxy
-
-
329
return super unless proxy
-
-
322
return super(request, connections, options.merge(proxy: nil)) unless proxy.key?(:uri)
-
-
322
@_proxy_uris ||= Array(proxy[:uri])
-
-
322
next_proxy = @_proxy_uris.first
-
322
raise Error, "Failed to connect to proxy" unless next_proxy
-
-
310
next_proxy = URI(next_proxy)
-
-
1
raise Error,
-
310
"#{next_proxy.scheme}: unsupported proxy protocol" unless options.supported_proxy_protocols.include?(next_proxy.scheme)
-
-
304
if proxy.key?(:no_proxy)
-
-
12
no_proxy = proxy[:no_proxy]
-
12
no_proxy = no_proxy.join(",") if no_proxy.is_a?(Array)
-
-
12
return super(request, connections, options.merge(proxy: nil)) unless URI::Generic.use_proxy?(uri.host, next_proxy.host,
-
next_proxy.port, no_proxy)
-
end
-
-
298
proxy.merge(uri: next_proxy)
-
end
-
-
302
proxy = Parameters.new(**proxy_opts)
-
-
302
proxy_options = options.merge(proxy: proxy)
-
302
connection = pool.find_connection(uri, proxy_options) || init_connection(uri, proxy_options)
-
302
unless connections.nil? || connections.include?(connection)
-
283
connections << connection
-
283
set_connection_callbacks(connection, connections, options)
-
end
-
302
connection
-
end
-
-
8
def fetch_response(request, connections, options)
-
1117
response = super
-
-
1117
if response.is_a?(ErrorResponse) && proxy_error?(request, response)
-
72
@_proxy_uris.shift
-
-
# return last error response if no more proxies to try
-
72
return response if @_proxy_uris.empty?
-
-
12
log { "failed connecting to proxy, trying next..." }
-
12
request.transition(:idle)
-
12
send_request(request, connections, options)
-
10
return
-
end
-
1045
response
-
end
-
-
8
def proxy_error?(_request, response)
-
108
error = response.error
-
90
case error
-
when NativeResolveError
-
12
return false unless @_proxy_uris && !@_proxy_uris.empty?
-
-
12
proxy_uri = URI(@_proxy_uris.first)
-
-
12
origin = error.connection.origin
-
-
# failed resolving proxy domain
-
12
origin.host == proxy_uri.host && origin.port == proxy_uri.port
-
when ResolveError
-
return false unless @_proxy_uris && !@_proxy_uris.empty?
-
-
proxy_uri = URI(@_proxy_uris.first)
-
-
error.message.end_with?(proxy_uri.to_s)
-
when *PROXY_ERRORS
-
# timeout errors connecting to proxy
-
96
true
-
else
-
false
-
end
-
end
-
end
-
-
8
module ConnectionMethods
-
8
using URIExtensions
-
-
8
def initialize(*)
-
296
super
-
296
return unless @options.proxy
-
-
# redefining the connection origin as the proxy's URI,
-
# as this will be used as the tcp peer ip.
-
283
proxy_uri = URI(@options.proxy.uri)
-
283
@origin.host = proxy_uri.host
-
283
@origin.port = proxy_uri.port
-
end
-
-
8
def coalescable?(connection)
-
10
return super unless @options.proxy
-
-
10
if @io.protocol == "h2" &&
-
@origin.scheme == "https" &&
-
connection.origin.scheme == "https" &&
-
@io.can_verify_peer?
-
# in proxied connections, .origin is the proxy ; Given names
-
# are stored in .origins, this is what is used.
-
5
origin = URI(connection.origins.first)
-
5
@io.verify_hostname(origin.host)
-
else
-
5
@origin == connection.origin
-
end
-
end
-
-
8
def connecting?
-
435310
return super unless @options.proxy
-
-
435189
super || @state == :connecting || @state == :connected
-
end
-
-
8
def call
-
786
super
-
-
786
return unless @options.proxy
-
-
655
case @state
-
when :connecting
-
175
consume
-
end
-
end
-
-
8
def reset
-
393
return super unless @options.proxy
-
-
367
@state = :open
-
-
367
super
-
367
emit(:close)
-
end
-
-
8
private
-
-
8
def initialize_type(uri, options)
-
296
return super unless options.proxy
-
-
283
"tcp"
-
end
-
-
8
def connect
-
832
return super unless @options.proxy
-
-
680
case @state
-
when :idle
-
562
transition(:connecting)
-
when :connected
-
244
transition(:open)
-
end
-
end
-
-
8
def handle_transition(nextstate)
-
1902
return super unless @options.proxy
-
-
1552
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
-
417
@state = :open if @state == :connecting
-
end
-
1836
super
-
end
-
end
-
end
-
8
register_plugin :proxy, Proxy
-
end
-
-
8
class ProxySSL < SSL
-
8
def initialize(tcp, request_uri, options)
-
68
@io = tcp.to_io
-
68
super(request_uri, tcp.addresses, options)
-
68
@hostname = request_uri.host
-
68
@state = :connected
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
module Plugins
-
8
module Proxy
-
8
module HTTP
-
8
class << self
-
8
def extra_options(options)
-
253
options.merge(supported_proxy_protocols: options.supported_proxy_protocols + %w[http])
-
end
-
end
-
-
8
module InstanceMethods
-
8
def with_proxy_basic_auth(opts)
-
6
with(proxy: opts.merge(scheme: "basic"))
-
end
-
-
8
def with_proxy_digest_auth(opts)
-
18
with(proxy: opts.merge(scheme: "digest"))
-
end
-
-
8
def with_proxy_ntlm_auth(opts)
-
6
with(proxy: opts.merge(scheme: "ntlm"))
-
end
-
-
8
def fetch_response(request, connections, options)
-
1117
response = super
-
-
1117
if response &&
-
response.is_a?(Response) &&
-
response.status == 407 &&
-
!request.headers.key?("proxy-authorization") &&
-
response.headers.key?("proxy-authenticate")
-
-
18
connection = find_connection(request, connections, options)
-
-
18
if connection.options.proxy.can_authenticate?(response.headers["proxy-authenticate"])
-
6
request.transition(:idle)
-
5
request.headers["proxy-authorization"] =
-
connection.options.proxy.authenticate(request, response.headers["proxy-authenticate"])
-
6
send_request(request, connections)
-
6
return
-
end
-
end
-
-
1111
response
-
end
-
end
-
-
8
module ConnectionMethods
-
8
def connecting?
-
435310
super || @state == :connecting || @state == :connected
-
end
-
-
8
private
-
-
8
def handle_transition(nextstate)
-
2108
return super unless @options.proxy && @options.proxy.uri.scheme == "http"
-
-
972
case nextstate
-
when :connecting
-
256
return unless @state == :idle
-
-
256
@io.connect
-
256
return unless @io.connected?
-
-
128
@parser || begin
-
122
@parser = self.class.parser_type(@io.protocol).new(@write_buffer, @options.merge(max_concurrent_requests: 1))
-
122
parser = @parser
-
122
parser.extend(ProxyParser)
-
122
parser.on(:response, &method(:__http_on_connect))
-
166
parser.on(:close) { transition(:closing) }
-
122
parser.on(:reset) do
-
12
if parser.empty?
-
6
reset
-
else
-
6
transition(:closing)
-
6
transition(:closed)
-
-
6
parser.reset if @parser
-
6
transition(:idle)
-
6
transition(:connecting)
-
end
-
end
-
122
__http_proxy_connect(parser)
-
end
-
128
return if @state == :connected
-
when :connected
-
116
return unless @state == :idle || @state == :connecting
-
-
99
case @state
-
when :connecting
-
38
@parser.close
-
38
@parser = nil
-
when :idle
-
78
@parser.callbacks.clear
-
78
set_parser_callbacks(@parser)
-
end
-
end
-
930
super
-
end
-
-
8
def __http_proxy_connect(parser)
-
122
req = @pending.first
-
122
if req && req.uri.scheme == "https"
-
# if the first request after CONNECT is to an https address, it is assumed that
-
# all requests in the queue are not only ALL HTTPS, but they also share the certificate,
-
# and therefore, will share the connection.
-
#
-
44
connect_request = ConnectRequest.new(req.uri, @options)
-
38
@inflight += 1
-
44
parser.send(connect_request)
-
else
-
78
handle_transition(:connected)
-
end
-
end
-
-
8
def __http_on_connect(request, response)
-
43
@inflight -= 1
-
50
if response.is_a?(Response) && response.status == 200
-
38
req = @pending.first
-
38
request_uri = req.uri
-
38
@io = ProxySSL.new(@io, request_uri, @options)
-
38
transition(:connected)
-
38
throw(:called)
-
12
elsif response.is_a?(Response) &&
-
response.status == 407 &&
-
!request.headers.key?("proxy-authorization") &&
-
@options.proxy.can_authenticate?(response.headers["proxy-authenticate"])
-
-
6
request.transition(:idle)
-
5
request.headers["proxy-authorization"] = @options.proxy.authenticate(request, response.headers["proxy-authenticate"])
-
6
@parser.send(request)
-
5
@inflight += 1
-
else
-
6
pending = @pending + @parser.pending
-
17
while (req = pending.shift)
-
6
req.emit(:response, response)
-
end
-
6
reset
-
end
-
end
-
end
-
-
8
module ProxyParser
-
8
def join_headline(request)
-
110
return super if request.verb == "CONNECT"
-
-
51
"#{request.verb} #{request.uri} HTTP/#{@version.join(".")}"
-
end
-
-
8
def set_protocol_headers(request)
-
116
extra_headers = super
-
-
116
proxy_params = @options.proxy
-
116
if proxy_params.scheme == "basic"
-
# opt for basic auth
-
63
extra_headers["proxy-authorization"] = proxy_params.authenticate(extra_headers)
-
end
-
116
extra_headers["proxy-connection"] = extra_headers.delete("connection") if extra_headers.key?("connection")
-
116
extra_headers
-
end
-
end
-
-
8
class ConnectRequest < Request
-
8
def initialize(uri, _options)
-
44
super("CONNECT", uri, {})
-
44
@headers.delete("accept")
-
end
-
-
8
def path
-
48
"#{@uri.hostname}:#{@uri.port}"
-
end
-
end
-
end
-
end
-
8
register_plugin :"proxy/http", Proxy::HTTP
-
end
-
end
-
# frozen_string_literal: true
-
-
8
require "resolv"
-
8
require "ipaddr"
-
-
8
module HTTPX
-
8
class Socks4Error < HTTPProxyError; end
-
-
8
module Plugins
-
8
module Proxy
-
8
module Socks4
-
8
VERSION = 4
-
8
CONNECT = 1
-
8
GRANTED = 0x5A
-
8
PROTOCOLS = %w[socks4 socks4a].freeze
-
-
8
Error = Socks4Error
-
-
8
class << self
-
8
def extra_options(options)
-
253
options.merge(supported_proxy_protocols: options.supported_proxy_protocols + PROTOCOLS)
-
end
-
end
-
-
8
module ConnectionMethods
-
8
def interests
-
434757
if @state == :connecting
-
return @write_buffer.empty? ? :r : :w
-
end
-
-
434757
super
-
end
-
-
8
private
-
-
8
def handle_transition(nextstate)
-
2156
return super unless @options.proxy && PROTOCOLS.include?(@options.proxy.uri.scheme)
-
-
305
case nextstate
-
when :connecting
-
96
return unless @state == :idle
-
-
96
@io.connect
-
96
return unless @io.connected?
-
-
48
req = @pending.first
-
48
return unless req
-
-
48
request_uri = req.uri
-
48
@write_buffer << Packet.connect(@options.proxy, request_uri)
-
48
__socks4_proxy_connect
-
when :connected
-
36
return unless @state == :connecting
-
-
36
@parser = nil
-
end
-
318
log(level: 1) { "SOCKS4: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
-
318
super
-
end
-
-
8
def __socks4_proxy_connect
-
48
@parser = SocksParser.new(@write_buffer, @options)
-
48
@parser.once(:packet, &method(:__socks4_on_packet))
-
end
-
-
8
def __socks4_on_packet(packet)
-
48
_version, status, _port, _ip = packet.unpack("CCnN")
-
48
if status == GRANTED
-
36
req = @pending.first
-
36
request_uri = req.uri
-
36
@io = ProxySSL.new(@io, request_uri, @options) if request_uri.scheme == "https"
-
36
transition(:connected)
-
36
throw(:called)
-
else
-
12
on_socks4_error("socks error: #{status}")
-
end
-
end
-
-
8
def on_socks4_error(message)
-
12
ex = Error.new(message)
-
12
ex.set_backtrace(caller)
-
12
on_error(ex)
-
12
throw(:called)
-
end
-
end
-
-
8
class SocksParser
-
8
include HTTPX::Callbacks
-
-
8
def initialize(buffer, options)
-
48
@buffer = buffer
-
48
@options = Options.new(options)
-
end
-
-
8
def close; end
-
-
8
def consume(*); end
-
-
8
def empty?
-
12
true
-
end
-
-
8
def <<(packet)
-
48
emit(:packet, packet)
-
end
-
end
-
-
8
module Packet
-
8
module_function
-
-
8
def connect(parameters, uri)
-
48
packet = [VERSION, CONNECT, uri.port].pack("CCn")
-
-
40
case parameters.uri.scheme
-
when "socks4"
-
36
socks_host = uri.host
-
begin
-
72
ip = IPAddr.new(socks_host)
-
36
packet << ip.hton
-
rescue IPAddr::InvalidAddressError
-
36
socks_host = Resolv.getaddress(socks_host)
-
36
retry
-
end
-
36
packet << [parameters.username].pack("Z*")
-
when "socks4a"
-
12
packet << "\x0\x0\x0\x1" << [parameters.username].pack("Z*") << uri.host << "\x0"
-
end
-
48
packet
-
end
-
end
-
end
-
end
-
8
register_plugin :"proxy/socks4", Proxy::Socks4
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
class Socks5Error < HTTPProxyError; end
-
-
8
module Plugins
-
8
module Proxy
-
8
module Socks5
-
8
VERSION = 5
-
8
NOAUTH = 0
-
8
PASSWD = 2
-
8
NONE = 0xff
-
8
CONNECT = 1
-
8
IPV4 = 1
-
8
DOMAIN = 3
-
8
IPV6 = 4
-
8
SUCCESS = 0
-
-
8
Error = Socks5Error
-
-
8
class << self
-
8
def load_dependencies(*)
-
253
require_relative "../auth/socks5"
-
end
-
-
8
def extra_options(options)
-
253
options.merge(supported_proxy_protocols: options.supported_proxy_protocols + %w[socks5])
-
end
-
end
-
-
8
module ConnectionMethods
-
8
def call
-
786
super
-
-
786
return unless @options.proxy && @options.proxy.uri.scheme == "socks5"
-
-
201
case @state
-
when :connecting,
-
:negotiating,
-
:authenticating
-
77
consume
-
end
-
end
-
-
8
def connecting?
-
435310
super || @state == :authenticating || @state == :negotiating
-
end
-
-
8
def interests
-
436445
if @state == :connecting || @state == :authenticating || @state == :negotiating
-
1477
return @write_buffer.empty? ? :r : :w
-
end
-
-
434757
super
-
end
-
-
8
private
-
-
8
def handle_transition(nextstate)
-
2372
return super unless @options.proxy && @options.proxy.uri.scheme == "socks5"
-
-
670
case nextstate
-
when :connecting
-
216
return unless @state == :idle
-
-
216
@io.connect
-
216
return unless @io.connected?
-
-
108
@write_buffer << Packet.negotiate(@options.proxy)
-
108
__socks5_proxy_connect
-
when :authenticating
-
36
return unless @state == :connecting
-
-
36
@write_buffer << Packet.authenticate(@options.proxy)
-
when :negotiating
-
144
return unless @state == :connecting || @state == :authenticating
-
-
36
req = @pending.first
-
36
request_uri = req.uri
-
36
@write_buffer << Packet.connect(request_uri)
-
when :connected
-
24
return unless @state == :negotiating
-
-
24
@parser = nil
-
end
-
588
log(level: 1) { "SOCKS5: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
-
588
super
-
end
-
-
8
def __socks5_proxy_connect
-
108
@parser = SocksParser.new(@write_buffer, @options)
-
108
@parser.on(:packet, &method(:__socks5_on_packet))
-
108
transition(:negotiating)
-
end
-
-
8
def __socks5_on_packet(packet)
-
150
case @state
-
when :connecting
-
108
version, method = packet.unpack("CC")
-
108
__socks5_check_version(version)
-
90
case method
-
when PASSWD
-
36
transition(:authenticating)
-
6
nil
-
when NONE
-
60
__on_socks5_error("no supported authorization methods")
-
else
-
12
transition(:negotiating)
-
end
-
when :authenticating
-
36
_, status = packet.unpack("CC")
-
36
return transition(:negotiating) if status == SUCCESS
-
-
12
__on_socks5_error("socks authentication error: #{status}")
-
when :negotiating
-
36
version, reply, = packet.unpack("CC")
-
36
__socks5_check_version(version)
-
36
__on_socks5_error("socks5 negotiation error: #{reply}") unless reply == SUCCESS
-
24
req = @pending.first
-
24
request_uri = req.uri
-
24
@io = ProxySSL.new(@io, request_uri, @options) if request_uri.scheme == "https"
-
24
transition(:connected)
-
24
throw(:called)
-
end
-
end
-
-
8
def __socks5_check_version(version)
-
144
__on_socks5_error("invalid SOCKS version (#{version})") if version != 5
-
end
-
-
8
def __on_socks5_error(message)
-
84
ex = Error.new(message)
-
84
ex.set_backtrace(caller)
-
84
on_error(ex)
-
84
throw(:called)
-
end
-
end
-
-
8
class SocksParser
-
8
include HTTPX::Callbacks
-
-
8
def initialize(buffer, options)
-
108
@buffer = buffer
-
108
@options = Options.new(options)
-
end
-
-
8
def close; end
-
-
8
def consume(*); end
-
-
8
def empty?
-
84
true
-
end
-
-
8
def <<(packet)
-
180
emit(:packet, packet)
-
end
-
end
-
-
8
module Packet
-
8
module_function
-
-
8
def negotiate(parameters)
-
108
methods = [NOAUTH]
-
108
methods << PASSWD if parameters.can_authenticate?
-
108
methods.unshift(methods.size)
-
108
methods.unshift(VERSION)
-
108
methods.pack("C*")
-
end
-
-
8
def authenticate(parameters)
-
36
parameters.authenticate
-
end
-
-
8
def connect(uri)
-
36
packet = [VERSION, CONNECT, 0].pack("C*")
-
begin
-
36
ip = IPAddr.new(uri.host)
-
-
12
ipcode = ip.ipv6? ? IPV6 : IPV4
-
-
12
packet << [ipcode].pack("C") << ip.hton
-
rescue IPAddr::InvalidAddressError
-
24
packet << [DOMAIN, uri.host.bytesize, uri.host].pack("CCA*")
-
end
-
36
packet << [uri.port].pack("n")
-
36
packet
-
end
-
end
-
end
-
end
-
8
register_plugin :"proxy/socks5", Proxy::Socks5
-
end
-
end
-
# frozen_string_literal: true
-
-
5
require "httpx/plugins/proxy"
-
-
5
module HTTPX
-
5
module Plugins
-
5
module Proxy
-
5
module SSH
-
5
class << self
-
5
def load_dependencies(*)
-
10
require "net/ssh/gateway"
-
end
-
end
-
-
5
module OptionsMethods
-
5
def option_proxy(value)
-
20
Hash[value]
-
end
-
end
-
-
5
module InstanceMethods
-
5
def request(*args, **options)
-
10
raise ArgumentError, "must perform at least one request" if args.empty?
-
-
10
requests = args.first.is_a?(Request) ? args : build_requests(*args, options)
-
-
10
request = requests.first or return super
-
-
10
request_options = request.options
-
-
10
return super unless request_options.proxy
-
-
10
ssh_options = request_options.proxy
-
10
ssh_uris = ssh_options.delete(:uri)
-
10
ssh_uri = URI.parse(ssh_uris.shift)
-
-
10
return super unless ssh_uri.scheme == "ssh"
-
-
10
ssh_username = ssh_options.delete(:username)
-
10
ssh_options[:port] ||= ssh_uri.port || 22
-
10
if request_options.debug
-
ssh_options[:verbose] = request_options.debug_level == 2 ? :debug : :info
-
end
-
-
10
request_uri = URI(requests.first.uri)
-
10
@_gateway = Net::SSH::Gateway.new(ssh_uri.host, ssh_username, ssh_options)
-
begin
-
10
@_gateway.open(request_uri.host, request_uri.port) do |local_port|
-
10
io = build_gateway_socket(local_port, request_uri, request_options)
-
10
super(*args, **options.merge(io: io))
-
end
-
ensure
-
10
@_gateway.shutdown!
-
end
-
end
-
-
5
private
-
-
5
def build_gateway_socket(port, request_uri, options)
-
10
case request_uri.scheme
-
when "https"
-
5
ctx = OpenSSL::SSL::SSLContext.new
-
5
ctx_options = SSL::TLS_OPTIONS.merge(options.ssl)
-
5
ctx.set_params(ctx_options) unless ctx_options.empty?
-
5
sock = TCPSocket.open("localhost", port)
-
5
io = OpenSSL::SSL::SSLSocket.new(sock, ctx)
-
5
io.hostname = request_uri.host
-
5
io.sync_close = true
-
5
io.connect
-
5
io.post_connection_check(request_uri.host) if ctx.verify_mode != OpenSSL::SSL::VERIFY_NONE
-
5
io
-
when "http"
-
5
TCPSocket.open("localhost", port)
-
else
-
raise TypeError, "unexpected scheme: #{request_uri.scheme}"
-
end
-
end
-
end
-
-
5
module ConnectionMethods
-
# should not coalesce connections here, as the IP is the IP of the proxy
-
5
def coalescable?(*)
-
return super unless @options.proxy
-
-
false
-
end
-
end
-
end
-
end
-
5
register_plugin :"proxy/ssh", Proxy::SSH
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds support for HTTP/2 Push responses.
-
#
-
# In order to benefit from this, requests are sent one at a time, so that
-
# no push responses are received after corresponding request has been sent.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Server-Push
-
#
-
6
module PushPromise
-
6
def self.extra_options(options)
-
12
options.merge(http2_settings: { settings_enable_push: 1 },
-
max_concurrent_requests: 1)
-
end
-
-
6
module ResponseMethods
-
6
def pushed?
-
12
@__pushed
-
end
-
-
6
def mark_as_pushed!
-
6
@__pushed = true
-
end
-
end
-
-
6
module InstanceMethods
-
6
private
-
-
6
def promise_headers
-
12
@promise_headers ||= {}
-
end
-
-
6
def on_promise(parser, stream)
-
12
stream.on(:promise_headers) do |h|
-
12
__on_promise_request(parser, stream, h)
-
end
-
12
stream.on(:headers) do |h|
-
6
__on_promise_response(parser, stream, h)
-
end
-
end
-
-
6
def __on_promise_request(parser, stream, h)
-
12
log(level: 1, color: :yellow) do
-
skipped
# :nocov:
-
skipped
h.map { |k, v| "#{stream.id}: -> PROMISE HEADER: #{k}: #{v}" }.join("\n")
-
skipped
# :nocov:
-
end
-
12
headers = @options.headers_class.new(h)
-
12
path = headers[":path"]
-
12
authority = headers[":authority"]
-
-
18
request = parser.pending.find { |r| r.authority == authority && r.path == path }
-
12
if request
-
6
request.merge_headers(headers)
-
5
promise_headers[stream] = request
-
6
parser.pending.delete(request)
-
5
parser.streams[request] = stream
-
6
request.transition(:done)
-
else
-
6
stream.refuse
-
end
-
end
-
-
6
def __on_promise_response(parser, stream, h)
-
6
request = promise_headers.delete(stream)
-
6
return unless request
-
-
6
parser.__send__(:on_stream_headers, stream, request, h)
-
6
response = request.response
-
6
response.mark_as_pushed!
-
6
stream.on(:data, &parser.method(:on_stream_data).curry(3)[stream, request])
-
6
stream.on(:close, &parser.method(:on_stream_close).curry(3)[stream, request])
-
end
-
end
-
end
-
6
register_plugin(:push_promise, PushPromise)
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds support for retrying requests when the request:
-
#
-
# * is rate limited;
-
# * when the server is unavailable (503);
-
# * when a 3xx request comes with a "retry-after" value
-
#
-
# https://gitlab.com/os85/httpx/wikis/Rate-Limiter
-
#
-
6
module RateLimiter
-
6
class << self
-
6
RATE_LIMIT_CODES = [429, 503].freeze
-
-
6
def configure(klass)
-
48
klass.plugin(:retries,
-
retry_change_requests: true,
-
retry_on: method(:retry_on_rate_limited_response),
-
retry_after: method(:retry_after_rate_limit))
-
end
-
-
6
def retry_on_rate_limited_response(response)
-
96
return false unless response.is_a?(Response)
-
-
96
status = response.status
-
-
96
RATE_LIMIT_CODES.include?(status)
-
end
-
-
# Servers send the "Retry-After" header field to indicate how long the
-
# user agent ought to wait before making a follow-up request. When
-
# sent with a 503 (Service Unavailable) response, Retry-After indicates
-
# how long the service is expected to be unavailable to the client.
-
# When sent with any 3xx (Redirection) response, Retry-After indicates
-
# the minimum time that the user agent is asked to wait before issuing
-
# the redirected request.
-
#
-
6
def retry_after_rate_limit(_, response)
-
48
retry_after = response.headers["retry-after"]
-
-
48
return unless retry_after
-
-
24
Utils.parse_retry_after(retry_after)
-
end
-
end
-
end
-
-
6
register_plugin :rate_limiter, RateLimiter
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds support for retrying requests when certain errors happen.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Response-Cache
-
#
-
6
module ResponseCache
-
6
CACHEABLE_VERBS = %w[GET HEAD].freeze
-
6
CACHEABLE_STATUS_CODES = [200, 203, 206, 300, 301, 410].freeze
-
6
private_constant :CACHEABLE_VERBS
-
6
private_constant :CACHEABLE_STATUS_CODES
-
-
6
class << self
-
6
def load_dependencies(*)
-
132
require_relative "response_cache/store"
-
end
-
-
6
def cacheable_request?(request)
-
186
CACHEABLE_VERBS.include?(request.verb) &&
-
(
-
186
!request.headers.key?("cache-control") || !request.headers.get("cache-control").include?("no-store")
-
)
-
end
-
-
6
def cacheable_response?(response)
-
126
response.is_a?(Response) &&
-
(
-
126
response.cache_control.nil? ||
-
# TODO: !response.cache_control.include?("private") && is shared cache
-
!response.cache_control.include?("no-store")
-
) &&
-
CACHEABLE_STATUS_CODES.include?(response.status) &&
-
# RFC 2616 13.4 - A response received with a status code of 200, 203, 206, 300, 301 or
-
# 410 MAY be stored by a cache and used in reply to a subsequent
-
# request, subject to the expiration mechanism, unless a cache-control
-
# directive prohibits caching. However, a cache that does not support
-
# the Range and Content-Range headers MUST NOT cache 206 (Partial
-
# Content) responses.
-
response.status != 206 && (
-
114
response.headers.key?("etag") || response.headers.key?("last-modified-at") || response.fresh?
-
)
-
end
-
-
6
def cached_response?(response)
-
60
response.is_a?(Response) && response.status == 304
-
end
-
-
6
def extra_options(options)
-
132
options.merge(response_cache_store: Store.new)
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_response_cache_store(value)
-
132
raise TypeError, "must be an instance of #{Store}" unless value.is_a?(Store)
-
-
132
value
-
end
-
end
-
-
6
module InstanceMethods
-
6
def clear_response_cache
-
12
@options.response_cache_store.clear
-
end
-
-
6
def build_request(*)
-
60
request = super
-
60
return request unless ResponseCache.cacheable_request?(request) && @options.response_cache_store.cached?(request)
-
-
24
@options.response_cache_store.prepare(request)
-
-
24
request
-
end
-
-
6
def fetch_response(request, *)
-
195
response = super
-
-
195
return unless response
-
-
60
if ResponseCache.cached_response?(response)
-
24
log { "returning cached response for #{request.uri}" }
-
24
cached_response = @options.response_cache_store.lookup(request)
-
-
24
response.copy_from_cached(cached_response)
-
-
else
-
36
@options.response_cache_store.cache(request, response)
-
end
-
-
60
response
-
end
-
end
-
-
6
module RequestMethods
-
6
def response_cache_key
-
384
@response_cache_key ||= Digest::SHA1.hexdigest("httpx-response-cache-#{@verb}-#{@uri}")
-
end
-
end
-
-
6
module ResponseMethods
-
6
def copy_from_cached(other)
-
24
@body = other.body.dup
-
-
24
@body.rewind
-
end
-
-
# A response is fresh if its age has not yet exceeded its freshness lifetime.
-
6
def fresh?
-
192
if cache_control
-
30
return false if cache_control.include?("no-cache")
-
-
# check age: max-age
-
36
max_age = cache_control.find { |directive| directive.start_with?("s-maxage") }
-
-
36
max_age ||= cache_control.find { |directive| directive.start_with?("max-age") }
-
-
18
max_age = max_age[/age=(\d+)/, 1] if max_age
-
-
18
max_age = max_age.to_i if max_age
-
-
18
return max_age > age if max_age
-
end
-
-
# check age: expires
-
162
if @headers.key?("expires")
-
begin
-
18
expires = Time.httpdate(@headers["expires"])
-
rescue ArgumentError
-
6
return true
-
end
-
-
10
return (expires - Time.now).to_i.positive?
-
end
-
-
144
true
-
end
-
-
6
def cache_control
-
414
return @cache_control if defined?(@cache_control)
-
-
48
@cache_control = begin
-
288
return unless @headers.key?("cache-control")
-
-
30
@headers["cache-control"].split(/ *, */)
-
end
-
end
-
-
6
def vary
-
210
return @vary if defined?(@vary)
-
-
28
@vary = begin
-
168
return unless @headers.key?("vary")
-
-
12
@headers["vary"].split(/ *, */)
-
end
-
end
-
-
6
private
-
-
6
def age
-
18
return @headers["age"].to_i if @headers.key?("age")
-
-
18
(Time.now - date).to_i
-
end
-
-
6
def date
-
18
@date ||= Time.httpdate(@headers["date"])
-
rescue NoMethodError, ArgumentError
-
6
Time.now
-
end
-
end
-
end
-
6
register_plugin :response_cache, ResponseCache
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX::Plugins
-
6
module ResponseCache
-
6
class Store
-
6
def initialize
-
186
@store = {}
-
186
@store_mutex = Thread::Mutex.new
-
end
-
-
6
def clear
-
24
@store_mutex.synchronize { @store.clear }
-
end
-
-
6
def lookup(request)
-
234
responses = _get(request)
-
-
234
return unless responses
-
-
180
responses.find(&method(:match_by_vary?).curry(2)[request])
-
end
-
-
6
def cached?(request)
-
84
lookup(request)
-
end
-
-
6
def cache(request, response)
-
126
return unless ResponseCache.cacheable_request?(request) && ResponseCache.cacheable_response?(response)
-
-
114
_set(request, response)
-
end
-
-
6
def prepare(request)
-
60
cached_response = lookup(request)
-
-
60
return unless cached_response
-
-
42
return unless match_by_vary?(request, cached_response)
-
-
42
if !request.headers.key?("if-modified-since") && (last_modified = cached_response.headers["last-modified"])
-
24
request.headers.add("if-modified-since", last_modified)
-
end
-
-
42
if !request.headers.key?("if-none-match") && (etag = cached_response.headers["etag"]) # rubocop:disable Style/GuardClause
-
42
request.headers.add("if-none-match", etag)
-
end
-
end
-
-
6
private
-
-
6
def match_by_vary?(request, response)
-
210
vary = response.vary
-
-
210
return true unless vary
-
-
54
original_request = response.instance_variable_get(:@request)
-
-
54
return request.headers.same_headers?(original_request.headers) if vary == %w[*]
-
-
30
vary.all? do |cache_field|
-
30
cache_field.downcase!
-
30
!original_request.headers.key?(cache_field) || request.headers[cache_field] == original_request.headers[cache_field]
-
end
-
end
-
-
6
def _get(request)
-
234
@store_mutex.synchronize do
-
234
responses = @store[request.response_cache_key]
-
-
234
return unless responses
-
-
180
responses.select! do |res|
-
180
!res.body.closed? && res.fresh?
-
end
-
-
180
responses
-
end
-
end
-
-
6
def _set(request, response)
-
114
@store_mutex.synchronize do
-
114
responses = (@store[request.response_cache_key] ||= [])
-
-
114
responses.reject! do |res|
-
12
res.body.closed? || !res.fresh? || match_by_vary?(request, res)
-
end
-
-
114
responses << response
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
13
module HTTPX
-
13
module Plugins
-
#
-
# This plugin adds support for retrying requests when certain errors happen.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Retries
-
#
-
13
module Retries
-
13
MAX_RETRIES = 3
-
# TODO: pass max_retries in a configure/load block
-
-
13
IDEMPOTENT_METHODS = %w[GET OPTIONS HEAD PUT DELETE].freeze
-
1
RETRYABLE_ERRORS = [
-
12
IOError,
-
EOFError,
-
Errno::ECONNRESET,
-
Errno::ECONNABORTED,
-
Errno::EPIPE,
-
Errno::EINVAL,
-
Errno::ETIMEDOUT,
-
Parser::Error,
-
TLSError,
-
TimeoutError,
-
ConnectionError,
-
Connection::HTTP2::GoawayError,
-
].freeze
-
13
DEFAULT_JITTER = ->(interval) { interval * ((rand + 1) * 0.5) }
-
-
13
if ENV.key?("HTTPX_NO_JITTER")
-
13
def self.extra_options(options)
-
511
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
-
-
13
module OptionsMethods
-
13
def option_retry_after(value)
-
# return early if callable
-
156
unless value.respond_to?(:call)
-
72
value = Float(value)
-
72
raise TypeError, ":retry_after must be positive" unless value.positive?
-
end
-
-
156
value
-
end
-
-
13
def option_retry_jitter(value)
-
# return early if callable
-
36
raise TypeError, ":retry_jitter must be callable" unless value.respond_to?(:call)
-
-
36
value
-
end
-
-
13
def option_max_retries(value)
-
1607
num = Integer(value)
-
1607
raise TypeError, ":max_retries must be positive" unless num >= 0
-
-
1607
num
-
end
-
-
13
def option_retry_change_requests(v)
-
887
v
-
end
-
-
13
def option_retry_on(value)
-
149
raise TypeError, ":retry_on must be called with the response" unless value.respond_to?(:call)
-
-
149
value
-
end
-
end
-
-
13
module InstanceMethods
-
13
def max_retries(n)
-
72
with(max_retries: n.to_i)
-
end
-
-
13
private
-
-
13
def fetch_response(request, connections, options)
-
3237358
response = super
-
-
3237358
if response &&
-
request.retries.positive? &&
-
__repeatable_request?(request, options) &&
-
(
-
94
(
-
217
response.is_a?(ErrorResponse) && __retryable_error?(response.error)
-
) ||
-
(
-
155
options.retry_on && options.retry_on.call(response)
-
)
-
)
-
332
__try_partial_retry(request, response)
-
332
log { "failed to get response, #{request.retries} tries to go..." }
-
332
request.retries -= 1
-
332
request.transition(:idle)
-
-
332
retry_after = options.retry_after
-
332
retry_after = retry_after.call(request, response) if retry_after.respond_to?(:call)
-
-
332
if retry_after
-
# apply jitter
-
72
if (jitter = request.options.retry_jitter)
-
12
retry_after = jitter.call(retry_after)
-
end
-
-
72
retry_start = Utils.now
-
72
log { "retrying after #{retry_after} secs..." }
-
72
pool.after(retry_after) do
-
72
log { "retrying (elapsed time: #{Utils.elapsed_time(retry_start)})!!" }
-
72
send_request(request, connections, options)
-
end
-
else
-
260
send_request(request, connections, options)
-
end
-
-
280
return
-
end
-
3237026
response
-
end
-
-
13
def __repeatable_request?(request, options)
-
709
IDEMPOTENT_METHODS.include?(request.verb) || options.retry_change_requests
-
end
-
-
13
def __retryable_error?(ex)
-
2513
RETRYABLE_ERRORS.any? { |klass| ex.is_a?(klass) }
-
end
-
-
13
def proxy_error?(request, response)
-
48
super && !request.retries.positive?
-
end
-
-
#
-
# Atttempt to set the request to perform a partial range request.
-
# This happens if the peer server accepts byte-range requests, and
-
# the last response contains some body payload.
-
#
-
13
def __try_partial_retry(request, response)
-
332
response = response.response if response.is_a?(ErrorResponse)
-
-
332
return unless response
-
-
141
unless response.headers.key?("accept-ranges") &&
-
response.headers["accept-ranges"] == "bytes" && # there's nothing else supported though...
-
12
(original_body = response.body)
-
129
response.close if response.respond_to?(:close)
-
109
return
-
end
-
-
12
request.partial_response = response
-
-
12
size = original_body.bytesize
-
-
10
request.headers["range"] = "bytes=#{size}-"
-
end
-
end
-
-
13
module RequestMethods
-
13
attr_accessor :retries
-
-
13
attr_writer :partial_response
-
-
13
def initialize(*args)
-
526
super
-
526
@retries = @options.max_retries
-
end
-
-
13
def response=(response)
-
870
if @partial_response
-
12
if response.is_a?(Response) && response.status == 206
-
12
response.from_partial_response(@partial_response)
-
else
-
@partial_response.close
-
end
-
12
@partial_response = nil
-
end
-
-
870
super
-
end
-
end
-
-
13
module ResponseMethods
-
13
def from_partial_response(response)
-
12
@status = response.status
-
12
@headers = response.headers
-
12
@body = response.body
-
end
-
end
-
end
-
13
register_plugin :retries, Retries
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
class ServerSideRequestForgeryError < Error; end
-
-
6
module Plugins
-
#
-
# This plugin adds support for preventing Server-Side Request Forgery attacks.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Server-Side-Request-Forgery-Filter
-
#
-
6
module SsrfFilter
-
6
module IPAddrExtensions
-
6
refine IPAddr do
-
6
def prefixlen
-
96
mask_addr = @mask_addr
-
96
raise "Invalid mask" if mask_addr.zero?
-
-
355
mask_addr >>= 1 while (mask_addr & 0x1).zero?
-
-
96
length = 0
-
349
while mask_addr & 0x1 == 0x1
-
1265
length += 1
-
1265
mask_addr >>= 1
-
end
-
-
96
length
-
end
-
end
-
end
-
-
6
using IPAddrExtensions
-
-
# https://en.wikipedia.org/wiki/Reserved_IP_addresses
-
1
IPV4_BLACKLIST = [
-
5
IPAddr.new("0.0.0.0/8"), # Current network (only valid as source address)
-
IPAddr.new("10.0.0.0/8"), # Private network
-
IPAddr.new("100.64.0.0/10"), # Shared Address Space
-
IPAddr.new("127.0.0.0/8"), # Loopback
-
IPAddr.new("169.254.0.0/16"), # Link-local
-
IPAddr.new("172.16.0.0/12"), # Private network
-
IPAddr.new("192.0.0.0/24"), # IETF Protocol Assignments
-
IPAddr.new("192.0.2.0/24"), # TEST-NET-1, documentation and examples
-
IPAddr.new("192.88.99.0/24"), # IPv6 to IPv4 relay (includes 2002::/16)
-
IPAddr.new("192.168.0.0/16"), # Private network
-
IPAddr.new("198.18.0.0/15"), # Network benchmark tests
-
IPAddr.new("198.51.100.0/24"), # TEST-NET-2, documentation and examples
-
IPAddr.new("203.0.113.0/24"), # TEST-NET-3, documentation and examples
-
IPAddr.new("224.0.0.0/4"), # IP multicast (former Class D network)
-
IPAddr.new("240.0.0.0/4"), # Reserved (former Class E network)
-
IPAddr.new("255.255.255.255"), # Broadcast
-
].freeze
-
-
1
IPV6_BLACKLIST = ([
-
5
IPAddr.new("::1/128"), # Loopback
-
IPAddr.new("64:ff9b::/96"), # IPv4/IPv6 translation (RFC 6052)
-
IPAddr.new("100::/64"), # Discard prefix (RFC 6666)
-
IPAddr.new("2001::/32"), # Teredo tunneling
-
IPAddr.new("2001:10::/28"), # Deprecated (previously ORCHID)
-
IPAddr.new("2001:20::/28"), # ORCHIDv2
-
IPAddr.new("2001:db8::/32"), # Addresses used in documentation and example source code
-
IPAddr.new("2002::/16"), # 6to4
-
IPAddr.new("fc00::/7"), # Unique local address
-
IPAddr.new("fe80::/10"), # Link-local address
-
IPAddr.new("ff00::/8"), # Multicast
-
] + IPV4_BLACKLIST.flat_map do |ipaddr|
-
96
prefixlen = ipaddr.prefixlen
-
-
96
ipv4_compatible = ipaddr.ipv4_compat.mask(96 + prefixlen)
-
96
ipv4_mapped = ipaddr.ipv4_mapped.mask(80 + prefixlen)
-
-
96
[ipv4_compatible, ipv4_mapped]
-
end).freeze
-
-
6
class << self
-
6
def extra_options(options)
-
54
options.merge(allowed_schemes: %w[https http])
-
end
-
-
6
def unsafe_ip_address?(ipaddr)
-
96
range = ipaddr.to_range
-
96
return true if range.first != range.last
-
-
108
return IPV6_BLACKLIST.any? { |r| r.include?(ipaddr) } if ipaddr.ipv6?
-
-
1140
IPV4_BLACKLIST.any? { |r| r.include?(ipaddr) } # then it's IPv4
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_allowed_schemes(value)
-
60
Array(value)
-
end
-
end
-
-
6
module InstanceMethods
-
6
def send_requests(*requests)
-
66
responses = requests.map do |request|
-
66
next if @options.allowed_schemes.include?(request.uri.scheme)
-
-
6
error = ServerSideRequestForgeryError.new("#{request.uri} URI scheme not allowed")
-
6
error.set_backtrace(caller)
-
6
response = ErrorResponse.new(request, error, request.options)
-
6
request.emit(:response, response)
-
6
response
-
end
-
132
allowed_requests = requests.select { |req| responses[requests.index(req)].nil? }
-
66
allowed_responses = super(*allowed_requests)
-
66
allowed_responses.each_with_index do |res, idx|
-
60
req = allowed_requests[idx]
-
50
responses[requests.index(req)] = res
-
end
-
-
66
responses
-
end
-
end
-
-
6
module ConnectionMethods
-
6
def initialize(*)
-
begin
-
60
super
-
8
rescue ServerSideRequestForgeryError => e
-
# may raise when IPs are passed as options via :addresses
-
12
throw(:resolve_error, e)
-
end
-
end
-
-
6
def addresses=(addrs)
-
156
addrs = addrs.map { |addr| addr.is_a?(IPAddr) ? addr : IPAddr.new(addr) }
-
-
60
addrs.reject!(&SsrfFilter.method(:unsafe_ip_address?))
-
-
60
raise ServerSideRequestForgeryError, "#{@origin.host} has no public IP addresses" if addrs.empty?
-
-
12
super
-
end
-
end
-
end
-
-
6
register_plugin :ssrf_filter, SsrfFilter
-
end
-
end
-
# frozen_string_literal: true
-
-
11
module HTTPX
-
11
class StreamResponse
-
11
def initialize(request, session)
-
119
@request = request
-
119
@session = session
-
119
@response = nil
-
end
-
-
11
def each(&block)
-
143
return enum_for(__method__) unless block
-
-
107
@request.stream = self
-
-
begin
-
107
@on_chunk = block
-
-
107
response.raise_for_status
-
ensure
-
107
response.close if @response
-
107
@on_chunk = nil
-
end
-
end
-
-
11
def each_line
-
82
return enum_for(__method__) unless block_given?
-
-
41
line = "".b
-
-
41
each do |chunk|
-
34
line << chunk
-
-
104
while (idx = line.index("\n"))
-
41
yield line.byteslice(0..idx - 1)
-
-
41
line = line.byteslice(idx + 1..-1)
-
end
-
end
-
-
17
yield line unless line.empty?
-
end
-
-
# This is a ghost method. It's to be used ONLY internally, when processing streams
-
11
def on_chunk(chunk)
-
161
raise NoMethodError unless @on_chunk
-
-
161
@on_chunk.call(chunk)
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<StreamResponse:#{object_id}>"
-
skipped
end
-
skipped
# :nocov:
-
-
11
def to_s
-
12
response.to_s
-
end
-
-
11
private
-
-
11
def response
-
476
return @response if @response
-
-
149
@request.response || begin
-
119
@response = @session.request(@request)
-
end
-
end
-
-
11
def respond_to_missing?(meth, *args)
-
12
response.respond_to?(meth, *args) || super
-
end
-
-
11
def method_missing(meth, *args, &block)
-
119
return super unless response.respond_to?(meth)
-
-
119
response.__send__(meth, *args, &block)
-
end
-
end
-
-
11
module Plugins
-
#
-
# This plugin adds support for stream response (text/event-stream).
-
#
-
# https://gitlab.com/os85/httpx/wikis/Stream
-
#
-
11
module Stream
-
11
def self.extra_options(options)
-
226
options.merge(timeout: { read_timeout: Float::INFINITY, operation_timeout: 60 })
-
end
-
-
11
module InstanceMethods
-
11
def request(*args, stream: false, **options)
-
347
return super(*args, **options) unless stream
-
-
131
requests = args.first.is_a?(Request) ? args : build_requests(*args, options)
-
131
raise Error, "only 1 response at a time is supported for streaming requests" unless requests.size == 1
-
-
119
request = requests.first
-
-
119
StreamResponse.new(request, self)
-
end
-
end
-
-
11
module RequestMethods
-
11
attr_accessor :stream
-
end
-
-
11
module ResponseMethods
-
11
def stream
-
211
request = @request.root_request if @request.respond_to?(:root_request)
-
211
request ||= @request
-
-
211
request.stream
-
end
-
end
-
-
11
module ResponseBodyMethods
-
11
def initialize(*)
-
211
super
-
211
@stream = @response.stream
-
end
-
-
11
def write(chunk)
-
266
return super unless @stream
-
-
183
return 0 if chunk.empty?
-
-
161
chunk = decode_chunk(chunk)
-
-
161
@stream.on_chunk(chunk.dup)
-
-
161
chunk.size
-
end
-
-
11
private
-
-
11
def transition(*)
-
198
return if @stream
-
-
103
super
-
end
-
end
-
end
-
11
register_plugin :stream, Stream
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin helps negotiating a new protocol from an HTTP/1.1 connection, via the
-
# Upgrade header.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Upgrade
-
#
-
6
module Upgrade
-
6
class << self
-
6
def configure(klass)
-
24
klass.plugin(:"upgrade/h2")
-
end
-
-
6
def extra_options(options)
-
24
options.merge(upgrade_handlers: {})
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_upgrade_handlers(value)
-
66
raise TypeError, ":upgrade_handlers must be a Hash" unless value.is_a?(Hash)
-
-
66
value
-
end
-
end
-
-
6
module InstanceMethods
-
6
def fetch_response(request, connections, options)
-
203
response = super
-
-
203
if response
-
66
return response unless response.is_a?(Response)
-
-
66
return response unless response.headers.key?("upgrade")
-
-
24
upgrade_protocol = response.headers["upgrade"].split(/ *, */).first
-
-
24
return response unless upgrade_protocol && options.upgrade_handlers.key?(upgrade_protocol)
-
-
24
protocol_handler = options.upgrade_handlers[upgrade_protocol]
-
-
24
return response unless protocol_handler
-
-
24
log { "upgrading to #{upgrade_protocol}..." }
-
24
connection = find_connection(request, connections, options)
-
-
# do not upgrade already upgraded connections
-
24
return if connection.upgrade_protocol == upgrade_protocol
-
-
24
protocol_handler.call(connection, request, response)
-
-
# keep in the loop if the server is switching, unless
-
# the connection has been hijacked, in which case you want
-
# to terminante immediately
-
24
return if response.status == 101 && !connection.hijacked
-
end
-
-
149
response
-
end
-
-
6
def close(*args)
-
30
return super if args.empty?
-
-
18
connections, = args
-
-
18
pool.close(connections.reject(&:hijacked))
-
end
-
end
-
-
6
module ConnectionMethods
-
6
attr_reader :upgrade_protocol, :hijacked
-
-
6
def hijack_io
-
6
@hijacked = true
-
end
-
end
-
end
-
6
register_plugin(:upgrade, Upgrade)
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds support for upgrading an HTTP/1.1 connection to HTTP/2
-
# via an Upgrade: h2 response declaration
-
#
-
# https://gitlab.com/os85/httpx/wikis/Connection-Upgrade#h2
-
#
-
6
module H2
-
6
class << self
-
6
def extra_options(options)
-
24
options.merge(upgrade_handlers: options.upgrade_handlers.merge("h2" => self))
-
end
-
-
6
def call(connection, _request, _response)
-
6
connection.upgrade_to_h2
-
end
-
end
-
-
6
module ConnectionMethods
-
6
using URIExtensions
-
-
6
def upgrade_to_h2
-
6
prev_parser = @parser
-
-
6
if prev_parser
-
6
prev_parser.reset
-
5
@inflight -= prev_parser.requests.size
-
end
-
-
6
@parser = Connection::HTTP2.new(@write_buffer, @options)
-
6
set_parser_callbacks(@parser)
-
6
@upgrade_protocol = "h2"
-
-
# what's happening here:
-
# a deviation from the state machine is done to perform the actions when a
-
# connection is closed, without transitioning, so the connection is kept in the pool.
-
# the state is reset to initial, so that the socket reconnect works out of the box,
-
# while the parser is already here.
-
6
purge_after_closed
-
6
transition(:idle)
-
-
6
prev_parser.requests.each do |req|
-
req.transition(:idle)
-
send(req)
-
end
-
end
-
end
-
end
-
6
register_plugin(:"upgrade/h2", H2)
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin implements convenience methods for performing WEBDAV requests.
-
#
-
# https://gitlab.com/os85/httpx/wikis/WebDav
-
#
-
6
module WebDav
-
6
module InstanceMethods
-
6
def copy(src, dest)
-
12
request("COPY", src, headers: { "destination" => @options.origin.merge(dest) })
-
end
-
-
6
def move(src, dest)
-
12
request("MOVE", src, headers: { "destination" => @options.origin.merge(dest) })
-
end
-
-
6
def lock(path, timeout: nil, &blk)
-
36
headers = {}
-
30
headers["timeout"] = if timeout && timeout.positive?
-
12
"Second-#{timeout}"
-
else
-
24
"Infinite, Second-4100000000"
-
end
-
36
xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" \
-
"<D:lockinfo xmlns:D=\"DAV:\">" \
-
"<D:lockscope><D:exclusive/></D:lockscope>" \
-
"<D:locktype><D:write/></D:locktype>" \
-
"<D:owner>null</D:owner>" \
-
"</D:lockinfo>"
-
36
response = request("LOCK", path, headers: headers, xml: xml)
-
-
36
return response unless response.is_a?(Response)
-
-
36
return response unless blk && response.status == 200
-
-
12
lock_token = response.headers["lock-token"]
-
-
begin
-
12
blk.call(response)
-
ensure
-
12
unlock(path, lock_token)
-
end
-
end
-
-
6
def unlock(path, lock_token)
-
24
request("UNLOCK", path, headers: { "lock-token" => lock_token })
-
end
-
-
6
def mkcol(dir)
-
12
request("MKCOL", dir)
-
end
-
-
6
def propfind(path, xml = nil)
-
48
body = case xml
-
when :acl
-
10
'<?xml version="1.0" encoding="utf-8" ?><D:propfind xmlns:D="DAV:"><D:prop><D:owner/>' \
-
"<D:supported-privilege-set/><D:current-user-privilege-set/><D:acl/></D:prop></D:propfind>"
-
when nil
-
24
'<?xml version="1.0" encoding="utf-8"?><DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
-
else
-
12
xml
-
end
-
-
48
request("PROPFIND", path, headers: { "depth" => "1" }, xml: body)
-
end
-
-
6
def proppatch(path, xml)
-
2
body = "<?xml version=\"1.0\"?>" \
-
12
"<D:propertyupdate xmlns:D=\"DAV:\" xmlns:Z=\"http://ns.example.com/standards/z39.50/\">#{xml}</D:propertyupdate>"
-
12
request("PROPPATCH", path, xml: body)
-
end
-
# %i[ orderpatch acl report search]
-
end
-
end
-
6
register_plugin(:webdav, WebDav)
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module ResponsePatternMatchExtensions
-
23
def deconstruct
-
31
[@status, @headers, @body]
-
end
-
-
23
def deconstruct_keys(_keys)
-
50
{ status: @status, headers: @headers, body: @body }
-
end
-
end
-
-
23
module ErrorResponsePatternMatchExtensions
-
23
def deconstruct
-
9
[@error]
-
end
-
-
23
def deconstruct_keys(_keys)
-
25
{ error: @error }
-
end
-
end
-
-
23
module HeadersPatternMatchExtensions
-
23
def deconstruct
-
5
to_a
-
end
-
end
-
-
23
Headers.include HeadersPatternMatchExtensions
-
23
Response.include ResponsePatternMatchExtensions
-
23
ErrorResponse.include ErrorResponsePatternMatchExtensions
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
23
require "httpx/selector"
-
23
require "httpx/connection"
-
23
require "httpx/resolver"
-
-
23
module HTTPX
-
23
class Pool
-
23
using ArrayExtensions::FilterMap
-
23
extend Forwardable
-
-
23
def_delegator :@timers, :after
-
-
23
def initialize
-
500
@resolvers = {}
-
500
@timers = Timers.new
-
500
@selector = Selector.new
-
500
@connections = []
-
end
-
-
23
def wrap
-
377
connections = @connections
-
377
@connections = []
-
-
begin
-
377
yield self
-
ensure
-
377
@connections.unshift(*connections)
-
end
-
end
-
-
23
def empty?
-
763
@connections.empty?
-
end
-
-
23
def next_tick
-
3691913
catch(:jump_tick) do
-
3691913
timeout = next_timeout
-
3691913
if timeout && timeout.negative?
-
@timers.fire
-
throw(:jump_tick)
-
end
-
-
begin
-
3691913
@selector.select(timeout, &:call)
-
3691809
@timers.fire
-
rescue TimeoutError => e
-
5
@timers.fire(e)
-
end
-
end
-
rescue StandardError => e
-
21
@connections.each do |connection|
-
38
connection.emit(:error, e)
-
end
-
rescue Exception # rubocop:disable Lint/RescueException
-
78
@connections.each(&:force_reset)
-
72
raise
-
end
-
-
23
def close(connections = @connections)
-
4814
return if connections.empty?
-
-
4684
connections = connections.reject(&:inflight?)
-
4684
connections.each(&:terminate)
-
9552
next_tick until connections.none? { |c| c.state != :idle && @connections.include?(c) }
-
-
# close resolvers
-
4678
outstanding_connections = @connections
-
4678
resolver_connections = @resolvers.each_value.flat_map(&:connections).compact
-
3969
outstanding_connections -= resolver_connections
-
-
4678
return unless outstanding_connections.empty?
-
-
1983
@resolvers.each_value do |resolver|
-
1849
resolver.close unless resolver.closed?
-
end
-
# for https resolver
-
1983
resolver_connections.each(&:terminate)
-
2018
next_tick until resolver_connections.none? { |c| c.state != :idle && @connections.include?(c) }
-
end
-
-
23
def init_connection(connection, _options)
-
5105
connection.timers = @timers
-
5105
connection.on(:activate) do
-
460
select_connection(connection)
-
end
-
5105
connection.on(:exhausted) do
-
5
case connection.state
-
when :closed
-
6
connection.idling
-
6
@connections << connection
-
6
select_connection(connection)
-
when :closing
-
connection.once(:close) do
-
connection.idling
-
@connections << connection
-
select_connection(connection)
-
end
-
end
-
end
-
5105
connection.on(:close) do
-
5718
unregister_connection(connection)
-
end
-
5105
connection.on(:terminate) do
-
4556
unregister_connection(connection, true)
-
end
-
5105
resolve_connection(connection) unless connection.family
-
end
-
-
23
def deactivate(connections)
-
779
connections.each do |connection|
-
809
connection.deactivate
-
809
deselect_connection(connection) if connection.state == :inactive
-
end
-
end
-
-
# opens a connection to the IP reachable through +uri+.
-
# Many hostnames are reachable through the same IP, so we try to
-
# maximize pipelining by opening as few connections as possible.
-
#
-
23
def find_connection(uri, options)
-
6487
conn = @connections.find do |connection|
-
12159
connection.match?(uri, options)
-
end
-
-
6487
return unless conn
-
-
1245
case conn.state
-
when :closed
-
336
conn.idling
-
336
select_connection(conn)
-
when :closing
-
conn.once(:close) do
-
conn.idling
-
select_connection(conn)
-
end
-
end
-
-
1364
conn
-
end
-
-
23
private
-
-
23
def resolve_connection(connection)
-
5110
@connections << connection unless @connections.include?(connection)
-
-
5110
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.
-
#
-
170
connection.once(:connect_error, &connection.method(:handle_error))
-
170
on_resolver_connection(connection)
-
161
return
-
end
-
-
4940
find_resolver_for(connection) do |resolver|
-
370
resolver << try_clone_connection(connection, resolver.family)
-
360
next if resolver.empty?
-
-
290
select_connection(resolver)
-
end
-
end
-
-
23
def try_clone_connection(connection, family)
-
370
connection.family ||= family
-
-
370
return connection if connection.family == family
-
-
new_connection = connection.class.new(connection.origin, connection.options)
-
new_connection.family = family
-
-
connection.once(:tcp_open) { new_connection.force_reset }
-
connection.once(:connect_error) do |err|
-
if new_connection.connecting?
-
new_connection.merge(connection)
-
connection.emit(:cloned, new_connection)
-
connection.force_reset
-
else
-
connection.__send__(:handle_error, err)
-
end
-
end
-
-
new_connection.once(:tcp_open) do |new_conn|
-
if new_conn != connection
-
new_conn.merge(connection)
-
connection.force_reset
-
end
-
end
-
new_connection.once(:connect_error) do |err|
-
if connection.connecting?
-
# main connection has the requests
-
connection.merge(new_connection)
-
new_connection.emit(:cloned, connection)
-
new_connection.force_reset
-
else
-
new_connection.__send__(:handle_error, err)
-
end
-
end
-
-
init_connection(new_connection, connection.options)
-
new_connection
-
end
-
-
23
def on_resolver_connection(connection)
-
5102
@connections << connection unless @connections.include?(connection)
-
5102
found_connection = @connections.find do |ch|
-
14412
ch != connection && ch.mergeable?(connection)
-
end
-
5102
return register_connection(connection) unless found_connection
-
-
23
if found_connection.open?
-
22
coalesce_connections(found_connection, connection)
-
22
throw(:coalesced, found_connection) unless @connections.include?(connection)
-
else
-
1
found_connection.once(:open) do
-
1
coalesce_connections(found_connection, connection)
-
end
-
end
-
end
-
-
23
def on_resolver_error(connection, error)
-
151
return connection.emit(:connect_error, error) if connection.connecting? && connection.callbacks_for?(:connect_error)
-
-
151
connection.emit(:error, error)
-
end
-
-
23
def on_resolver_close(resolver)
-
179
resolver_type = resolver.class
-
179
return if resolver.closed?
-
-
179
@resolvers.delete(resolver_type)
-
-
179
deselect_connection(resolver)
-
179
resolver.close unless resolver.closed?
-
end
-
-
23
def register_connection(connection)
-
5091
select_connection(connection)
-
end
-
-
23
def unregister_connection(connection, cleanup = !connection.used?)
-
10279
@connections.delete(connection) if cleanup
-
10279
deselect_connection(connection)
-
end
-
-
23
def select_connection(connection)
-
6183
@selector.register(connection)
-
end
-
-
23
def deselect_connection(connection)
-
10955
@selector.deregister(connection)
-
end
-
-
23
def coalesce_connections(conn1, conn2)
-
23
return register_connection(conn2) unless conn1.coalescable?(conn2)
-
-
11
conn2.emit(:tcp_open, conn1)
-
11
conn1.merge(conn2)
-
11
@connections.delete(conn2)
-
end
-
-
23
def next_timeout
-
450619
[
-
3241294
@timers.wait_interval,
-
*@resolvers.values.reject(&:closed?).filter_map(&:timeout),
-
*@connections.filter_map(&:timeout),
-
].compact.min
-
end
-
-
23
def find_resolver_for(connection)
-
4940
connection_options = connection.options
-
4940
resolver_type = connection_options.resolver_class
-
4940
resolver_type = Resolver.resolver_for(resolver_type)
-
-
4940
@resolvers[resolver_type] ||= begin
-
600
resolver_manager = if resolver_type.multi?
-
579
Resolver::Multi.new(resolver_type, connection_options)
-
else
-
21
resolver_type.new(connection_options)
-
end
-
600
resolver_manager.on(:resolve, &method(:on_resolver_connection))
-
600
resolver_manager.on(:error, &method(:on_resolver_error))
-
600
resolver_manager.on(:close, &method(:on_resolver_close))
-
600
resolver_manager
-
end
-
-
4940
manager = @resolvers[resolver_type]
-
-
4940
(manager.is_a?(Resolver::Multi) && manager.early_resolve(connection)) || manager.resolvers.each do |resolver|
-
370
resolver.pool = self
-
370
yield resolver
-
end
-
-
4895
manager
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Punycode
-
23
module_function
-
-
begin
-
23
require "idnx"
-
-
22
def encode_hostname(hostname)
-
24
Idnx.to_punycode(hostname)
-
end
-
rescue LoadError
-
1
def encode_hostname(hostname)
-
1
warn "#{hostname} cannot be converted to punycode. Install the " \
-
"\"idnx\" gem: https://github.com/HoneyryderChuck/idnx"
-
-
1
hostname
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "delegate"
-
23
require "forwardable"
-
-
23
module HTTPX
-
# Defines how an HTTP request is handled internally, both in terms of making attributes accessible,
-
# as well as maintaining the state machine which manages streaming the request onto the wire.
-
23
class Request
-
23
extend Forwardable
-
23
include Callbacks
-
23
using URIExtensions
-
-
# default value used for "user-agent" header, when not overridden.
-
23
USER_AGENT = "httpx.rb/#{VERSION}"
-
-
# the upcased string HTTP verb for this request.
-
23
attr_reader :verb
-
-
# the absolute URI object for this request.
-
23
attr_reader :uri
-
-
# an HTTPX::Headers object containing the request HTTP headers.
-
23
attr_reader :headers
-
-
# an HTTPX::Request::Body object containing the request body payload (or +nil+, whenn there is none).
-
23
attr_reader :body
-
-
# a symbol describing which frame is currently being flushed.
-
23
attr_reader :state
-
-
# an HTTPX::Options object containing request options.
-
23
attr_reader :options
-
-
# the corresponding HTTPX::Response object, when there is one.
-
23
attr_reader :response
-
-
# Exception raised during enumerable body writes.
-
23
attr_reader :drain_error
-
-
# The IP address from the peer server.
-
23
attr_accessor :peer_address
-
-
23
attr_writer :persistent
-
-
# will be +true+ when request body has been completely flushed.
-
23
def_delegator :@body, :empty?
-
-
# initializes the instance with the given +verb+, an absolute or relative +uri+, and the
-
# request options.
-
23
def initialize(verb, uri, options = {})
-
6916
@verb = verb.to_s.upcase
-
6916
@options = Options.new(options)
-
6916
@uri = Utils.to_uri(uri)
-
6915
if @uri.relative?
-
432
origin = @options.origin
-
432
raise(Error, "invalid URI: #{@uri}") unless origin
-
-
432
base_path = @options.base_path
-
-
432
@uri = origin.merge("#{base_path}#{@uri}")
-
end
-
-
6915
@headers = @options.headers.dup
-
6915
@headers["user-agent"] ||= USER_AGENT
-
6915
@headers["accept"] ||= "*/*"
-
-
6915
@body = @options.request_body_class.new(@headers, @options)
-
6909
@state = :idle
-
6909
@response = nil
-
6909
@peer_address = nil
-
6909
@persistent = @options.persistent
-
end
-
-
# the read timeout defied for this requet.
-
23
def read_timeout
-
16506
@options.timeout[:read_timeout]
-
end
-
-
# the write timeout defied for this requet.
-
23
def write_timeout
-
16506
@options.timeout[:write_timeout]
-
end
-
-
# the request timeout defied for this requet.
-
23
def request_timeout
-
16506
@options.timeout[:request_timeout]
-
end
-
-
23
def persistent?
-
3453
@persistent
-
end
-
-
23
def trailers?
-
2110
defined?(@trailers)
-
end
-
-
23
def trailers
-
66
@trailers ||= @options.headers_class.new
-
end
-
-
# returns +:r+ or +:w+, depending on whether the request is waiting for a response or flushing.
-
23
def interests
-
18733
return :r if @state == :done || @state == :expect
-
-
2885
:w
-
end
-
-
23
def merge_headers(h)
-
6
@headers = @headers.merge(h)
-
end
-
-
# the URI scheme of the request +uri+.
-
23
def scheme
-
2530
@uri.scheme
-
end
-
-
# sets the +response+ on this request.
-
23
def response=(response)
-
6553
return unless response
-
-
6553
if response.is_a?(Response) && response.status < 200
-
# deal with informational responses
-
-
114
if response.status == 100 && @headers.key?("expect")
-
96
@informational_status = response.status
-
96
return
-
end
-
-
# 103 Early Hints advertises resources in document to browsers.
-
# not very relevant for an HTTP client, discard.
-
18
return if response.status >= 103
-
end
-
-
6457
@response = response
-
-
6457
emit(:response_started, response)
-
end
-
-
# returnns the URI path of the request +uri+.
-
23
def path
-
6099
path = uri.path.dup
-
6099
path = +"" if path.nil?
-
6099
path << "/" if path.empty?
-
6099
path << "?#{query}" unless query.empty?
-
6099
path
-
end
-
-
# returs the URI authority of the request.
-
#
-
# session.build_request("GET", "https://google.com/query").authority #=> "google.com"
-
# session.build_request("GET", "http://internal:3182/a").authority #=> "internal:3182"
-
23
def authority
-
6145
@uri.authority
-
end
-
-
# returs the URI origin of the request.
-
#
-
# session.build_request("GET", "https://google.com/query").authority #=> "https://google.com"
-
# session.build_request("GET", "http://internal:3182/a").authority #=> "http://internal:3182"
-
23
def origin
-
2730
@uri.origin
-
end
-
-
# returs the URI query string of the request (when available).
-
#
-
# session.build_request("GET", "https://search.com").query #=> ""
-
# session.build_request("GET", "https://search.com?q=a").query #=> "q=a"
-
# session.build_request("GET", "https://search.com", params: { q: "a"}).query #=> "q=a"
-
# session.build_request("GET", "https://search.com?q=a", params: { foo: "bar"}).query #=> "q=a&foo&bar"
-
23
def query
-
6737
return @query if defined?(@query)
-
-
5673
query = []
-
5673
if (q = @options.params)
-
116
query << Transcoder::Form.encode(q)
-
end
-
5673
query << @uri.query if @uri.query
-
5673
@query = query.join("&")
-
end
-
-
# consumes and returns the next available chunk of request body that can be sent
-
23
def drain_body
-
6628
return nil if @body.nil?
-
-
6628
@drainer ||= @body.each
-
6628
chunk = @drainer.next.dup
-
-
4527
emit(:body_chunk, chunk)
-
4527
chunk
-
rescue StopIteration
-
2091
nil
-
rescue StandardError => e
-
10
@drain_error = e
-
10
nil
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<HTTPX::Request:#{object_id} " \
-
skipped
"#{@verb} " \
-
skipped
"#{uri} " \
-
skipped
"@headers=#{@headers} " \
-
skipped
"@body=#{@body}>"
-
skipped
end
-
skipped
# :nocov:
-
-
# moves on to the +nextstate+ of the request state machine (when all preconditions are met)
-
23
def transition(nextstate)
-
24903
case nextstate
-
when :idle
-
513
@body.rewind
-
513
@response = nil
-
513
@drainer = nil
-
when :headers
-
8020
return unless @state == :idle
-
when :body
-
8008
return unless @state == :headers ||
-
@state == :expect
-
-
6236
if @headers.key?("expect")
-
365
if @informational_status && @informational_status == 100
-
# check for 100 Continue response, and deallocate the var
-
# if @informational_status == 100
-
# @response = nil
-
# end
-
else
-
277
return if @state == :expect # do not re-set it
-
-
108
nextstate = :expect
-
end
-
end
-
when :trailers
-
6226
return unless @state == :body
-
when :done
-
6232
return if @state == :expect
-
end
-
24447
@state = nextstate
-
24447
emit(@state, self)
-
3357
nil
-
end
-
-
# whether the request supports the 100-continue handshake and already processed the 100 response.
-
23
def expects?
-
5739
@headers["expect"] == "100-continue" && @informational_status == 100 && !@response
-
end
-
end
-
end
-
-
23
require_relative "request/body"
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
# Implementation of the HTTP Request body as a delegator which iterates (responds to +each+) payload chunks.
-
23
class Request::Body < SimpleDelegator
-
23
class << self
-
23
def new(_, options)
-
6921
return options.body if options.body.is_a?(self)
-
-
6714
super
-
end
-
end
-
-
# inits the instance with the request +headers+ and +options+, which contain the payload definition.
-
23
def initialize(headers, options)
-
6714
@headers = headers
-
-
# forego compression in the Range request case
-
6714
if @headers.key?("range")
-
6
@headers.delete("accept-encoding")
-
else
-
6708
@headers["accept-encoding"] ||= options.supported_compression_formats
-
end
-
-
6714
initialize_body(options)
-
-
6714
return if @body.nil?
-
-
2142
@headers["content-type"] ||= @body.content_type
-
2142
@headers["content-length"] = @body.bytesize unless unbounded_body?
-
2136
super(@body)
-
end
-
-
# consumes and yields the request payload in chunks.
-
23
def each(&block)
-
4658
return enum_for(__method__) unless block
-
2329
return if @body.nil?
-
-
2154
body = stream(@body)
-
2154
if body.respond_to?(:read)
-
922
::IO.copy_stream(body, ProcIO.new(block))
-
1232
elsif body.respond_to?(:each)
-
303
body.each(&block)
-
else
-
929
block[body.to_s]
-
end
-
end
-
-
# if the +@body+ is rewindable, it rewinnds it.
-
23
def rewind
-
597
return if empty?
-
-
96
@body.rewind if @body.respond_to?(:rewind)
-
end
-
-
# return +true+ if the +body+ has been fully drained (or does nnot exist).
-
23
def empty?
-
13508
return true if @body.nil?
-
6205
return false if chunked?
-
-
6133
@body.bytesize.zero?
-
end
-
-
# returns the +@body+ payload size in bytes.
-
23
def bytesize
-
2472
return 0 if @body.nil?
-
-
96
@body.bytesize
-
end
-
-
# sets the body to yield using chunked trannsfer encoding format.
-
23
def stream(body)
-
2154
return body unless chunked?
-
-
72
Transcoder::Chunker.encode(body.enum_for(:each))
-
end
-
-
# returns whether the body yields infinitely.
-
23
def unbounded_body?
-
2448
return @unbounded_body if defined?(@unbounded_body)
-
-
2142
@unbounded_body = !@body.nil? && (chunked? || @body.bytesize == Float::INFINITY)
-
end
-
-
# returns whether the chunked transfer encoding header is set.
-
23
def chunked?
-
14112
@headers["transfer-encoding"] == "chunked"
-
end
-
-
# sets the chunked transfer encoding header.
-
23
def chunk!
-
24
@headers.add("transfer-encoding", "chunked")
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<HTTPX::Request::Body:#{object_id} " \
-
skipped
"#{unbounded_body? ? "stream" : "@bytesize=#{bytesize}"}>"
-
skipped
end
-
skipped
# :nocov:
-
-
23
private
-
-
# wraps the given body with the appropriate encoder.
-
#
-
# ..., json: { foo: "bar" }) #=> json encoder
-
# ..., form: { foo: "bar" }) #=> form urlencoded encoder
-
# ..., form: { foo: Pathname.open("path/to/file") }) #=> multipart urlencoded encoder
-
# ..., form: { foo: File.open("path/to/file") }) #=> multipart urlencoded encoder
-
# ..., form: { body: "bla") }) #=> raw data encoder
-
23
def initialize_body(options)
-
6714
@body = if options.body
-
902
Transcoder::Body.encode(options.body)
-
5812
elsif options.form
-
1084
Transcoder::Form.encode(options.form)
-
4728
elsif options.json
-
54
Transcoder::JSON.encode(options.json)
-
4674
elsif options.xml
-
102
Transcoder::Xml.encode(options.xml)
-
end
-
-
6714
return unless @body && options.compress_request_body && @headers.key?("content-encoding")
-
-
62
@headers.get("content-encoding").each do |encoding|
-
62
@body = self.class.initialize_deflater_body(@body, encoding)
-
end
-
end
-
-
23
class << self
-
# returns the +body+ wrapped with the correct deflater accordinng to the given +encodisng+.
-
23
def initialize_deflater_body(body, encoding)
-
55
case encoding
-
when "gzip"
-
32
Transcoder::GZIP.encode(body)
-
when "deflate"
-
12
Transcoder::Deflate.encode(body)
-
when "identity"
-
12
body
-
else
-
6
body
-
end
-
end
-
end
-
end
-
-
# Wrapper yielder which can be used with functions which expect an IO writer.
-
23
class ProcIO
-
23
def initialize(block)
-
922
@block = block
-
end
-
-
# Implementation the IO write protocol, which yield the given chunk to +@block+.
-
23
def write(data)
-
2622
@block.call(data.dup)
-
2616
data.bytesize
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "resolv"
-
23
require "ipaddr"
-
-
23
module HTTPX
-
23
module Resolver
-
23
RESOLVE_TIMEOUT = [2, 3].freeze
-
-
23
require "httpx/resolver/resolver"
-
23
require "httpx/resolver/system"
-
23
require "httpx/resolver/native"
-
23
require "httpx/resolver/https"
-
23
require "httpx/resolver/multi"
-
-
23
@lookup_mutex = Thread::Mutex.new
-
152
@lookups = Hash.new { |h, k| h[k] = [] }
-
-
23
@identifier_mutex = Thread::Mutex.new
-
23
@identifier = 1
-
23
@system_resolver = Resolv::Hosts.new
-
-
23
module_function
-
-
23
def resolver_for(resolver_type)
-
4227
case resolver_type
-
4820
when :native then Native
-
27
when :system then System
-
61
when :https then HTTPS
-
else
-
62
return resolver_type if resolver_type.is_a?(Class) && resolver_type < Resolver
-
-
6
raise Error, "unsupported resolver type (#{resolver_type})"
-
end
-
end
-
-
23
def nolookup_resolve(hostname)
-
4815
ip_resolve(hostname) || cached_lookup(hostname) || system_resolve(hostname)
-
end
-
-
23
def ip_resolve(hostname)
-
4815
[IPAddr.new(hostname)]
-
rescue ArgumentError
-
end
-
-
23
def system_resolve(hostname)
-
429
ips = @system_resolver.getaddresses(hostname)
-
429
return if ips.empty?
-
-
555
ips.map { |ip| IPAddr.new(ip) }
-
rescue IOError
-
end
-
-
23
def cached_lookup(hostname)
-
4578
now = Utils.now
-
4578
@lookup_mutex.synchronize do
-
4578
lookup(hostname, now)
-
end
-
end
-
-
23
def cached_lookup_set(hostname, family, entries)
-
176
now = Utils.now
-
176
entries.each do |entry|
-
233
entry["TTL"] += now
-
end
-
176
@lookup_mutex.synchronize do
-
148
case family
-
when Socket::AF_INET6
-
30
@lookups[hostname].concat(entries)
-
when Socket::AF_INET
-
146
@lookups[hostname].unshift(*entries)
-
end
-
176
entries.each do |entry|
-
233
next unless entry["name"] != hostname
-
-
22
case family
-
when Socket::AF_INET6
-
6
@lookups[entry["name"]] << entry
-
when Socket::AF_INET
-
18
@lookups[entry["name"]].unshift(entry)
-
end
-
end
-
end
-
end
-
-
# do not use directly!
-
23
def lookup(hostname, ttl)
-
4584
return unless @lookups.key?(hostname)
-
-
4150
entries = @lookups[hostname] = @lookups[hostname].select do |address|
-
8657
address["TTL"] > ttl
-
end
-
-
4150
ips = entries.flat_map do |address|
-
8650
if address.key?("alias")
-
6
lookup(address["alias"], ttl)
-
else
-
8644
IPAddr.new(address["data"])
-
end
-
end.compact
-
-
4150
ips unless ips.empty?
-
end
-
-
23
def generate_id
-
1216
@identifier_mutex.synchronize { @identifier = (@identifier + 1) & 0xFFFF }
-
end
-
-
23
def encode_dns_query(hostname, type: Resolv::DNS::Resource::IN::A, message_id: generate_id)
-
608
Resolv::DNS::Message.new.tap do |query|
-
608
query.id = message_id
-
608
query.rd = 1
-
608
query.add_question(hostname, type)
-
end.encode
-
end
-
-
23
def decode_dns_answer(payload)
-
begin
-
551
message = Resolv::DNS::Message.decode(payload)
-
rescue Resolv::DNS::DecodeError => e
-
5
return :decode_error, e
-
end
-
-
# no domain was found
-
546
return :no_domain_found if message.rcode == Resolv::DNS::RCode::NXDomain
-
-
220
return :message_truncated if message.tc == 1
-
-
210
return :dns_error, message.rcode if message.rcode != Resolv::DNS::RCode::NoError
-
-
200
addresses = []
-
-
200
message.each_answer do |question, _, value|
-
849
case value
-
when Resolv::DNS::Resource::IN::CNAME
-
18
addresses << {
-
"name" => question.to_s,
-
"TTL" => value.ttl,
-
"alias" => value.name.to_s,
-
}
-
when Resolv::DNS::Resource::IN::A,
-
Resolv::DNS::Resource::IN::AAAA
-
860
addresses << {
-
"name" => question.to_s,
-
"TTL" => value.ttl,
-
"data" => value.address.to_s,
-
}
-
end
-
end
-
-
200
[:ok, addresses]
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "resolv"
-
23
require "uri"
-
23
require "cgi"
-
23
require "forwardable"
-
23
require "httpx/base64"
-
-
23
module HTTPX
-
23
class Resolver::HTTPS < Resolver::Resolver
-
23
extend Forwardable
-
23
using URIExtensions
-
-
23
module DNSExtensions
-
23
refine Resolv::DNS do
-
23
def generate_candidates(name)
-
35
@config.generate_candidates(name)
-
end
-
end
-
end
-
23
using DNSExtensions
-
-
23
NAMESERVER = "https://1.1.1.1/dns-query"
-
-
1
DEFAULTS = {
-
22
uri: NAMESERVER,
-
use_get: false,
-
}.freeze
-
-
23
def_delegators :@resolver_connection, :state, :connecting?, :to_io, :call, :close, :terminate
-
-
23
def initialize(_, options)
-
40
super
-
40
@resolver_options = DEFAULTS.merge(@options.resolver_options)
-
40
@queries = {}
-
40
@requests = {}
-
40
@connections = []
-
40
@uri = URI(@resolver_options[:uri])
-
40
@uri_addresses = nil
-
40
@resolver = Resolv::DNS.new
-
40
@resolver.timeouts = @resolver_options.fetch(:timeouts, Resolver::RESOLVE_TIMEOUT)
-
40
@resolver.lazy_initialize
-
end
-
-
23
def <<(connection)
-
75
return if @uri.origin == connection.origin.to_s
-
-
40
@uri_addresses ||= HTTPX::Resolver.nolookup_resolve(@uri.host) || @resolver.getaddresses(@uri.host)
-
-
40
if @uri_addresses.empty?
-
5
ex = ResolveError.new("Can't resolve DNS server #{@uri.host}")
-
5
ex.set_backtrace(caller)
-
5
connection.force_reset
-
5
throw(:resolve_error, ex)
-
end
-
-
35
resolve(connection)
-
end
-
-
23
def closed?
-
200
true
-
end
-
-
23
def empty?
-
70
true
-
end
-
-
23
def resolver_connection
-
90
@resolver_connection ||= @pool.find_connection(@uri, @options) || begin
-
35
@building_connection = true
-
35
connection = @options.connection_class.new(@uri, @options.merge(ssl: { alpn_protocols: %w[h2] }))
-
35
@pool.init_connection(connection, @options)
-
# only explicity emit addresses if connection didn't pre-resolve, i.e. it's not an IP.
-
35
emit_addresses(connection, @family, @uri_addresses) unless connection.addresses
-
35
@building_connection = false
-
35
connection
-
end
-
end
-
-
23
private
-
-
23
def resolve(connection = @connections.first, hostname = nil)
-
55
return if @building_connection
-
55
return unless connection
-
-
55
hostname ||= @queries.key(connection)
-
-
55
if hostname.nil?
-
35
hostname = connection.origin.host
-
35
log { "resolver: resolve IDN #{connection.origin.non_ascii_hostname} as #{hostname}" } if connection.origin.non_ascii_hostname
-
-
35
hostname = @resolver.generate_candidates(hostname).each do |name|
-
105
@queries[name.to_s] = connection
-
end.first.to_s
-
else
-
20
@queries[hostname] = connection
-
end
-
55
log { "resolver: query #{FAMILY_TYPES[RECORD_TYPES[@family]]} for #{hostname}" }
-
-
begin
-
55
request = build_request(hostname)
-
55
request.on(:response, &method(:on_response).curry(2)[request])
-
55
request.on(:promise, &method(:on_promise))
-
55
@requests[request] = hostname
-
55
resolver_connection.send(request)
-
55
@connections << connection
-
rescue ResolveError, Resolv::DNS::EncodeError => e
-
reset_hostname(hostname)
-
emit_resolve_error(connection, connection.origin.host, e)
-
end
-
end
-
-
23
def on_response(request, response)
-
55
response.raise_for_status
-
rescue StandardError => e
-
5
hostname = @requests.delete(request)
-
5
connection = reset_hostname(hostname)
-
5
emit_resolve_error(connection, connection.origin.host, e)
-
else
-
# @type var response: HTTPX::Response
-
50
parse(request, response)
-
ensure
-
55
@requests.delete(request)
-
end
-
-
23
def on_promise(_, stream)
-
log(level: 2) { "#{stream.id}: refusing stream!" }
-
stream.refuse
-
end
-
-
23
def parse(request, response)
-
50
code, result = decode_response_body(response)
-
-
50
case code
-
when :ok
-
15
parse_addresses(result, request)
-
when :no_domain_found
-
# Indicates no such domain was found.
-
-
30
host = @requests.delete(request)
-
30
connection = reset_hostname(host, reset_candidates: false)
-
-
30
unless @queries.value?(connection)
-
10
emit_resolve_error(connection)
-
10
return
-
end
-
-
20
resolve
-
when :dns_error
-
host = @requests.delete(request)
-
connection = reset_hostname(host)
-
-
emit_resolve_error(connection)
-
when :decode_error
-
5
host = @requests.delete(request)
-
5
connection = reset_hostname(host)
-
5
emit_resolve_error(connection, connection.origin.host, result)
-
end
-
end
-
-
23
def parse_addresses(answers, request)
-
15
if answers.empty?
-
# no address found, eliminate candidates
-
host = @requests.delete(request)
-
connection = reset_hostname(host)
-
emit_resolve_error(connection)
-
return
-
-
else
-
35
answers = answers.group_by { |answer| answer["name"] }
-
15
answers.each do |hostname, addresses|
-
20
addresses = addresses.flat_map do |address|
-
20
if address.key?("alias")
-
5
alias_address = answers[address["alias"]]
-
5
if alias_address.nil?
-
reset_hostname(address["name"])
-
if catch(:coalesced) { early_resolve(connection, hostname: address["alias"]) }
-
@connections.delete(connection)
-
else
-
resolve(connection, address["alias"])
-
return # rubocop:disable Lint/NonLocalExitFromIterator
-
end
-
else
-
5
alias_address
-
end
-
else
-
15
address
-
end
-
end.compact
-
20
next if addresses.empty?
-
-
20
hostname.delete_suffix!(".") if hostname.end_with?(".")
-
20
connection = reset_hostname(hostname, reset_candidates: false)
-
20
next unless connection # probably a retried query for which there's an answer
-
-
15
@connections.delete(connection)
-
-
# eliminate other candidates
-
45
@queries.delete_if { |_, conn| connection == conn }
-
-
15
Resolver.cached_lookup_set(hostname, @family, addresses) if @resolver_options[:cache]
-
30
emit_addresses(connection, @family, addresses.map { |addr| addr["data"] })
-
end
-
end
-
15
return if @connections.empty?
-
-
resolve
-
end
-
-
23
def build_request(hostname)
-
50
uri = @uri.dup
-
50
rklass = @options.request_class
-
50
payload = Resolver.encode_dns_query(hostname, type: @record_type)
-
-
50
if @resolver_options[:use_get]
-
5
params = URI.decode_www_form(uri.query.to_s)
-
5
params << ["type", FAMILY_TYPES[@record_type]]
-
5
params << ["dns", Base64.urlsafe_encode64(payload, padding: false)]
-
5
uri.query = URI.encode_www_form(params)
-
5
request = rklass.new("GET", uri, @options)
-
else
-
45
request = rklass.new("POST", uri, @options.merge(body: [payload]))
-
45
request.headers["content-type"] = "application/dns-message"
-
end
-
50
request.headers["accept"] = "application/dns-message"
-
50
request
-
end
-
-
23
def decode_response_body(response)
-
45
case response.headers["content-type"]
-
when "application/dns-udpwireformat",
-
"application/dns-message"
-
45
Resolver.decode_dns_answer(response.to_s)
-
else
-
raise Error, "unsupported DNS mime-type (#{response.headers["content-type"]})"
-
end
-
end
-
-
23
def reset_hostname(hostname, reset_candidates: true)
-
60
connection = @queries.delete(hostname)
-
-
60
return connection unless connection && reset_candidates
-
-
# eliminate other candidates
-
30
candidates = @queries.select { |_, conn| connection == conn }.keys
-
30
@queries.delete_if { |h, _| candidates.include?(h) }
-
-
10
connection
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
23
require "resolv"
-
-
23
module HTTPX
-
23
class Resolver::Multi
-
23
include Callbacks
-
23
using ArrayExtensions::FilterMap
-
-
23
attr_reader :resolvers
-
-
23
def initialize(resolver_type, options)
-
579
@options = options
-
579
@resolver_options = @options.resolver_options
-
-
579
@resolvers = options.ip_families.map do |ip_family|
-
579
resolver = resolver_type.new(ip_family, options)
-
579
resolver.on(:resolve, &method(:on_resolver_connection))
-
579
resolver.on(:error, &method(:on_resolver_error))
-
737
resolver.on(:close) { on_resolver_close(resolver) }
-
579
resolver
-
end
-
-
579
@errors = Hash.new { |hs, k| hs[k] = [] }
-
end
-
-
23
def closed?
-
3692973
@resolvers.all?(&:closed?)
-
end
-
-
23
def timeout
-
3690700
@resolvers.filter_map(&:timeout).min
-
end
-
-
23
def close
-
1813
@resolvers.each(&:close)
-
end
-
-
23
def connections
-
8988
@resolvers.filter_map { |r| r.resolver_connection if r.respond_to?(:resolver_connection) }
-
end
-
-
23
def early_resolve(connection)
-
4919
hostname = connection.origin.host
-
4919
addresses = @resolver_options[:cache] && (connection.addresses || HTTPX::Resolver.nolookup_resolve(hostname))
-
4919
return unless addresses
-
-
4755
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.
-
9486
resolver = @resolvers.find { |r| r.family == family } || @resolvers.first
-
-
4743
next unless resolver # this should ever happen
-
-
# it does not matter which resolver it is, as early-resolve code is shared.
-
4743
resolver.emit_addresses(connection, family, addrs, true)
-
end
-
end
-
-
23
private
-
-
23
def on_resolver_connection(connection)
-
4922
emit(:resolve, connection)
-
end
-
-
23
def on_resolver_error(connection, error)
-
140
emit(:error, connection, error)
-
end
-
-
23
def on_resolver_close(resolver)
-
158
emit(:close, resolver)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
23
require "resolv"
-
-
23
module HTTPX
-
23
class Resolver::Native < Resolver::Resolver
-
23
extend Forwardable
-
23
using URIExtensions
-
-
1
DEFAULTS = {
-
22
nameserver: nil,
-
**Resolv::DNS::Config.default_config_hash,
-
packet_size: 512,
-
timeouts: Resolver::RESOLVE_TIMEOUT,
-
}.freeze
-
-
23
DNS_PORT = 53
-
-
23
def_delegator :@connections, :empty?
-
-
23
attr_reader :state
-
-
23
def initialize(family, options)
-
539
super
-
539
@ns_index = 0
-
539
@resolver_options = DEFAULTS.merge(@options.resolver_options)
-
539
@socket_type = @resolver_options.fetch(:socket_type, :udp)
-
539
@nameserver = if (nameserver = @resolver_options[:nameserver])
-
534
nameserver = nameserver[family] if nameserver.is_a?(Hash)
-
534
Array(nameserver)
-
end
-
539
@ndots = @resolver_options.fetch(:ndots, 1)
-
1617
@search = Array(@resolver_options[:search]).map { |srch| srch.scan(/[^.]+/) }
-
539
@_timeouts = Array(@resolver_options[:timeouts])
-
1698
@timeouts = Hash.new { |timeouts, host| timeouts[host] = @_timeouts.dup }
-
539
@connections = []
-
539
@queries = {}
-
539
@read_buffer = "".b
-
539
@write_buffer = Buffer.new(@resolver_options[:packet_size])
-
539
@state = :idle
-
end
-
-
23
def close
-
1971
transition(:closed)
-
end
-
-
23
def closed?
-
3693089
@state == :closed
-
end
-
-
23
def to_io
-
1019
@io.to_io
-
end
-
-
23
def call
-
753
case @state
-
when :open
-
835
consume
-
end
-
78
nil
-
rescue Errno::EHOSTUNREACH => e
-
15
@ns_index += 1
-
15
nameserver = @nameserver
-
15
if nameserver && @ns_index < nameserver.size
-
10
log { "resolver: failed resolving on nameserver #{@nameserver[@ns_index - 1]} (#{e.message})" }
-
10
transition(:idle)
-
else
-
5
handle_error(e)
-
end
-
rescue NativeResolveError => e
-
94
handle_error(e)
-
end
-
-
23
def interests
-
1772281
case @state
-
when :idle
-
3052
transition(:open)
-
when :closed
-
259
transition(:idle)
-
259
transition(:open)
-
end
-
-
1772525
calculate_interests
-
end
-
-
23
def <<(connection)
-
274
if @nameserver.nil?
-
5
ex = ResolveError.new("No available nameserver")
-
5
ex.set_backtrace(caller)
-
5
connection.force_reset
-
5
throw(:resolve_error, ex)
-
else
-
269
@connections << connection
-
269
resolve
-
end
-
end
-
-
23
def timeout
-
3690700
return if @connections.empty?
-
-
3702
@start_timeout = Utils.now
-
3702
hosts = @queries.keys
-
3702
@timeouts.values_at(*hosts).reject(&:empty?).map(&:first).min
-
end
-
-
23
def handle_socket_timeout(interval)
-
82
do_retry(interval)
-
end
-
-
23
private
-
-
23
def calculate_interests
-
1774066
return :w unless @write_buffer.empty?
-
-
1772865
return :r unless @queries.empty?
-
-
178
nil
-
end
-
-
23
def consume
-
820
dread if calculate_interests == :r
-
721
do_retry
-
721
dwrite if calculate_interests == :w
-
end
-
-
23
def do_retry(loop_time = nil)
-
803
return if @queries.empty? || !@start_timeout
-
-
619
loop_time ||= Utils.elapsed_time(@start_timeout)
-
-
619
query = @queries.first
-
-
619
return unless query
-
-
619
h, connection = query
-
619
host = connection.origin.host
-
619
timeout = (@timeouts[host][0] -= loop_time)
-
-
619
return unless timeout <= 0
-
-
62
@timeouts[host].shift
-
-
62
if !@timeouts[host].empty?
-
37
log { "resolver: timeout after #{timeout}s, retry(#{@timeouts[host].first}) #{host}..." }
-
37
resolve(connection)
-
25
elsif @ns_index + 1 < @nameserver.size
-
# try on the next nameserver
-
5
@ns_index += 1
-
5
log { "resolver: failed resolving #{host} on nameserver #{@nameserver[@ns_index - 1]} (timeout error)" }
-
5
transition(:idle)
-
5
resolve(connection)
-
else
-
-
20
@timeouts.delete(host)
-
20
reset_hostname(h, reset_candidates: false)
-
-
20
return unless @queries.empty?
-
-
5
@connections.delete(connection)
-
# This loop_time passed to the exception is bogus. Ideally we would pass the total
-
# resolve timeout, including from the previous retries.
-
5
raise ResolveTimeoutError.new(loop_time, "Timed out while resolving #{connection.origin.host}")
-
end
-
end
-
-
23
def dread(wsize = @resolver_options[:packet_size])
-
506
loop do
-
750
wsize = @large_packet.capacity if @large_packet
-
-
750
siz = @io.read(wsize, @read_buffer)
-
-
750
unless siz
-
ex = EOFError.new("descriptor closed")
-
ex.set_backtrace(caller)
-
raise ex
-
end
-
-
750
return unless siz.positive?
-
-
516
if @socket_type == :tcp
-
# packet may be incomplete, need to keep draining from the socket
-
25
if @large_packet
-
# large packet buffer already exists, continue pumping
-
10
@large_packet << @read_buffer
-
-
10
next unless @large_packet.full?
-
-
10
parse(@large_packet.to_s)
-
10
@socket_type = @resolver_options.fetch(:socket_type, :udp)
-
10
@large_packet = nil
-
10
transition(:idle)
-
10
transition(:open)
-
10
return
-
else
-
15
size = @read_buffer[0, 2].unpack1("n")
-
15
buffer = @read_buffer.byteslice(2..-1)
-
-
15
if size > @read_buffer.bytesize
-
# only do buffer logic if it's worth it, and the whole packet isn't here already
-
10
@large_packet = Buffer.new(size)
-
10
@large_packet << buffer
-
-
10
next
-
else
-
5
parse(buffer)
-
end
-
end
-
else # udp
-
491
parse(@read_buffer)
-
end
-
-
397
return if @state == :closed
-
end
-
end
-
-
23
def dwrite
-
553
loop do
-
1106
return if @write_buffer.empty?
-
-
553
siz = @io.write(@write_buffer)
-
-
553
unless siz
-
ex = EOFError.new("descriptor closed")
-
ex.set_backtrace(caller)
-
raise ex
-
end
-
-
553
return unless siz.positive?
-
-
553
return if @state == :closed
-
end
-
end
-
-
23
def parse(buffer)
-
506
code, result = Resolver.decode_dns_answer(buffer)
-
-
449
case code
-
when :ok
-
185
parse_addresses(result)
-
when :no_domain_found
-
# Indicates no such domain was found.
-
296
hostname, connection = @queries.first
-
296
reset_hostname(hostname, reset_candidates: false)
-
-
296
unless @queries.value?(connection)
-
74
@connections.delete(connection)
-
74
raise NativeResolveError.new(connection, connection.origin.host, "name or service not known")
-
end
-
-
222
resolve
-
when :message_truncated
-
# TODO: what to do if it's already tcp??
-
10
return if @socket_type == :tcp
-
-
10
@socket_type = :tcp
-
-
10
hostname, _ = @queries.first
-
10
reset_hostname(hostname)
-
10
transition(:closed)
-
when :dns_error
-
10
hostname, connection = @queries.first
-
10
reset_hostname(hostname)
-
10
@connections.delete(connection)
-
10
ex = NativeResolveError.new(connection, connection.origin.host, "unknown DNS error (error code #{result})")
-
10
raise ex
-
when :decode_error
-
5
hostname, connection = @queries.first
-
5
reset_hostname(hostname)
-
5
@connections.delete(connection)
-
5
ex = NativeResolveError.new(connection, connection.origin.host, result.message)
-
5
ex.set_backtrace(result.backtrace)
-
5
raise ex
-
end
-
end
-
-
23
def parse_addresses(addresses)
-
185
if addresses.empty?
-
# no address found, eliminate candidates
-
5
hostname, connection = @queries.first
-
5
reset_hostname(hostname)
-
5
@connections.delete(connection)
-
5
raise NativeResolveError.new(connection, connection.origin.host)
-
else
-
180
address = addresses.first
-
180
name = address["name"]
-
-
180
connection = @queries.delete(name)
-
-
180
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
-
-
180
if address.key?("alias") # CNAME
-
# clean up intermediate queries
-
16
@timeouts.delete(name) unless connection.origin.host == name
-
-
32
if catch(:coalesced) { early_resolve(connection, hostname: address["alias"]) }
-
1
@connections.delete(connection)
-
else
-
15
resolve(connection, address["alias"])
-
15
return
-
end
-
else
-
164
reset_hostname(name, connection: connection)
-
164
@timeouts.delete(connection.origin.host)
-
164
@connections.delete(connection)
-
164
Resolver.cached_lookup_set(connection.origin.host, @family, addresses) if @resolver_options[:cache]
-
680
emit_addresses(connection, @family, addresses.map { |addr| addr["data"] })
-
end
-
end
-
160
return emit(:close) if @connections.empty?
-
-
2
resolve
-
end
-
-
23
def resolve(connection = @connections.first, hostname = nil)
-
560
raise Error, "no URI to resolve" unless connection
-
-
560
return unless @write_buffer.empty?
-
-
558
hostname ||= @queries.key(connection)
-
-
558
if hostname.nil?
-
279
hostname = connection.origin.host
-
279
log { "resolver: resolve IDN #{connection.origin.non_ascii_hostname} as #{hostname}" } if connection.origin.non_ascii_hostname
-
-
279
hostname = generate_candidates(hostname).each do |name|
-
996
@queries[name] = connection
-
end.first
-
else
-
252
@queries[hostname] = connection
-
end
-
558
log { "resolver: query #{@record_type.name.split("::").last} for #{hostname}" }
-
begin
-
558
@write_buffer << encode_dns_query(hostname)
-
rescue Resolv::DNS::EncodeError => e
-
emit_resolve_error(connection, hostname, e)
-
end
-
end
-
-
23
def encode_dns_query(hostname)
-
558
message_id = Resolver.generate_id
-
558
msg = Resolver.encode_dns_query(hostname, type: @record_type, message_id: message_id)
-
558
msg[0, 2] = [msg.size, message_id].pack("nn") if @socket_type == :tcp
-
558
msg
-
end
-
-
23
def generate_candidates(name)
-
279
return [name] if name.end_with?(".")
-
-
279
candidates = []
-
279
name_parts = name.scan(/[^.]+/)
-
279
candidates = [name] if @ndots <= name_parts.size - 1
-
837
candidates.concat(@search.map { |domain| [*name_parts, *domain].join(".") })
-
279
fname = "#{name}."
-
279
candidates << fname unless candidates.include?(fname)
-
-
279
candidates
-
end
-
-
23
def build_socket
-
514
ip, port = @nameserver[@ns_index]
-
514
port ||= DNS_PORT
-
-
455
case @socket_type
-
when :udp
-
499
log { "resolver: server: udp://#{ip}:#{port}..." }
-
499
UDP.new(ip, port, @options)
-
when :tcp
-
15
log { "resolver: server: tcp://#{ip}:#{port}..." }
-
15
origin = URI("tcp://#{ip}:#{port}")
-
15
TCP.new(origin, [ip], @options)
-
end
-
end
-
-
23
def transition(nextstate)
-
5052
case nextstate
-
when :idle
-
284
if @io
-
284
@io.close
-
284
@io = nil
-
end
-
284
@timeouts.clear
-
when :open
-
3321
return unless @state == :idle
-
-
3321
@io ||= build_socket
-
-
3321
@io.connect
-
3321
return unless @io.connected?
-
-
514
resolve if @queries.empty? && !@connections.empty?
-
when :closed
-
1981
return unless @state == :open
-
-
465
@io.close if @io
-
465
@start_timeout = nil
-
465
@write_buffer.clear
-
465
@read_buffer.clear
-
end
-
1263
@state = nextstate
-
end
-
-
23
def handle_error(error)
-
99
if error.respond_to?(:connection) &&
-
error.respond_to?(:host)
-
94
emit_resolve_error(error.connection, error.host, error)
-
else
-
5
@queries.each do |host, connection|
-
20
emit_resolve_error(connection, host, error)
-
end
-
end
-
end
-
-
23
def reset_hostname(hostname, connection: @queries.delete(hostname), reset_candidates: true)
-
510
@timeouts.delete(hostname)
-
510
@timeouts.delete(hostname)
-
-
510
return unless connection && reset_candidates
-
-
# eliminate other candidates
-
776
candidates = @queries.select { |_, conn| connection == conn }.keys
-
776
@queries.delete_if { |h, _| candidates.include?(h) }
-
# reset timeouts
-
789
@timeouts.delete_if { |h, _| candidates.include?(h) }
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "resolv"
-
23
require "ipaddr"
-
-
23
module HTTPX
-
23
class Resolver::Resolver
-
23
include Callbacks
-
23
include Loggable
-
-
23
using ArrayExtensions::Intersect
-
-
1
RECORD_TYPES = {
-
22
Socket::AF_INET6 => Resolv::DNS::Resource::IN::AAAA,
-
Socket::AF_INET => Resolv::DNS::Resource::IN::A,
-
}.freeze
-
-
1
FAMILY_TYPES = {
-
22
Resolv::DNS::Resource::IN::AAAA => "AAAA",
-
Resolv::DNS::Resource::IN::A => "A",
-
}.freeze
-
-
23
class << self
-
23
def multi?
-
579
true
-
end
-
end
-
-
23
attr_reader :family
-
-
23
attr_writer :pool
-
-
23
def initialize(family, options)
-
600
@family = family
-
600
@record_type = RECORD_TYPES[family]
-
600
@options = Options.new(options)
-
end
-
-
23
def close; end
-
-
23
alias_method :terminate, :close
-
-
23
def closed?
-
true
-
end
-
-
23
def empty?
-
true
-
end
-
-
23
def emit_addresses(connection, family, addresses, early_resolve = false)
-
4968
addresses.map! do |address|
-
9797
address.is_a?(IPAddr) ? address : IPAddr.new(address.to_s)
-
end
-
-
# double emission check, but allow early resolution to work
-
4968
return if !early_resolve && connection.addresses && !addresses.intersect?(connection.addresses)
-
-
5027
log { "resolver: answer #{FAMILY_TYPES[RECORD_TYPES[family]]} #{connection.origin.host}: #{addresses.inspect}" }
-
4968
if @pool && # if triggered by early resolve, pool may not be here yet
-
!connection.io &&
-
connection.options.ip_families.size > 1 &&
-
family == Socket::AF_INET &&
-
addresses.first.to_s != connection.origin.host.to_s
-
log { "resolver: A response, applying resolution delay..." }
-
@pool.after(0.05) do
-
unless connection.state == :closed ||
-
# double emission check
-
(connection.addresses && addresses.intersect?(connection.addresses))
-
emit_resolved_connection(connection, addresses, early_resolve)
-
end
-
end
-
else
-
4968
emit_resolved_connection(connection, addresses, early_resolve)
-
end
-
end
-
-
23
private
-
-
23
def emit_resolved_connection(connection, addresses, early_resolve)
-
begin
-
4968
connection.addresses = addresses
-
-
4932
emit(:resolve, connection)
-
24
rescue StandardError => e
-
36
if early_resolve
-
30
connection.force_reset
-
30
throw(:resolve_error, e)
-
else
-
6
emit(:error, connection, e)
-
end
-
end
-
end
-
-
23
def early_resolve(connection, hostname: connection.origin.host)
-
16
addresses = @resolver_options[:cache] && (connection.addresses || HTTPX::Resolver.nolookup_resolve(hostname))
-
-
16
return unless addresses
-
-
5
addresses = addresses.select { |addr| addr.family == @family }
-
-
1
return if addresses.empty?
-
-
1
emit_addresses(connection, @family, addresses, true)
-
end
-
-
23
def emit_resolve_error(connection, hostname = connection.origin.host, ex = nil)
-
145
emit(:error, connection, resolve_error(hostname, ex))
-
end
-
-
23
def resolve_error(hostname, ex = nil)
-
145
return ex if ex.is_a?(ResolveError) || ex.is_a?(ResolveTimeoutError)
-
-
50
message = ex ? ex.message : "Can't resolve #{hostname}"
-
50
error = ResolveError.new(message)
-
50
error.set_backtrace(ex ? ex.backtrace : caller)
-
50
error
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
23
require "resolv"
-
-
23
module HTTPX
-
23
class Resolver::System < Resolver::Resolver
-
23
using URIExtensions
-
23
extend Forwardable
-
-
23
RESOLV_ERRORS = [Resolv::ResolvError,
-
Resolv::DNS::Requester::RequestError,
-
Resolv::DNS::EncodeError,
-
Resolv::DNS::DecodeError].freeze
-
-
23
DONE = 1
-
23
ERROR = 2
-
-
23
class << self
-
23
def multi?
-
21
false
-
end
-
end
-
-
23
attr_reader :state
-
-
23
def_delegator :@connections, :empty?
-
-
23
def initialize(options)
-
21
super(nil, options)
-
21
@resolver_options = @options.resolver_options
-
21
resolv_options = @resolver_options.dup
-
21
timeouts = resolv_options.delete(:timeouts) || Resolver::RESOLVE_TIMEOUT
-
21
@_timeouts = Array(timeouts)
-
42
@timeouts = Hash.new { |tims, host| tims[host] = @_timeouts.dup }
-
21
resolv_options.delete(:cache)
-
21
@connections = []
-
21
@queries = []
-
21
@ips = []
-
21
@pipe_mutex = Thread::Mutex.new
-
21
@state = :idle
-
end
-
-
23
def resolvers
-
42
return enum_for(__method__) unless block_given?
-
-
21
yield self
-
end
-
-
23
def connections
-
EMPTY
-
end
-
-
23
def close
-
21
transition(:closed)
-
end
-
-
23
def closed?
-
63
@state == :closed
-
end
-
-
23
def to_io
-
21
@pipe_read.to_io
-
end
-
-
23
def call
-
21
case @state
-
when :open
-
21
consume
-
end
-
nil
-
end
-
-
23
def interests
-
21
return if @queries.empty?
-
-
21
:r
-
end
-
-
23
def timeout
-
21
return unless @queries.empty?
-
-
_, connection = @queries.first
-
-
return unless connection
-
-
@timeouts[connection.origin.host].first
-
end
-
-
23
def <<(connection)
-
21
@connections << connection
-
21
resolve
-
end
-
-
23
def handle_socket_timeout(interval)
-
error = HTTPX::ResolveTimeoutError.new(interval, "timed out while waiting on select")
-
error.set_backtrace(caller)
-
on_error(error)
-
end
-
-
23
private
-
-
23
def transition(nextstate)
-
42
case nextstate
-
when :idle
-
@timeouts.clear
-
when :open
-
21
return unless @state == :idle
-
-
21
@pipe_read, @pipe_write = ::IO.pipe
-
when :closed
-
21
return unless @state == :open
-
-
21
@pipe_write.close
-
21
@pipe_read.close
-
end
-
42
@state = nextstate
-
end
-
-
23
def consume
-
42
return if @connections.empty?
-
-
63
while @pipe_read.ready? && (event = @pipe_read.getbyte)
-
21
case event
-
when DONE
-
20
*pair, addrs = @pipe_mutex.synchronize { @ips.pop }
-
10
@queries.delete(pair)
-
-
10
family, connection = pair
-
10
emit_addresses(connection, family, addrs)
-
when ERROR
-
22
*pair, error = @pipe_mutex.synchronize { @ips.pop }
-
11
@queries.delete(pair)
-
-
11
family, connection = pair
-
11
emit_resolve_error(connection, connection.origin.host, error)
-
end
-
-
21
@connections.delete(connection) if @queries.empty?
-
end
-
-
42
return emit(:close, self) if @connections.empty?
-
-
21
resolve
-
end
-
-
23
def resolve(connection = @connections.first)
-
42
raise Error, "no URI to resolve" unless connection
-
42
return unless @queries.empty?
-
-
21
hostname = connection.origin.host
-
21
scheme = connection.origin.scheme
-
21
log { "resolver: resolve IDN #{connection.origin.non_ascii_hostname} as #{hostname}" } if connection.origin.non_ascii_hostname
-
-
21
transition(:open)
-
-
21
connection.options.ip_families.each do |family|
-
21
@queries << [family, connection]
-
end
-
21
async_resolve(connection, hostname, scheme)
-
21
consume
-
end
-
-
23
def async_resolve(connection, hostname, scheme)
-
21
families = connection.options.ip_families
-
21
log { "resolver: query for #{hostname}" }
-
21
timeouts = @timeouts[connection.origin.host]
-
21
resolve_timeout = timeouts.first
-
-
21
Thread.start do
-
21
Thread.current.report_on_exception = false
-
begin
-
21
addrs = if resolve_timeout
-
-
21
Timeout.timeout(resolve_timeout) do
-
21
__addrinfo_resolve(hostname, scheme)
-
end
-
else
-
__addrinfo_resolve(hostname, scheme)
-
end
-
10
addrs = addrs.sort_by(&:afamily).group_by(&:afamily)
-
10
families.each do |family|
-
10
addresses = addrs[family]
-
10
next unless addresses
-
-
10
addresses.map!(&:ip_address)
-
10
addresses.uniq!
-
10
@pipe_mutex.synchronize do
-
10
@ips.unshift([family, connection, addresses])
-
10
@pipe_write.putc(DONE) unless @pipe_write.closed?
-
end
-
end
-
rescue StandardError => e
-
11
if e.is_a?(Timeout::Error)
-
1
timeouts.shift
-
1
retry unless timeouts.empty?
-
1
e = ResolveTimeoutError.new(resolve_timeout, e.message)
-
1
e.set_backtrace(e.backtrace)
-
end
-
11
@pipe_mutex.synchronize do
-
11
families.each do |family|
-
11
@ips.unshift([family, connection, e])
-
11
@pipe_write.putc(ERROR) unless @pipe_write.closed?
-
end
-
end
-
end
-
end
-
end
-
-
23
def __addrinfo_resolve(host, scheme)
-
21
Addrinfo.getaddrinfo(host, scheme, Socket::AF_UNSPEC, Socket::SOCK_STREAM)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "objspace"
-
23
require "stringio"
-
23
require "tempfile"
-
23
require "fileutils"
-
23
require "forwardable"
-
-
23
module HTTPX
-
# Defines a HTTP response is handled internally, with a few properties exposed as attributes.
-
#
-
# It delegates the following methods to the corresponding HTTPX::Request:
-
#
-
# * HTTPX::Request#uri
-
# * HTTPX::Request#peer_address
-
#
-
# It implements (indirectly, via the +body+) the IO write protocol to internally buffer payloads.
-
#
-
# It implements the IO reader protocol in order for users to buffer/stream it, acts as an enumerable
-
# (of payload chunks).
-
#
-
23
class Response
-
23
extend Forwardable
-
23
include Callbacks
-
-
# the HTTP response status code
-
23
attr_reader :status
-
-
# an HTTPX::Headers object containing the response HTTP headers.
-
23
attr_reader :headers
-
-
# a HTTPX::Response::Body object wrapping the response body. The following methods are delegated to it:
-
#
-
# * HTTPX::Response::Body#to_s
-
# * HTTPX::Response::Body#to_str
-
# * HTTPX::Response::Body#read
-
# * HTTPX::Response::Body#copy_to
-
# * HTTPX::Response::Body#close
-
23
attr_reader :body
-
-
# The HTTP protocol version used to fetch the response.
-
23
attr_reader :version
-
-
# returns the response body buffered in a string.
-
23
def_delegator :@body, :to_s
-
-
23
def_delegator :@body, :to_str
-
-
# implements the IO reader +#read+ interface.
-
23
def_delegator :@body, :read
-
-
# copies the response body to a different location.
-
23
def_delegator :@body, :copy_to
-
-
# closes the body.
-
23
def_delegator :@body, :close
-
-
# the corresponding request uri.
-
23
def_delegator :@request, :uri
-
-
# the IP address of the peer server.
-
23
def_delegator :@request, :peer_address
-
-
# inits the instance with the corresponding +request+ to this response, an the
-
# response HTTP +status+, +version+ and HTTPX::Headers instance of +headers+.
-
23
def initialize(request, status, version, headers)
-
6343
@request = request
-
6343
@options = request.options
-
6343
@version = version
-
6343
@status = Integer(status)
-
6343
@headers = @options.headers_class.new(headers)
-
6343
@body = @options.response_body_class.new(self, @options)
-
6343
@finished = complete?
-
6343
@content_type = nil
-
end
-
-
# merges headers defined in +h+ into the response headers.
-
23
def merge_headers(h)
-
167
@headers = @headers.merge(h)
-
end
-
-
# writes +data+ chunk into the response body.
-
23
def <<(data)
-
8239
@body.write(data)
-
end
-
-
# returns the HTTPX::ContentType for the response, as per what's declared in the content-type header.
-
#
-
# response.content_type #=> #<HTTPX::ContentType:xxx @header_value="text/plain">
-
# response.content_type.mime_type #=> "text/plain"
-
23
def content_type
-
6568
@content_type ||= ContentType.new(@headers["content-type"])
-
end
-
-
# returns whether the response has been fully fetched.
-
23
def finished?
-
3361
@finished
-
end
-
-
# marks the response as finished, freezes the headers.
-
23
def finish!
-
3279
@finished = true
-
3279
@headers.freeze
-
end
-
-
# returns whether the response contains body payload.
-
23
def bodyless?
-
6343
@request.verb == "HEAD" ||
-
@status < 200 || # informational response
-
@status == 204 ||
-
@status == 205 ||
-
@status == 304 || begin
-
6010
content_length = @headers["content-length"]
-
6010
return false if content_length.nil?
-
-
5202
content_length == "0"
-
end
-
end
-
-
23
def complete?
-
6343
bodyless? || (@request.verb == "CONNECT" && @status == 200)
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<Response:#{object_id} " \
-
skipped
"HTTP/#{version} " \
-
skipped
"@status=#{@status} " \
-
skipped
"@headers=#{@headers} " \
-
skipped
"@body=#{@body.bytesize}>"
-
skipped
end
-
skipped
# :nocov:
-
-
# returns an instance of HTTPX::HTTPError if the response has a 4xx or 5xx
-
# status code, or nothing.
-
#
-
# ok_response.error #=> nil
-
# not_found_response.error #=> HTTPX::HTTPError instance, status 404
-
23
def error
-
412
return if @status < 400
-
-
41
HTTPError.new(self)
-
end
-
-
# it raises the exception returned by +error+, or itself otherwise.
-
#
-
# ok_response.raise_for_status #=> ok_response
-
# not_found_response.raise_for_status #=> raises HTTPX::HTTPError exception
-
23
def raise_for_status
-
382
return self unless (err = error)
-
-
29
raise err
-
end
-
-
# decodes the response payload into a ruby object **if** the payload is valid json.
-
#
-
# response.json #≈> { "foo" => "bar" } for "{\"foo\":\"bar\"}" payload
-
# response.json(symbolize_names: true) #≈> { foo: "bar" } for "{\"foo\":\"bar\"}" payload
-
23
def json(*args)
-
57
decode(Transcoder::JSON, *args)
-
end
-
-
# decodes the response payload into a ruby object **if** the payload is valid
-
# "application/x-www-urlencoded" or "multipart/form-data".
-
23
def form
-
48
decode(Transcoder::Form)
-
end
-
-
# decodes the response payload into a Nokogiri::XML::Node object **if** the payload is valid
-
# "application/xml" (requires the "nokogiri" gem).
-
23
def xml
-
6
decode(Transcoder::Xml)
-
end
-
-
23
private
-
-
# decodes the response payload using the given +transcoder+, which implements the decoding logic.
-
#
-
# +transcoder+ must implement the internal transcoder API, i.e. respond to <tt>decode(HTTPX::Response response)</tt>,
-
# which returns a decoder which responds to <tt>call(HTTPX::Response response, **kwargs)</tt>
-
23
def decode(transcoder, *args)
-
# TODO: check if content-type is a valid format, i.e. "application/json" for json parsing
-
-
111
decoder = transcoder.decode(self)
-
-
99
raise Error, "no decoder available for \"#{transcoder}\"" unless decoder
-
-
99
@body.rewind
-
-
99
decoder.call(self, *args)
-
end
-
end
-
-
# Helper class which decodes the HTTP "content-type" header.
-
23
class ContentType
-
23
MIME_TYPE_RE = %r{^([^/]+/[^;]+)(?:$|;)}.freeze
-
23
CHARSET_RE = /;\s*charset=([^;]+)/i.freeze
-
-
23
def initialize(header_value)
-
6538
@header_value = header_value
-
end
-
-
# returns the mime type declared in the header.
-
#
-
# ContentType.new("application/json; charset=utf-8").mime_type #=> "application/json"
-
23
def mime_type
-
111
return @mime_type if defined?(@mime_type)
-
-
81
m = @header_value.to_s[MIME_TYPE_RE, 1]
-
81
m && @mime_type = m.strip.downcase
-
end
-
-
# returns the charset declared in the header.
-
#
-
# ContentType.new("application/json; charset=utf-8").charset #=> "utf-8"
-
# ContentType.new("text/plain").charset #=> nil
-
23
def charset
-
6457
return @charset if defined?(@charset)
-
-
6457
m = @header_value.to_s[CHARSET_RE, 1]
-
6457
m && @charset = m.strip.delete('"')
-
end
-
end
-
-
# Wraps an error which has happened while processing an HTTP Request. It has partial
-
# public API parity with HTTPX::Response, so users should rely on it to infer whether
-
# the returned response is one or the other.
-
#
-
# response = HTTPX.get("https://some-domain/path") #=> response is HTTPX::Response or HTTPX::ErrorResponse
-
# response.raise_for_status #=> raises if it wraps an error
-
23
class ErrorResponse
-
23
include Loggable
-
23
extend Forwardable
-
-
# the corresponding HTTPX::Request instance.
-
23
attr_reader :request
-
-
# the HTTPX::Response instance, when there is one (i.e. error happens fetching the response).
-
23
attr_reader :response
-
-
# the wrapped exception.
-
23
attr_reader :error
-
-
# the request uri
-
23
def_delegator :@request, :uri
-
-
# the IP address of the peer server.
-
23
def_delegator :@request, :peer_address
-
-
23
def initialize(request, error, options)
-
818
@request = request
-
818
@response = request.response if request.response.is_a?(Response)
-
818
@error = error
-
818
@options = Options.new(options)
-
818
log_exception(@error)
-
end
-
-
# returns the exception full message.
-
23
def to_s
-
7
@error.full_message(highlight: false)
-
end
-
-
# closes the error resources.
-
23
def close
-
18
@response.close if @response && @response.respond_to?(:close)
-
end
-
-
# always true for error responses.
-
23
def finished?
-
6
true
-
end
-
-
# raises the wrapped exception.
-
23
def raise_for_status
-
58
raise @error
-
end
-
-
# buffers lost chunks to error response
-
23
def <<(data)
-
6
@response << data
-
end
-
end
-
end
-
-
23
require_relative "response/body"
-
23
require_relative "response/buffer"
-
23
require_relative "pmatch_extensions" if RUBY_VERSION >= "2.7.0"
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
# Implementation of the HTTP Response body as a buffer which implements the IO writer protocol
-
# (for buffering the response payload), the IO reader protocol (for consuming the response payload),
-
# and can be iterated over (via #each, which yields the payload in chunks).
-
23
class Response::Body
-
# the payload encoding (i.e. "utf-8", "ASCII-8BIT")
-
23
attr_reader :encoding
-
-
# Array of encodings contained in the response "content-encoding" header.
-
23
attr_reader :encodings
-
-
# initialized with the corresponding HTTPX::Response +response+ and HTTPX::Options +options+.
-
23
def initialize(response, options)
-
6457
@response = response
-
6457
@headers = response.headers
-
6457
@options = options
-
6457
@window_size = options.window_size
-
6457
@encoding = response.content_type.charset || Encoding::BINARY
-
6457
@encodings = []
-
6457
@length = 0
-
6457
@buffer = nil
-
6457
@reader = nil
-
6457
@state = :idle
-
6457
initialize_inflaters
-
end
-
-
23
def initialize_dup(other)
-
24
super
-
-
24
@buffer = other.instance_variable_get(:@buffer).dup
-
end
-
-
23
def closed?
-
222
@state == :closed
-
end
-
-
# write the response payload +chunk+ into the buffer. Inflates the chunk when required
-
# and supported.
-
23
def write(chunk)
-
8110
return if @state == :closed
-
-
8110
return 0 if chunk.empty?
-
-
7820
chunk = decode_chunk(chunk)
-
-
7820
size = chunk.bytesize
-
6684
@length += size
-
7820
transition(:open)
-
7820
@buffer.write(chunk)
-
-
7820
@response.emit(:chunk_received, chunk)
-
7808
size
-
end
-
-
# reads a chunk from the payload (implementation of the IO reader protocol).
-
23
def read(*args)
-
123
return unless @buffer
-
-
123
unless @reader
-
81
rewind
-
81
@reader = @buffer
-
end
-
-
123
@reader.read(*args)
-
end
-
-
# size of the decoded response payload. May differ from "content-length" header if
-
# response was encoded over-the-wire.
-
23
def bytesize
-
133
@length
-
end
-
-
# yields the payload in chunks.
-
23
def each
-
36
return enum_for(__method__) unless block_given?
-
-
begin
-
24
if @buffer
-
24
rewind
-
68
while (chunk = @buffer.read(@window_size))
-
24
yield(chunk.force_encoding(@encoding))
-
end
-
end
-
ensure
-
24
close
-
end
-
end
-
-
# returns the declared filename in the "contennt-disposition" header, when present.
-
23
def filename
-
36
return unless @headers.key?("content-disposition")
-
-
30
Utils.get_filename(@headers["content-disposition"])
-
end
-
-
# returns the full response payload as a string.
-
23
def to_s
-
3227
return "".b unless @buffer
-
-
2991
@buffer.to_s
-
end
-
-
23
alias_method :to_str, :to_s
-
-
# whether the payload is empty.
-
23
def empty?
-
24
@length.zero?
-
end
-
-
# copies the payload to +dest+.
-
#
-
# body.copy_to("path/to/file")
-
# body.copy_to(Pathname.new("path/to/file"))
-
# body.copy_to(File.new("path/to/file"))
-
23
def copy_to(dest)
-
36
return unless @buffer
-
-
36
rewind
-
-
36
if dest.respond_to?(:path) && @buffer.respond_to?(:path)
-
6
FileUtils.mv(@buffer.path, dest.path)
-
else
-
30
::IO.copy_stream(@buffer, dest)
-
end
-
end
-
-
# closes/cleans the buffer, resets everything
-
23
def close
-
501
if @buffer
-
275
@buffer.close
-
275
@buffer = nil
-
end
-
501
@length = 0
-
501
transition(:closed)
-
end
-
-
23
def ==(other)
-
82
object_id == other.object_id || begin
-
82
if other.respond_to?(:read)
-
60
_with_same_buffer_pos { FileUtils.compare_stream(@buffer, other) }
-
else
-
52
to_s == other.to_s
-
end
-
end
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<HTTPX::Response::Body:#{object_id} " \
-
skipped
"@state=#{@state} " \
-
skipped
"@length=#{@length}>"
-
skipped
end
-
skipped
# :nocov:
-
-
# rewinds the response payload buffer.
-
23
def rewind
-
270
return unless @buffer
-
-
# in case there's some reading going on
-
270
@reader = nil
-
-
270
@buffer.rewind
-
end
-
-
23
private
-
-
# prepares inflaters for the advertised encodings in "content-encoding" header.
-
23
def initialize_inflaters
-
6457
@inflaters = nil
-
-
6457
return unless @headers.key?("content-encoding")
-
-
132
return unless @options.decompress_response_body
-
-
120
@inflaters = @headers.get("content-encoding").filter_map do |encoding|
-
120
next if encoding == "identity"
-
-
120
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.
-
120
break unless inflater
-
-
120
@encodings << encoding
-
120
inflater
-
end
-
end
-
-
# passes the +chunk+ through all inflaters to decode it.
-
23
def decode_chunk(chunk)
-
40
@inflaters.reverse_each do |inflater|
-
339
chunk = inflater.call(chunk)
-
7936
end if @inflaters
-
-
7936
chunk
-
end
-
-
# tries transitioning the body STM to the +nextstate+.
-
23
def transition(nextstate)
-
7035
case nextstate
-
when :open
-
7820
return unless @state == :idle
-
-
4958
@buffer = Response::Buffer.new(
-
threshold_size: @options.body_threshold_size,
-
bytesize: @length,
-
encoding: @encoding
-
)
-
when :closed
-
406
return if @state == :closed
-
end
-
-
5364
@state = nextstate
-
end
-
-
23
def _with_same_buffer_pos # :nodoc:
-
30
return yield unless @buffer && @buffer.respond_to?(:pos)
-
-
# @type ivar @buffer: StringIO | Tempfile
-
30
current_pos = @buffer.pos
-
30
@buffer.rewind
-
begin
-
30
yield
-
ensure
-
30
@buffer.pos = current_pos
-
end
-
end
-
-
23
class << self
-
23
def initialize_inflater_by_encoding(encoding, response, **kwargs) # :nodoc:
-
105
case encoding
-
when "gzip"
-
108
Transcoder::GZIP.decode(response, **kwargs)
-
when "deflate"
-
12
Transcoder::Deflate.decode(response, **kwargs)
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "delegate"
-
23
require "stringio"
-
23
require "tempfile"
-
-
23
module HTTPX
-
# wraps and delegates to an internal buffer, which can be a StringIO or a Tempfile.
-
23
class Response::Buffer < SimpleDelegator
-
# initializes buffer with the +threshold_size+ over which the payload gets buffer to a tempfile,
-
# the initial +bytesize+, and the +encoding+.
-
23
def initialize(threshold_size:, bytesize: 0, encoding: Encoding::BINARY)
-
5012
@threshold_size = threshold_size
-
5012
@bytesize = bytesize
-
5012
@encoding = encoding
-
5012
@buffer = StringIO.new("".b)
-
5012
super(@buffer)
-
end
-
-
23
def initialize_dup(other)
-
24
super
-
-
24
@buffer = other.instance_variable_get(:@buffer).dup
-
end
-
-
# size in bytes of the buffered content.
-
23
def size
-
206
@bytesize
-
end
-
-
# writes the +chunk+ into the buffer.
-
23
def write(chunk)
-
6774
@bytesize += chunk.bytesize
-
7918
try_upgrade_buffer
-
7918
@buffer.write(chunk)
-
end
-
-
# returns the buffered content as a string.
-
23
def to_s
-
2525
case @buffer
-
when StringIO
-
begin
-
2931
@buffer.string.force_encoding(@encoding)
-
4
rescue ArgumentError
-
6
@buffer.string
-
end
-
when Tempfile
-
60
rewind
-
120
content = _with_same_buffer_pos { @buffer.read }
-
begin
-
60
content.force_encoding(@encoding)
-
4
rescue ArgumentError # ex: unknown encoding name - utf
-
6
content
-
end
-
end
-
end
-
-
# closes the buffer.
-
23
def close
-
275
@buffer.close
-
275
@buffer.unlink if @buffer.respond_to?(:unlink)
-
end
-
-
23
private
-
-
# initializes the buffer into a StringIO, or turns it into a Tempfile when the threshold
-
# has been reached.
-
23
def try_upgrade_buffer
-
7918
return unless @bytesize > @threshold_size
-
-
242
return if @buffer.is_a?(Tempfile)
-
-
99
aux = @buffer
-
-
99
@buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
-
99
if aux
-
99
aux.rewind
-
99
::IO.copy_stream(aux, @buffer)
-
99
aux.close
-
end
-
-
99
__setobj__(@buffer)
-
end
-
-
23
def _with_same_buffer_pos # :nodoc:
-
60
current_pos = @buffer.pos
-
60
@buffer.rewind
-
begin
-
60
yield
-
ensure
-
60
@buffer.pos = current_pos
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "io/wait"
-
-
23
class HTTPX::Selector
-
23
READABLE = %i[rw r].freeze
-
23
WRITABLE = %i[rw w].freeze
-
-
23
private_constant :READABLE
-
23
private_constant :WRITABLE
-
-
23
def initialize
-
500
@selectables = []
-
end
-
-
# deregisters +io+ from selectables.
-
23
def deregister(io)
-
10955
@selectables.delete(io)
-
end
-
-
# register +io+.
-
23
def register(io)
-
6183
return if @selectables.include?(io)
-
-
5971
@selectables << io
-
end
-
-
23
private
-
-
23
def select_many(interval, &block)
-
7678
selectables, r, w = nil
-
-
# first, we group IOs based on interest type. On call to #interests however,
-
# things might already happen, and new IOs might be registered, so we might
-
# have to start all over again. We do this until we group all selectables
-
begin
-
7678
loop do
-
begin
-
7678
r = nil
-
7678
w = nil
-
-
7678
selectables = @selectables
-
7678
@selectables = []
-
-
7678
selectables.delete_if do |io|
-
20079
interests = io.interests
-
-
20079
(r ||= []) << io if READABLE.include?(interests)
-
20079
(w ||= []) << io if WRITABLE.include?(interests)
-
-
20079
io.state == :closed
-
end
-
-
7678
if @selectables.empty?
-
7678
@selectables = selectables
-
-
# do not run event loop if there's nothing to wait on.
-
# this might happen if connect failed and connection was unregistered.
-
7678
return if (!r || r.empty?) && (!w || w.empty?) && !selectables.empty?
-
-
3248
break
-
else
-
@selectables.concat(selectables)
-
end
-
rescue StandardError
-
@selectables = selectables if selectables
-
raise
-
end
-
end
-
-
# TODO: what to do if there are no selectables?
-
-
3248
readers, writers = IO.select(r, w, nil, interval)
-
-
3248
if readers.nil? && writers.nil? && interval
-
278
[*r, *w].each { |io| io.handle_socket_timeout(interval) }
-
164
return
-
end
-
rescue IOError, SystemCallError
-
@selectables.reject!(&:closed?)
-
retry
-
end
-
-
3084
if writers
-
407
readers.each do |io|
-
1484
yield io
-
-
# so that we don't yield 2 times
-
1483
writers.delete(io)
-
3084
end if readers
-
-
3083
writers.each(&block)
-
else
-
readers.each(&block) if readers
-
end
-
end
-
-
23
def select_one(interval)
-
3684235
io = @selectables.first
-
-
3684235
return unless io
-
-
3684235
interests = io.interests
-
-
3684235
result = case interests
-
6633
when :r then io.to_io.wait_readable(interval)
-
5725
when :w then io.to_io.wait_writable(interval)
-
when :rw then io.to_io.wait(interval, :read_write)
-
3671877
when nil then return
-
end
-
-
12358
unless result || interval.nil?
-
308
io.handle_socket_timeout(interval)
-
303
return
-
end
-
# raise HTTPX::TimeoutError.new(interval, "timed out while waiting on select")
-
-
12050
yield io
-
rescue IOError, SystemCallError
-
@selectables.reject!(&:closed?)
-
raise unless @selectables.empty?
-
end
-
-
23
def select(interval, &block)
-
# do not cause an infinite loop here.
-
#
-
# this may happen if timeout calculation actually triggered an error which causes
-
# the connections to be reaped (such as the total timeout error) before #select
-
# gets called.
-
3691913
return if interval.nil? && @selectables.empty?
-
-
3691913
return select_one(interval, &block) if @selectables.size == 1
-
-
7678
select_many(interval, &block)
-
end
-
-
23
public :select
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
# Class implementing the APIs being used publicly.
-
#
-
# HTTPX.get(..) #=> delegating to an internal HTTPX::Session object.
-
# HTTPX.plugin(..).get(..) #=> creating an intermediate HTTPX::Session with plugin, then sending the GET request
-
23
class Session
-
23
include Loggable
-
23
include Chainable
-
-
23
EMPTY_HASH = {}.freeze
-
-
# initializes the session with a set of +options+, which will be shared by all
-
# requests sent from it.
-
#
-
# When pass a block, it'll yield itself to it, then closes after the block is evaluated.
-
23
def initialize(options = EMPTY_HASH, &blk)
-
7403
@options = self.class.default_options.merge(options)
-
7403
@responses = {}
-
7403
@persistent = @options.persistent
-
7403
wrap(&blk) if blk
-
end
-
-
# Yields itself the block, then closes it after the block is evaluated.
-
#
-
# session.wrap do |http|
-
# http.get("https://wikipedia.com")
-
# end # wikipedia connection closes here
-
23
def wrap
-
377
prev_persistent = @persistent
-
377
@persistent = true
-
377
pool.wrap do
-
begin
-
377
yield self
-
ensure
-
377
@persistent = prev_persistent
-
377
close unless @persistent
-
end
-
end
-
end
-
-
# closes all the active connections from the session
-
23
def close(*args)
-
4796
pool.close(*args)
-
end
-
-
# performs one, or multple requests; it accepts:
-
#
-
# 1. one or multiple HTTPX::Request objects;
-
# 2. an HTTP verb, then a sequence of URIs or URI/options tuples;
-
# 3. one or multiple HTTP verb / uri / (optional) options tuples;
-
#
-
# when present, the set of +options+ kwargs is applied to all of the
-
# sent requests.
-
#
-
# respectively returns a single HTTPX::Response response, or all of them in an Array, in the same order.
-
#
-
# resp1 = session.request(req1)
-
# resp1, resp2 = session.request(req1, req2)
-
# resp1 = session.request("GET", "https://server.org/a")
-
# resp1, resp2 = session.request("GET", ["https://server.org/a", "https://server.org/b"])
-
# resp1, resp2 = session.request(["GET", "https://server.org/a"], ["GET", "https://server.org/b"])
-
# resp1 = session.request("POST", "https://server.org/a", form: { "foo" => "bar" })
-
# resp1, resp2 = session.request(["POST", "https://server.org/a", form: { "foo" => "bar" }], ["GET", "https://server.org/b"])
-
# resp1, resp2 = session.request("GET", ["https://server.org/a", "https://server.org/b"], headers: { "x-api-token" => "TOKEN" })
-
#
-
23
def request(*args, **options)
-
5005
raise ArgumentError, "must perform at least one request" if args.empty?
-
-
5005
requests = args.first.is_a?(Request) ? args : build_requests(*args, options)
-
5004
responses = send_requests(*requests)
-
4897
return responses.first if responses.size == 1
-
-
147
responses
-
end
-
-
# returns a HTTP::Request instance built from the HTTP +verb+, the request +uri+, and
-
# the optional set of request-specific +options+. This request **must** be sent through
-
# the same session it was built from.
-
#
-
# req = session.build_request("GET", "https://server.com")
-
# resp = session.request(req)
-
23
def build_request(verb, uri, options = EMPTY_HASH)
-
6117
rklass = @options.request_class
-
6117
options = @options.merge(options) unless options.is_a?(Options)
-
6117
request = rklass.new(verb, uri, options)
-
6116
request.persistent = @persistent
-
6116
set_request_callbacks(request)
-
6116
request
-
end
-
-
23
private
-
-
# returns the HTTPX::Pool object which manages the networking required to
-
# perform requests.
-
23
def pool
-
3700932
Thread.current[:httpx_connection_pool] ||= Pool.new
-
end
-
-
# callback executed when a response for a given request has been received.
-
23
def on_response(request, response)
-
5490
@responses[request] = response
-
end
-
-
# callback executed when an HTTP/2 promise frame has been received.
-
23
def on_promise(_, stream)
-
6
log(level: 2) { "#{stream.id}: refusing stream!" }
-
6
stream.refuse
-
end
-
-
# returns the corresponding HTTP::Response to the given +request+ if it has been received.
-
23
def fetch_response(request, _, _)
-
3697331
@responses.delete(request)
-
end
-
-
# returns the HTTPX::Connection through which the +request+ should be sent through.
-
23
def find_connection(request, connections, options)
-
6126
uri = request.uri
-
-
6126
connection = pool.find_connection(uri, options) || init_connection(uri, options)
-
6074
unless connections.nil? || connections.include?(connection)
-
4832
connections << connection
-
4832
set_connection_callbacks(connection, connections, options)
-
end
-
6074
connection
-
end
-
-
23
def send_request(request, connections, options = request.options)
-
6404
error = catch(:resolve_error) do
-
6404
connection = find_connection(request, connections, options)
-
6334
connection.send(request)
-
end
-
6381
return unless error.is_a?(Error)
-
-
52
request.emit(:response, ErrorResponse.new(request, error, options))
-
end
-
-
# sets the callbacks on the +connection+ required to process certain specific
-
# connection lifecycle events which deal with request rerouting.
-
23
def set_connection_callbacks(connection, connections, options, cloned: false)
-
5127
connection.only(:misdirected) do |misdirected_request|
-
6
other_connection = connection.create_idle(ssl: { alpn_protocols: %w[http/1.1] })
-
6
other_connection.merge(connection)
-
6
catch(:coalesced) do
-
6
pool.init_connection(other_connection, options)
-
end
-
6
set_connection_callbacks(other_connection, connections, options)
-
6
connections << other_connection
-
6
misdirected_request.transition(:idle)
-
6
other_connection.send(misdirected_request)
-
end
-
5127
connection.only(:altsvc) do |alt_origin, origin, alt_params|
-
6
other_connection = build_altsvc_connection(connection, connections, alt_origin, origin, alt_params, options)
-
6
connections << other_connection if other_connection
-
end
-
5127
connection.only(:cloned) do |cloned_conn|
-
set_connection_callbacks(cloned_conn, connections, options, cloned: true)
-
connections << cloned_conn
-
5127
end unless cloned
-
end
-
-
# returns an HTTPX::Connection for the negotiated Alternative Service (or none).
-
23
def build_altsvc_connection(existing_connection, connections, alt_origin, origin, alt_params, options)
-
# do not allow security downgrades on altsvc negotiation
-
6
return if existing_connection.origin.scheme == "https" && alt_origin.scheme != "https"
-
-
6
altsvc = AltSvc.cached_altsvc_set(origin, alt_params.merge("origin" => alt_origin))
-
-
# altsvc already exists, somehow it wasn't advertised, probably noop
-
6
return unless altsvc
-
-
6
alt_options = options.merge(ssl: options.ssl.merge(hostname: URI(origin).host))
-
-
6
connection = pool.find_connection(alt_origin, alt_options) || init_connection(alt_origin, alt_options)
-
-
# advertised altsvc is the same origin being used, ignore
-
6
return if connection == existing_connection
-
-
6
connection.extend(AltSvc::ConnectionMixin) unless connection.is_a?(AltSvc::ConnectionMixin)
-
-
6
set_connection_callbacks(connection, connections, alt_options)
-
-
6
log(level: 1) { "#{origin} alt-svc: #{alt_origin}" }
-
-
6
connection.merge(existing_connection)
-
6
existing_connection.terminate
-
6
connection
-
rescue UnsupportedSchemeError
-
altsvc["noop"] = true
-
nil
-
end
-
-
# returns a set of HTTPX::Request objects built from the given +args+ and +options+.
-
23
def build_requests(*args, options)
-
4620
request_options = @options.merge(options)
-
-
4620
requests = if args.size == 1
-
59
reqs = args.first
-
59
reqs.map do |verb, uri, opts = EMPTY_HASH|
-
118
build_request(verb, uri, request_options.merge(opts))
-
end
-
else
-
4561
verb, uris = args
-
4561
if uris.respond_to?(:each)
-
4381
uris.enum_for(:each).map do |uri, opts = EMPTY_HASH|
-
5090
build_request(verb, uri, request_options.merge(opts))
-
end
-
else
-
180
[build_request(verb, uris, request_options)]
-
end
-
end
-
4619
raise ArgumentError, "wrong number of URIs (given 0, expect 1..+1)" if requests.empty?
-
-
4619
requests
-
end
-
-
23
def set_request_callbacks(request)
-
6116
request.on(:response, &method(:on_response).curry(2)[request])
-
6116
request.on(:promise, &method(:on_promise))
-
end
-
-
23
def init_connection(uri, options)
-
5076
connection = options.connection_class.new(uri, options)
-
5064
catch(:coalesced) do
-
5064
pool.init_connection(connection, options)
-
5019
connection
-
end
-
end
-
-
# sends an array of HTTPX::Request +requests+, returns the respective array of HTTPX::Response objects.
-
23
def send_requests(*requests)
-
5078
connections = _send_requests(requests)
-
5055
receive_requests(requests, connections)
-
end
-
-
# sends an array of HTTPX::Request objects
-
23
def _send_requests(requests)
-
5078
connections = []
-
-
5078
requests.each do |request|
-
5835
send_request(request, connections)
-
end
-
-
5055
connections
-
end
-
-
# returns the array of HTTPX::Response objects corresponding to the array of HTTPX::Request +requests+.
-
23
def receive_requests(requests, connections)
-
# @type var responses: Array[response]
-
5055
responses = []
-
-
begin
-
# guarantee ordered responses
-
5055
loop do
-
5818
request = requests.first
-
-
5818
return responses unless request
-
-
4147445
catch(:coalesced) { pool.next_tick } until (response = fetch_response(request, connections, request.options))
-
-
5734
responses << response
-
5734
requests.shift
-
-
5734
break if requests.empty?
-
-
763
next unless pool.empty?
-
-
# in some cases, the pool of connections might have been drained because there was some
-
# handshake error, and the error responses have already been emitted, but there was no
-
# opportunity to traverse the requests, hence we're returning only a fraction of the errors
-
# we were supposed to. This effectively fetches the existing responses and return them.
-
while (request = requests.shift)
-
responses << fetch_response(request, connections, request.options)
-
end
-
break
-
end
-
4971
responses
-
ensure
-
5055
if @persistent
-
779
pool.deactivate(connections)
-
else
-
4276
close(connections)
-
end
-
end
-
end
-
-
23
@default_options = Options.new
-
23
@default_options.freeze
-
23
@plugins = []
-
-
23
class << self
-
23
attr_reader :default_options
-
-
23
def inherited(klass)
-
3642
super
-
3642
klass.instance_variable_set(:@default_options, @default_options)
-
3642
klass.instance_variable_set(:@plugins, @plugins.dup)
-
3642
klass.instance_variable_set(:@callbacks, @callbacks.dup)
-
end
-
-
# returns a new HTTPX::Session instance, with the plugin pointed by +pl+ loaded.
-
#
-
# session_with_retries = session.plugin(:retries)
-
# session_with_custom = session.plugin(CustomPlugin)
-
#
-
23
def plugin(pl, options = nil, &block)
-
# raise Error, "Cannot add a plugin to a frozen config" if frozen?
-
4974
pl = Plugins.load_plugin(pl) if pl.is_a?(Symbol)
-
4974
if !@plugins.include?(pl)
-
4815
@plugins << pl
-
4815
pl.load_dependencies(self, &block) if pl.respond_to?(:load_dependencies)
-
-
4815
@default_options = @default_options.dup
-
-
4815
include(pl::InstanceMethods) if defined?(pl::InstanceMethods)
-
4815
extend(pl::ClassMethods) if defined?(pl::ClassMethods)
-
-
4815
opts = @default_options
-
4815
opts.extend_with_plugin_classes(pl)
-
4815
if defined?(pl::OptionsMethods)
-
-
1815
(pl::OptionsMethods.instance_methods - Object.instance_methods).each do |meth|
-
5358
opts.options_class.method_added(meth)
-
end
-
1815
@default_options = opts.options_class.new(opts)
-
end
-
-
4815
@default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
-
4815
@default_options = @default_options.merge(options) if options
-
-
4815
pl.configure(self, &block) if pl.respond_to?(:configure)
-
-
4815
@default_options.freeze
-
159
elsif options
-
# this can happen when two plugins are loaded, an one of them calls the other under the hood,
-
# albeit changing some default.
-
12
@default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
-
12
@default_options = @default_options.merge(options) if options
-
-
12
@default_options.freeze
-
end
-
4974
self
-
end
-
end
-
end
-
-
# session may be overridden by certain adapters.
-
23
S = Session
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
unless ENV.keys.grep(/\Ahttps?_proxy\z/i).empty?
-
1
proxy_session = plugin(:proxy)
-
1
remove_const(:Session)
-
1
const_set(:Session, proxy_session.class)
-
-
# redefine the default options static var, which needs to
-
# refresh options_class
-
1
options = proxy_session.class.default_options.to_hash
-
1
original_verbosity = $VERBOSE
-
1
$VERBOSE = nil
-
1
const_set(:Options, proxy_session.class.default_options.options_class)
-
1
options[:options_class] = Class.new(options[:options_class])
-
1
options.freeze
-
1
Options.send(:const_set, :DEFAULT_OPTIONS, options)
-
1
Session.instance_variable_set(:@default_options, Options.new(options))
-
1
$VERBOSE = original_verbosity
-
end
-
-
skipped
# :nocov:
-
skipped
if Session.default_options.debug_level > 2
-
skipped
proxy_session = plugin(:internal_telemetry)
-
skipped
remove_const(:Session)
-
skipped
const_set(:Session, proxy_session.class)
-
skipped
end
-
skipped
# :nocov:
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
class Timers
-
23
def initialize
-
500
@intervals = []
-
end
-
-
23
def after(interval_in_secs, cb = nil, &blk)
-
32769
return unless interval_in_secs
-
-
32769
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.
-
60167
unless (interval = @intervals.find { |t| t.interval == interval_in_secs })
-
6167
interval = Interval.new(interval_in_secs)
-
12202
interval.on_empty { @intervals.delete(interval) }
-
6167
@intervals << interval
-
6167
@intervals.sort!
-
end
-
-
32769
interval << callback
-
-
32769
@next_interval_at = nil
-
-
32769
interval
-
end
-
-
23
def wait_interval
-
3691913
return if @intervals.empty?
-
-
3679068
@next_interval_at = Utils.now
-
-
3679068
@intervals.first.interval
-
end
-
-
23
def fire(error = nil)
-
3691814
raise error if error && error.timeout != @intervals.first
-
3691809
return if @intervals.empty? || !@next_interval_at
-
-
3674597
elapsed_time = Utils.elapsed_time(@next_interval_at)
-
-
7349266
@intervals.delete_if { |interval| interval.elapse(elapsed_time) <= 0 }
-
-
3674597
@next_interval_at = nil if @intervals.empty?
-
end
-
-
23
class Interval
-
23
include Comparable
-
-
23
attr_reader :interval
-
-
23
def initialize(interval)
-
6167
@interval = interval
-
6167
@callbacks = []
-
6167
@on_empty = nil
-
end
-
-
23
def on_empty(&blk)
-
6167
@on_empty = blk
-
end
-
-
23
def <=>(other)
-
450
@interval <=> other.interval
-
end
-
-
23
def ==(other)
-
1846
return @interval == other if other.is_a?(Numeric)
-
-
1846
@interval == other.to_f # rubocop:disable Lint/FloatComparison
-
end
-
-
23
def to_f
-
1846
Float(@interval)
-
end
-
-
23
def <<(callback)
-
32769
@callbacks << callback
-
end
-
-
23
def delete(callback)
-
48589
@callbacks.delete(callback)
-
48589
@on_empty.call if @callbacks.empty?
-
end
-
-
23
def no_callbacks?
-
48589
@callbacks.empty?
-
end
-
-
23
def elapsed?
-
832
@interval <= 0
-
end
-
-
23
def elapse(elapsed)
-
3225584
@interval -= elapsed
-
-
3674669
if @interval <= 0
-
400
cb = @callbacks.dup
-
400
cb.each(&:call)
-
end
-
-
3674669
@interval
-
end
-
end
-
23
private_constant :Interval
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Transcoder
-
23
module_function
-
-
23
def normalize_keys(key, value, cond = nil, &block)
-
2482
if cond && cond.call(value)
-
749
block.call(key.to_s, value)
-
1733
elsif value.respond_to?(:to_ary)
-
341
if value.empty?
-
96
block.call("#{key}[]")
-
else
-
245
value.to_ary.each do |element|
-
394
normalize_keys("#{key}[]", element, cond, &block)
-
end
-
end
-
1392
elsif value.respond_to?(:to_hash)
-
384
value.to_hash.each do |child_key, child_value|
-
384
normalize_keys("#{key}[#{child_key}]", child_value, cond, &block)
-
end
-
else
-
1008
block.call(key.to_s, value)
-
end
-
end
-
-
# based on https://github.com/rack/rack/blob/d15dd728440710cfc35ed155d66a98dc2c07ae42/lib/rack/query_parser.rb#L82
-
23
def normalize_query(params, name, v, depth)
-
138
raise Error, "params depth surpasses what's supported" if depth <= 0
-
-
138
name =~ /\A[\[\]]*([^\[\]]+)\]*/
-
138
k = Regexp.last_match(1) || ""
-
138
after = Regexp.last_match ? Regexp.last_match.post_match : ""
-
-
138
if k.empty?
-
12
return Array(v) if !v.empty? && name == "[]"
-
-
5
return
-
end
-
-
105
case after
-
when ""
-
35
params[k] = v
-
when "["
-
5
params[name] = v
-
when "[]"
-
12
params[k] ||= []
-
12
raise Error, "expected Array (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Array)
-
-
12
params[k] << v
-
when /^\[\]\[([^\[\]]+)\]$/, /^\[\](.+)$/
-
24
child_key = Regexp.last_match(1)
-
24
params[k] ||= []
-
24
raise Error, "expected Array (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Array)
-
-
24
if params[k].last.is_a?(Hash) && !params_hash_has_key?(params[k].last, child_key)
-
6
normalize_query(params[k].last, child_key, v, depth - 1)
-
else
-
18
params[k] << normalize_query({}, child_key, v, depth - 1)
-
end
-
else
-
42
params[k] ||= {}
-
42
raise Error, "expected Hash (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Hash)
-
-
35
params[k] = normalize_query(params[k], after, v, depth - 1)
-
end
-
-
126
params
-
end
-
-
23
def params_hash_has_key?(hash, key)
-
12
return false if key.include?("[]")
-
-
12
key.split(/[\[\]]+/).inject(hash) do |h, part|
-
12
next h if part == ""
-
12
return false unless h.is_a?(Hash) && h.key?(part)
-
-
6
h[part]
-
end
-
-
6
true
-
end
-
end
-
end
-
-
23
require "httpx/transcoder/body"
-
23
require "httpx/transcoder/form"
-
23
require "httpx/transcoder/json"
-
23
require "httpx/transcoder/xml"
-
23
require "httpx/transcoder/chunker"
-
23
require "httpx/transcoder/deflate"
-
23
require "httpx/transcoder/gzip"
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
-
23
module HTTPX::Transcoder
-
23
module Body
-
23
class Error < HTTPX::Error; end
-
-
23
module_function
-
-
23
class Encoder
-
23
extend Forwardable
-
-
23
def_delegator :@raw, :to_s
-
-
23
def initialize(body)
-
902
@raw = body
-
end
-
-
23
def bytesize
-
3746
if @raw.respond_to?(:bytesize)
-
1775
@raw.bytesize
-
1971
elsif @raw.respond_to?(:to_ary)
-
699
@raw.sum(&:bytesize)
-
1272
elsif @raw.respond_to?(:size)
-
858
@raw.size || Float::INFINITY
-
414
elsif @raw.respond_to?(:length)
-
192
@raw.length || Float::INFINITY
-
222
elsif @raw.respond_to?(:each)
-
216
Float::INFINITY
-
else
-
6
raise Error, "cannot determine size of body: #{@raw.inspect}"
-
end
-
end
-
-
23
def content_type
-
866
"application/octet-stream"
-
end
-
-
23
private
-
-
23
def respond_to_missing?(meth, *args)
-
3678
@raw.respond_to?(meth, *args) || super
-
end
-
-
23
def method_missing(meth, *args, &block)
-
1017
return super unless @raw.respond_to?(meth)
-
-
1017
@raw.__send__(meth, *args, &block)
-
end
-
end
-
-
23
def encode(body)
-
902
Encoder.new(body)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
-
23
module HTTPX::Transcoder
-
23
module Chunker
-
23
class Error < HTTPX::Error; end
-
-
23
CRLF = "\r\n".b
-
-
23
class Encoder
-
23
extend Forwardable
-
-
23
def initialize(body)
-
72
@raw = body
-
end
-
-
23
def each
-
72
return enum_for(__method__) unless block_given?
-
-
72
@raw.each do |chunk|
-
336
yield "#{chunk.bytesize.to_s(16)}#{CRLF}#{chunk}#{CRLF}"
-
end
-
72
yield "0#{CRLF}"
-
end
-
-
23
def respond_to_missing?(meth, *args)
-
120
@raw.respond_to?(meth, *args) || super
-
end
-
end
-
-
23
class Decoder
-
23
extend Forwardable
-
-
23
def_delegator :@buffer, :empty?
-
-
23
def_delegator :@buffer, :<<
-
-
23
def_delegator :@buffer, :clear
-
-
23
def initialize(buffer, trailers = false)
-
80
@buffer = buffer
-
80
@chunk_buffer = "".b
-
80
@finished = false
-
80
@state = :length
-
80
@trailers = trailers
-
end
-
-
23
def to_s
-
74
@buffer
-
end
-
-
23
def each
-
144
loop do
-
679
case @state
-
when :length
-
232
index = @buffer.index(CRLF)
-
232
return unless index && index.positive?
-
-
# Read hex-length
-
232
hexlen = @buffer.byteslice(0, index)
-
232
@buffer = @buffer.byteslice(index..-1) || "".b
-
232
hexlen[/\h/] || raise(Error, "wrong chunk size line: #{hexlen}")
-
232
@chunk_length = hexlen.hex
-
# check if is last chunk
-
232
@finished = @chunk_length.zero?
-
232
nextstate(:crlf)
-
when :crlf
-
384
crlf_size = @finished && !@trailers ? 4 : 2
-
# consume CRLF
-
384
return if @buffer.bytesize < crlf_size
-
384
raise Error, "wrong chunked encoding format" unless @buffer.start_with?(CRLF * (crlf_size / 2))
-
-
384
@buffer = @buffer.byteslice(crlf_size..-1)
-
384
if @chunk_length.nil?
-
152
nextstate(:length)
-
else
-
232
return if @finished
-
-
158
nextstate(:data)
-
end
-
when :data
-
196
chunk = @buffer.byteslice(0, @chunk_length)
-
196
@buffer = @buffer.byteslice(@chunk_length..-1) || "".b
-
196
@chunk_buffer << chunk
-
164
@chunk_length -= chunk.bytesize
-
196
if @chunk_length.zero?
-
158
yield @chunk_buffer unless @chunk_buffer.empty?
-
152
@chunk_buffer.clear
-
152
@chunk_length = nil
-
152
nextstate(:crlf)
-
end
-
end
-
732
break if @buffer.empty?
-
end
-
end
-
-
23
def finished?
-
138
@finished
-
end
-
-
23
private
-
-
23
def nextstate(state)
-
694
@state = state
-
end
-
end
-
-
23
module_function
-
-
23
def encode(chunks)
-
72
Encoder.new(chunks)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "zlib"
-
23
require_relative "utils/deflater"
-
-
23
module HTTPX
-
23
module Transcoder
-
23
module Deflate
-
23
class Deflater < Transcoder::Deflater
-
23
def deflate(chunk)
-
36
@deflater ||= Zlib::Deflate.new
-
-
36
if chunk.nil?
-
24
unless @deflater.closed?
-
12
last = @deflater.finish
-
12
@deflater.close
-
12
last.empty? ? nil : last
-
end
-
else
-
12
@deflater.deflate(chunk)
-
end
-
end
-
end
-
-
23
module_function
-
-
23
def encode(body)
-
12
Deflater.new(body)
-
end
-
-
23
def decode(response, bytesize: nil)
-
12
bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
-
12
GZIP::Inflater.new(bytesize)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
23
require "uri"
-
23
require_relative "multipart"
-
-
23
module HTTPX
-
23
module Transcoder
-
23
module Form
-
23
module_function
-
-
23
PARAM_DEPTH_LIMIT = 32
-
-
23
class Encoder
-
23
extend Forwardable
-
-
23
def_delegator :@raw, :to_s
-
-
23
def_delegator :@raw, :to_str
-
-
23
def_delegator :@raw, :bytesize
-
-
23
def initialize(form)
-
511
@raw = form.each_with_object("".b) do |(key, val), buf|
-
859
HTTPX::Transcoder.normalize_keys(key, val) do |k, v|
-
1008
buf << "&" unless buf.empty?
-
1008
buf << URI.encode_www_form_component(k)
-
1008
buf << "=#{URI.encode_www_form_component(v.to_s)}" unless v.nil?
-
end
-
end
-
end
-
-
23
def content_type
-
395
"application/x-www-form-urlencoded"
-
end
-
end
-
-
23
module Decoder
-
23
module_function
-
-
23
def call(response, *)
-
30
URI.decode_www_form(response.to_s).each_with_object({}) do |(field, value), params|
-
72
HTTPX::Transcoder.normalize_query(params, field, value, PARAM_DEPTH_LIMIT)
-
end
-
end
-
end
-
-
23
def encode(form)
-
1200
if multipart?(form)
-
689
Multipart::Encoder.new(form)
-
else
-
511
Encoder.new(form)
-
end
-
end
-
-
23
def decode(response)
-
48
content_type = response.content_type.mime_type
-
-
40
case content_type
-
when "application/x-www-form-urlencoded"
-
30
Decoder
-
when "multipart/form-data"
-
12
Multipart::Decoder.new(response)
-
else
-
6
raise Error, "invalid form mime type (#{content_type})"
-
end
-
end
-
-
23
def multipart?(data)
-
1200
data.any? do |_, v|
-
1596
Multipart::MULTIPART_VALUE_COND.call(v) ||
-
1243
(v.respond_to?(:to_ary) && v.to_ary.any?(&Multipart::MULTIPART_VALUE_COND)) ||
-
1531
(v.respond_to?(:to_hash) && v.to_hash.any? { |_, e| Multipart::MULTIPART_VALUE_COND.call(e) })
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
23
require "uri"
-
23
require "stringio"
-
23
require "zlib"
-
-
23
module HTTPX
-
23
module Transcoder
-
23
module GZIP
-
23
class Deflater < Transcoder::Deflater
-
23
def initialize(body)
-
32
@compressed_chunk = "".b
-
32
super
-
end
-
-
23
def deflate(chunk)
-
64
@deflater ||= Zlib::GzipWriter.new(self)
-
-
64
if chunk.nil?
-
32
unless @deflater.closed?
-
32
@deflater.flush
-
32
@deflater.close
-
32
compressed_chunk
-
end
-
else
-
32
@deflater.write(chunk)
-
32
compressed_chunk
-
end
-
end
-
-
23
private
-
-
23
def write(chunk)
-
96
@compressed_chunk << chunk
-
end
-
-
23
def compressed_chunk
-
64
@compressed_chunk.dup
-
ensure
-
64
@compressed_chunk.clear
-
end
-
end
-
-
23
class Inflater
-
23
def initialize(bytesize)
-
120
@inflater = Zlib::Inflate.new(Zlib::MAX_WBITS + 32)
-
120
@bytesize = bytesize
-
end
-
-
23
def call(chunk)
-
339
buffer = @inflater.inflate(chunk)
-
299
@bytesize -= chunk.bytesize
-
339
if @bytesize <= 0
-
72
buffer << @inflater.finish
-
72
@inflater.close
-
end
-
339
buffer
-
end
-
end
-
-
23
module_function
-
-
23
def encode(body)
-
32
Deflater.new(body)
-
end
-
-
23
def decode(response, bytesize: nil)
-
108
bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
-
108
Inflater.new(bytesize)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
-
23
module HTTPX::Transcoder
-
23
module JSON
-
23
module_function
-
-
23
JSON_REGEX = %r{\bapplication/(?:vnd\.api\+|hal\+)?json\b}i.freeze
-
-
23
class Encoder
-
23
extend Forwardable
-
-
23
def_delegator :@raw, :to_s
-
-
23
def_delegator :@raw, :bytesize
-
-
23
def initialize(json)
-
54
@raw = JSON.json_dump(json)
-
54
@charset = @raw.encoding.name.downcase
-
end
-
-
23
def content_type
-
54
"application/json; charset=#{@charset}"
-
end
-
end
-
-
23
def encode(json)
-
54
Encoder.new(json)
-
end
-
-
23
def decode(response)
-
57
content_type = response.content_type.mime_type
-
-
57
raise HTTPX::Error, "invalid json mime type (#{content_type})" unless JSON_REGEX.match?(content_type)
-
-
51
method(:json_load)
-
end
-
-
# rubocop:disable Style/SingleLineMethods
-
23
if defined?(MultiJson)
-
4
def json_load(*args); MultiJson.load(*args); end
-
1
def json_dump(*args); MultiJson.dump(*args); end
-
22
elsif defined?(Oj)
-
4
def json_load(response, *args); Oj.load(response.to_s, *args); end
-
1
def json_dump(*args); Oj.dump(*args); end
-
21
elsif defined?(Yajl)
-
4
def json_load(response, *args); Yajl::Parser.new(*args).parse(response.to_s); end
-
1
def json_dump(*args); Yajl::Encoder.encode(*args); end
-
else
-
20
require "json"
-
55
def json_load(*args); ::JSON.parse(*args); end
-
65
def json_dump(*args); ::JSON.dump(*args); end
-
end
-
# rubocop:enable Style/SingleLineMethods
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require_relative "multipart/encoder"
-
23
require_relative "multipart/decoder"
-
23
require_relative "multipart/part"
-
23
require_relative "multipart/mime_type_detector"
-
-
23
module HTTPX::Transcoder
-
23
module Multipart
-
23
MULTIPART_VALUE_COND = lambda do |value|
-
3555
value.respond_to?(:read) ||
-
2601
(value.respond_to?(:to_hash) &&
-
value.key?(:body) &&
-
484
(value.key?(:filename) || value.key?(:content_type)))
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "tempfile"
-
23
require "delegate"
-
-
23
module HTTPX
-
23
module Transcoder
-
23
module Multipart
-
23
class FilePart < SimpleDelegator
-
23
attr_reader :original_filename, :content_type
-
-
23
def initialize(filename, content_type)
-
24
@original_filename = filename
-
24
@content_type = content_type
-
24
@file = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
24
super(@file)
-
end
-
end
-
-
23
class Decoder
-
23
include HTTPX::Utils
-
-
23
CRLF = "\r\n"
-
23
BOUNDARY_RE = /;\s*boundary=([^;]+)/i.freeze
-
23
MULTIPART_CONTENT_TYPE = /Content-Type: (.*)#{CRLF}/ni.freeze
-
23
MULTIPART_CONTENT_DISPOSITION = /Content-Disposition:.*;\s*name=(#{VALUE})/ni.freeze
-
23
MULTIPART_CONTENT_ID = /Content-ID:\s*([^#{CRLF}]*)/ni.freeze
-
23
WINDOW_SIZE = 2 << 14
-
-
23
def initialize(response)
-
2
@boundary = begin
-
12
m = response.headers["content-type"].to_s[BOUNDARY_RE, 1]
-
12
raise Error, "no boundary declared in content-type header" unless m
-
-
12
m.strip
-
end
-
12
@buffer = "".b
-
12
@parts = {}
-
12
@intermediate_boundary = "--#{@boundary}"
-
12
@state = :idle
-
end
-
-
23
def call(response, *)
-
12
response.body.each do |chunk|
-
12
@buffer << chunk
-
-
12
parse
-
end
-
-
12
raise Error, "invalid or unsupported multipart format" unless @buffer.empty?
-
-
12
@parts
-
end
-
-
23
private
-
-
23
def parse
-
10
case @state
-
when :idle
-
12
raise Error, "payload does not start with boundary" unless @buffer.start_with?("#{@intermediate_boundary}#{CRLF}")
-
-
12
@buffer = @buffer.byteslice(@intermediate_boundary.bytesize + 2..-1)
-
-
12
@state = :part_header
-
when :part_header
-
36
idx = @buffer.index("#{CRLF}#{CRLF}")
-
-
# raise Error, "couldn't parse part headers" unless idx
-
36
return unless idx
-
-
36
head = @buffer.byteslice(0..idx + 4 - 1)
-
-
36
@buffer = @buffer.byteslice(head.bytesize..-1)
-
-
36
content_type = head[MULTIPART_CONTENT_TYPE, 1]
-
66
if (name = head[MULTIPART_CONTENT_DISPOSITION, 1])
-
36
name = /\A"(.*)"\Z/ =~ name ? Regexp.last_match(1) : name.dup
-
36
name.gsub!(/\\(.)/, "\\1")
-
6
name
-
else
-
name = head[MULTIPART_CONTENT_ID, 1]
-
end
-
-
36
filename = HTTPX::Utils.get_filename(head)
-
-
36
name = filename || +"#{content_type || "text/plain"}[]" if name.nil? || name.empty?
-
-
36
@current = name
-
-
30
@parts[name] = if filename
-
24
FilePart.new(filename, content_type)
-
else
-
12
"".b
-
end
-
-
36
@state = :part_body
-
when :part_body
-
36
part = @parts[@current]
-
-
36
body_separator = if part.is_a?(FilePart)
-
20
"#{CRLF}#{CRLF}"
-
else
-
12
CRLF
-
end
-
36
idx = @buffer.index(body_separator)
-
-
36
if idx
-
36
payload = @buffer.byteslice(0..idx - 1)
-
36
@buffer = @buffer.byteslice(idx + body_separator.bytesize..-1)
-
36
part << payload
-
36
part.rewind if part.respond_to?(:rewind)
-
36
@state = :parse_boundary
-
else
-
part << @buffer
-
@buffer.clear
-
end
-
when :parse_boundary
-
36
raise Error, "payload does not start with boundary" unless @buffer.start_with?(@intermediate_boundary)
-
-
36
@buffer = @buffer.byteslice(@intermediate_boundary.bytesize..-1)
-
-
36
if @buffer == "--"
-
12
@buffer.clear
-
12
@state = :done
-
12
return
-
24
elsif @buffer.start_with?(CRLF)
-
24
@buffer = @buffer.byteslice(2..-1)
-
24
@state = :part_header
-
else
-
return
-
end
-
when :done
-
raise Error, "parsing should have been over by now"
-
20
end until @buffer.empty?
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Transcoder::Multipart
-
23
class Encoder
-
23
attr_reader :bytesize
-
-
23
def initialize(form)
-
689
@boundary = ("-" * 21) << SecureRandom.hex(21)
-
689
@part_index = 0
-
689
@buffer = "".b
-
-
689
@form = form
-
689
@parts = to_parts(form)
-
end
-
-
23
def content_type
-
689
"multipart/form-data; boundary=#{@boundary}"
-
end
-
-
23
def read(length = nil, outbuf = nil)
-
2564
data = outbuf.clear.force_encoding(Encoding::BINARY) if outbuf
-
2564
data ||= "".b
-
-
2564
read_chunks(data, length)
-
-
2564
data unless length && data.empty?
-
end
-
-
23
def rewind
-
12
form = @form.each_with_object([]) do |(key, val), aux|
-
12
val = val.reopen(val.path, File::RDONLY) if val.is_a?(File) && val.closed?
-
12
val.rewind if val.respond_to?(:rewind)
-
12
aux << [key, val]
-
end
-
12
@form = form
-
12
@parts = to_parts(form)
-
12
@part_index = 0
-
end
-
-
23
private
-
-
23
def to_parts(form)
-
701
@bytesize = 0
-
701
params = form.each_with_object([]) do |(key, val), aux|
-
845
Transcoder.normalize_keys(key, val, MULTIPART_VALUE_COND) do |k, v|
-
845
next if v.nil?
-
-
845
value, content_type, filename = Part.call(v)
-
-
845
header = header_part(k, content_type, filename)
-
705
@bytesize += header.size
-
845
aux << header
-
-
705
@bytesize += value.size
-
845
aux << value
-
-
845
delimiter = StringIO.new("\r\n")
-
705
@bytesize += delimiter.size
-
845
aux << delimiter
-
end
-
end
-
701
final_delimiter = StringIO.new("--#{@boundary}--\r\n")
-
585
@bytesize += final_delimiter.size
-
701
params << final_delimiter
-
-
701
params
-
end
-
-
23
def header_part(key, content_type, filename)
-
845
header = "--#{@boundary}\r\n".b
-
845
header << "Content-Disposition: form-data; name=#{key.inspect}".b
-
845
header << "; filename=#{filename.inspect}" if filename
-
845
header << "\r\nContent-Type: #{content_type}\r\n\r\n"
-
845
StringIO.new(header)
-
end
-
-
23
def read_chunks(buffer, length = nil)
-
3636
while @part_index < @parts.size
-
7634
chunk = read_from_part(length)
-
-
7634
next unless chunk
-
-
4398
buffer << chunk.force_encoding(Encoding::BINARY)
-
-
4398
next unless length
-
-
3670
length -= chunk.bytesize
-
-
4398
break if length.zero?
-
end
-
end
-
-
# if there's a current part to read from, tries to read a chunk.
-
23
def read_from_part(max_length = nil)
-
7634
part = @parts[@part_index]
-
-
7634
chunk = part.read(max_length, @buffer)
-
-
7634
return chunk if chunk && !chunk.empty?
-
-
3236
part.close if part.respond_to?(:close)
-
-
2700
@part_index += 1
-
-
536
nil
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Transcoder::Multipart
-
23
module MimeTypeDetector
-
23
module_function
-
-
23
DEFAULT_MIMETYPE = "application/octet-stream"
-
-
# inspired by https://github.com/shrinerb/shrine/blob/master/lib/shrine/plugins/determine_mime_type.rb
-
23
if defined?(FileMagic)
-
1
MAGIC_NUMBER = 256 * 1024
-
-
1
def call(file, _)
-
1
return nil if file.eof? # FileMagic returns "application/x-empty" for empty files
-
-
1
mime = FileMagic.open(FileMagic::MAGIC_MIME_TYPE) do |filemagic|
-
1
filemagic.buffer(file.read(MAGIC_NUMBER))
-
end
-
-
1
file.rewind
-
-
1
mime
-
end
-
22
elsif defined?(Marcel)
-
1
def call(file, filename)
-
1
return nil if file.eof? # marcel returns "application/octet-stream" for empty files
-
-
1
Marcel::MimeType.for(file, name: filename)
-
end
-
-
21
elsif defined?(MimeMagic)
-
-
1
def call(file, _)
-
1
mime = MimeMagic.by_magic(file)
-
1
mime.type if mime
-
end
-
-
20
elsif system("which file", out: File::NULL)
-
20
require "open3"
-
-
20
def call(file, _)
-
457
return if file.eof? # file command returns "application/x-empty" for empty files
-
-
457
Open3.popen3(*%w[file --mime-type --brief -]) do |stdin, stdout, stderr, thread|
-
begin
-
457
::IO.copy_stream(file, stdin.binmode)
-
rescue Errno::EPIPE
-
end
-
457
file.rewind
-
457
stdin.close
-
-
457
status = thread.value
-
-
# call to file command failed
-
457
if status.nil? || !status.success?
-
$stderr.print(stderr.read)
-
else
-
-
457
output = stdout.read.strip
-
-
457
if output.include?("cannot open")
-
$stderr.print(output)
-
else
-
457
output
-
end
-
end
-
end
-
end
-
-
else
-
-
def call(_, _); end
-
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Transcoder::Multipart
-
23
module Part
-
23
module_function
-
-
23
def call(value)
-
# take out specialized objects of the way
-
845
if value.respond_to?(:filename) && value.respond_to?(:content_type) && value.respond_to?(:read)
-
80
return value, value.content_type, value.filename
-
end
-
-
749
content_type = filename = nil
-
-
749
if value.is_a?(Hash)
-
242
content_type = value[:content_type]
-
242
filename = value[:filename]
-
242
value = value[:body]
-
end
-
-
749
value = value.open(File::RDONLY) if Object.const_defined?(:Pathname) && value.is_a?(Pathname)
-
-
749
if value.respond_to?(:path) && value.respond_to?(:read)
-
# either a File, a Tempfile, or something else which has to quack like a file
-
461
filename ||= File.basename(value.path)
-
461
content_type ||= MimeTypeDetector.call(value, filename) || "application/octet-stream"
-
461
[value, content_type, filename]
-
else
-
288
[StringIO.new(value.to_s), content_type || "text/plain", filename]
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "stringio"
-
-
23
module HTTPX
-
23
module Transcoder
-
23
class BodyReader
-
23
def initialize(body)
-
159
@body = if body.respond_to?(:read)
-
10
body.rewind if body.respond_to?(:rewind)
-
10
body
-
149
elsif body.respond_to?(:each)
-
30
body.enum_for(:each)
-
else
-
119
StringIO.new(body.to_s)
-
end
-
end
-
-
23
def bytesize
-
335
return @body.bytesize if @body.respond_to?(:bytesize)
-
-
305
Float::INFINITY
-
end
-
-
23
def read(length = nil, outbuf = nil)
-
340
return @body.read(length, outbuf) if @body.respond_to?(:read)
-
-
begin
-
70
chunk = @body.next
-
40
if outbuf
-
40
outbuf.clear.force_encoding(Encoding::BINARY)
-
40
outbuf << chunk
-
else
-
outbuf = chunk
-
end
-
40
outbuf unless length && outbuf.empty?
-
24
rescue StopIteration
-
end
-
end
-
-
23
def close
-
32
@body.close if @body.respond_to?(:close)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "forwardable"
-
23
require_relative "body_reader"
-
-
23
module HTTPX
-
23
module Transcoder
-
23
class Deflater
-
23
extend Forwardable
-
-
23
attr_reader :content_type
-
-
23
def initialize(body)
-
54
@content_type = body.content_type
-
54
@body = BodyReader.new(body)
-
54
@closed = false
-
end
-
-
23
def bytesize
-
206
buffer_deflate!
-
-
206
@buffer.size
-
end
-
-
23
def read(length = nil, outbuf = nil)
-
260
return @buffer.read(length, outbuf) if @buffer
-
-
152
return if @closed
-
-
120
chunk = @body.read(length)
-
-
120
compressed_chunk = deflate(chunk)
-
-
120
return unless compressed_chunk
-
-
98
if outbuf
-
98
outbuf.clear.force_encoding(Encoding::BINARY)
-
98
outbuf << compressed_chunk
-
else
-
compressed_chunk
-
end
-
end
-
-
23
def close
-
32
return if @closed
-
-
32
@buffer.close if @buffer
-
-
32
@body.close
-
-
32
@closed = true
-
end
-
-
23
private
-
-
# rubocop:disable Naming/MemoizedInstanceVariableName
-
23
def buffer_deflate!
-
206
return @buffer if defined?(@buffer)
-
-
54
buffer = Response::Buffer.new(
-
threshold_size: Options::MAX_BODY_THRESHOLD_SIZE
-
)
-
54
::IO.copy_stream(self, buffer)
-
-
54
buffer.rewind
-
-
54
@buffer = buffer
-
end
-
# rubocop:enable Naming/MemoizedInstanceVariableName
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
require "delegate"
-
23
require "forwardable"
-
23
require "uri"
-
-
23
module HTTPX::Transcoder
-
23
module Xml
-
23
module_function
-
-
23
MIME_TYPES = %r{\b(application|text)/(.+\+)?xml\b}.freeze
-
-
23
class Encoder
-
23
def initialize(xml)
-
102
@raw = xml
-
end
-
-
23
def content_type
-
102
charset = @raw.respond_to?(:encoding) ? @raw.encoding.to_s.downcase : "utf-8"
-
102
"application/xml; charset=#{charset}"
-
end
-
-
23
def bytesize
-
306
@raw.to_s.bytesize
-
end
-
-
23
def to_s
-
96
@raw.to_s
-
end
-
end
-
-
23
def encode(xml)
-
102
Encoder.new(xml)
-
end
-
-
begin
-
23
require "nokogiri"
-
-
23
def decode(response)
-
6
content_type = response.content_type.mime_type
-
-
6
raise HTTPX::Error, "invalid form mime type (#{content_type})" unless MIME_TYPES.match?(content_type)
-
-
6
Nokogiri::XML.method(:parse)
-
end
-
rescue LoadError
-
def decode(_response)
-
raise HTTPX::Error, "\"nokogiri\" is required in order to decode XML"
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
23
module HTTPX
-
23
module Utils
-
23
using URIExtensions
-
-
23
TOKEN = %r{[^\s()<>,;:\\"/\[\]?=]+}.freeze
-
23
VALUE = /"(?:\\"|[^"])*"|#{TOKEN}/.freeze
-
23
FILENAME_REGEX = /\s*filename=(#{VALUE})/.freeze
-
23
FILENAME_EXTENSION_REGEX = /\s*filename\*=(#{VALUE})/.freeze
-
-
23
module_function
-
-
23
def now
-
3698401
Process.clock_gettime(Process::CLOCK_MONOTONIC)
-
end
-
-
23
def elapsed_time(monotonic_timestamp)
-
3675468
Process.clock_gettime(Process::CLOCK_MONOTONIC) - monotonic_timestamp
-
end
-
-
# The value of this field can be either an HTTP-date or a number of
-
# seconds to delay after the response is received.
-
23
def parse_retry_after(retry_after)
-
# first: bet on it being an integer
-
36
Integer(retry_after)
-
rescue ArgumentError
-
# Then it's a datetime
-
12
time = Time.httpdate(retry_after)
-
12
time - Time.now
-
end
-
-
23
def get_filename(header, _prefix_regex = nil)
-
66
filename = nil
-
55
case header
-
when FILENAME_REGEX
-
42
filename = Regexp.last_match(1)
-
42
filename = Regexp.last_match(1) if filename =~ /^"(.*)"$/
-
when FILENAME_EXTENSION_REGEX
-
12
filename = Regexp.last_match(1)
-
12
encoding, _, filename = filename.split("'", 3)
-
end
-
-
66
return unless filename
-
-
102
filename = URI::DEFAULT_PARSER.unescape(filename) if filename.scan(/%.?.?/).all? { |s| /%[0-9a-fA-F]{2}/.match?(s) }
-
-
54
filename.scrub!
-
-
54
filename = filename.gsub(/\\(.)/, '\1') unless /\\[^\\"]/.match?(filename)
-
-
54
filename.force_encoding ::Encoding.find(encoding) if encoding
-
-
54
filename
-
end
-
-
23
URIParser = URI::RFC2396_Parser.new
-
-
23
def to_uri(uri)
-
12246
return URI(uri) unless uri.is_a?(String) && !uri.ascii_only?
-
-
25
uri = URI(URIParser.escape(uri))
-
-
25
non_ascii_hostname = URIParser.unescape(uri.host)
-
-
25
non_ascii_hostname.force_encoding(Encoding::UTF_8)
-
-
25
idna_hostname = Punycode.encode_hostname(non_ascii_hostname)
-
-
25
uri.host = idna_hostname
-
24
uri.non_ascii_hostname = non_ascii_hostname
-
24
uri
-
end
-
end
-
end