diff --git a/lib/httpx/client.rb b/lib/httpx/client.rb index 7a7ba421..3e0493b9 100644 --- a/lib/httpx/client.rb +++ b/lib/httpx/client.rb @@ -7,6 +7,7 @@ module HTTPX def initialize(options = {}) @default_options = self.class.default_options.merge(options) @connection = Connection.new(@default_options) + @responses = {} if block_given? begin @keep_open = true @@ -33,10 +34,24 @@ module HTTPX private + def on_response(request, response) + @responses[request] = response + end + + def fetch_response(request) + response = @responses.delete(request) + if response.is_a?(ErrorResponse) && response.retryable? + channel = find_channel(request) + channel.send(request, retries: response.retries - 1) + return + end + response + end + def find_channel(request) uri = URI(request.uri) @connection.find_channel(uri) || - @connection.build_channel(uri) + @connection.build_channel(uri, &method(:on_response)) end def __build_reqs(*args, **options) @@ -71,7 +86,7 @@ module HTTPX # guarantee ordered responses loop do request = requests.shift - @connection.next_tick until response = @connection.response(request) + @connection.next_tick until response = fetch_response(request) responses << response diff --git a/lib/httpx/connection.rb b/lib/httpx/connection.rb index 2e3bf723..9cdbb4b3 100644 --- a/lib/httpx/connection.rb +++ b/lib/httpx/connection.rb @@ -10,7 +10,6 @@ module HTTPX @timeout = options.timeout @selector = Selector.new @channels = [] - @responses = {} end def running? @@ -39,17 +38,8 @@ module HTTPX end end - def response(request) - response = @responses.delete(request) - if response.is_a?(ErrorResponse) && response.retryable? - send(request, retries: response.retries - 1) - return - end - response - end - - def build_channel(uri) - channel = Channel.by(uri, @options, &method(:on_response)) + def build_channel(uri, &on_response) + channel = Channel.by(uri, @options, &on_response) register_channel(channel) channel end @@ -66,10 +56,6 @@ module HTTPX private - def on_response(request, response) - @responses[request] = response - end - def register_channel(channel) monitor = @selector.register(channel, :rw) monitor.value = channel diff --git a/lib/httpx/plugins/proxy.rb b/lib/httpx/plugins/proxy.rb index 950841f4..4ffd2191 100644 --- a/lib/httpx/plugins/proxy.rb +++ b/lib/httpx/plugins/proxy.rb @@ -53,7 +53,7 @@ module HTTPX uri = parameters.uri io = TCP.new(uri.host, uri.port, @default_options) proxy_type = Parameters.registry(parameters.uri.scheme) - channel = proxy_type.new(io, parameters, @default_options, &@connection.method(:on_response)) + channel = proxy_type.new(io, parameters, @default_options, &method(:on_response)) @connection.__send__(:register_channel, channel) channel end @@ -78,8 +78,8 @@ module HTTPX end class ProxyChannel < Channel - def initialize(io, parameters, options) - super(io, options) + def initialize(io, parameters, options, &blk) + super(io, options, &blk) @parameters = parameters @state = :idle end