Class: HTTPX::Connection
- Inherits:
-
Object
- Object
- HTTPX::Connection
- Extended by:
- Forwardable
- Defined in:
- lib/httpx/connection.rb,
sig/connection.rbs
Overview
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.
Defined Under Namespace
Modules: _Parser Classes: HTTP1, HTTP2
Constant Summary
Constants included from Loggable
Loggable::COLORS, Loggable::USE_DEBUG_LOG
Instance Attribute Summary collapse
-
#current_selector ⇒ Object
writeonly
Sets the attribute current_selector.
-
#current_session ⇒ Session?
Returns the value of attribute current_session.
-
#family ⇒ Integer?
Returns the value of attribute family.
-
#io ⇒ TCP, ...
readonly
Returns the value of attribute io.
-
#options ⇒ Options
readonly
Returns the value of attribute options.
-
#origin ⇒ http_uri
readonly
Returns the value of attribute origin.
-
#origins ⇒ Array[String]
readonly
Returns the value of attribute origins.
-
#pending ⇒ Array[Request]
readonly
Returns the value of attribute pending.
-
#sibling ⇒ instance?
Returns the value of attribute sibling.
-
#ssl_session ⇒ OpenSSL::SSL::Session?
readonly
Returns the value of attribute ssl_session.
-
#state ⇒ Symbol
readonly
Returns the value of attribute state.
-
#type ⇒ io_type
readonly
Returns the value of attribute type.
Instance Method Summary collapse
- #addresses ⇒ Array[Resolver::Entry]?
-
#addresses=(addrs) ⇒ void
this is a semi-private method, to be used by the resolver to initiate the io object.
- #addresses? ⇒ Boolean
-
#build_altsvc_connection(alt_origin, origin, alt_params) ⇒ void
returns an HTTPX::Connection for the negotiated Alternative Service (or none).
- #build_parser(protocol = @io.protocol) ⇒ Object & _Parser
- #build_socket(addrs = nil) ⇒ TCP, ...
- #call ⇒ void
- #close ⇒ void
- #close_sibling ⇒ void
-
#coalescable?(connection) ⇒ Boolean
coalescable connections need to be mergeable! but internally, #mergeable? is called before #coalescable?.
-
#coalesce!(connection) ⇒ void
coalesces
selfintoconnection. - #coalesced? ⇒ Boolean
- #connect ⇒ void
- #connecting? ⇒ Boolean
- #consume ⇒ void
- #current_context? ⇒ Boolean
- #deactivate ⇒ void
-
#disconnect ⇒ void
disconnects from the current session it's attached to.
- #enqueue_pending_requests_from_parser(parser) ⇒ void
- #exhausted? ⇒ boolish
-
#force_close(delete_pending = false) ⇒ void
bypasses state machine rules while setting the connection in the :closed state.
- #force_purge ⇒ void
-
#force_reset(cloned = false) ⇒ void
bypasses the state machine to force closing of connections still connecting.
- #handle_connect_error(error) ⇒ void
-
#handle_error(error, request = nil) ⇒ void
recover internal state and emit all relevant error responses when
errorwas raised. - #handle_socket_timeout(interval) ⇒ void
- #handle_transition(nextstate) ⇒ void
- #idling ⇒ void
- #inflight? ⇒ Boolean
- #initial_call ⇒ void
-
#initialize(uri, options) ⇒ Connection
constructor
A new instance of Connection.
- #initialize_type(uri, options) ⇒ io_type
-
#inspect ⇒ Object
simplecov:disable.
- #interests ⇒ io_interests?
- #io_connected? ⇒ Boolean
- #match?(uri, options) ⇒ Boolean
- #merge(connection) ⇒ void
- #mergeable?(connection) ⇒ Boolean
-
#no_more_requests? ⇒ Boolean
true when there are no more pending nor inflight (in parser) requests.
- #no_more_requests_loop_check ⇒ void
- #on_connect_error(e) ⇒ void
- #on_error(error, request = nil) ⇒ void
- #on_io_error(e) ⇒ void
- #open? ⇒ Boolean
- #parser ⇒ Object & _Parser
- #parser_type(protocol) ⇒ singleton(HTTP1), singleton(HTTP2)
- #peer ⇒ URI::Generic
- #ping(_request) ⇒ void
- #pong ⇒ void
- #purge_after_closed ⇒ void
- #purge_pending {|request| ... } ⇒ void
- #read_timeout_callback(request, timeout, error_type = ReadTimeoutError) ⇒ void
- #reset ⇒ void
- #send(request) ⇒ void
- #send_pending ⇒ void
- #send_request_to_parser(request) ⇒ void
- #set_parser_callbacks(parser) ⇒ void
- #set_request_read_timeout(request) ⇒ void
- #set_request_request_timeout(request) ⇒ void
- #set_request_timeout(label, request, timeout, start_event, finish_events) { ... } ⇒ void
- #set_request_timeouts(request) ⇒ void
- #set_request_total_request_timeout(request) ⇒ void
- #set_request_write_timeout(request) ⇒ void
- #terminate ⇒ void
- #timeout ⇒ interval?
- #to_io ⇒ IO
- #transition(nextstate) ⇒ void
- #used? ⇒ Boolean
- #write_timeout_callback(request, timeout) ⇒ void
Methods included from Callbacks
#callbacks, #callbacks_for?, #emit, #on, #once
Methods included from Loggable
#log, #log_exception, log_identifiers, #log_redact, #log_redact_body, #log_redact_headers
Constructor Details
#initialize(uri, options) ⇒ Connection
Returns a new instance of Connection.
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/httpx/connection.rb', line 47 def initialize(uri, ) @current_session = @current_selector = @max_concurrent_requests = @parser = @sibling = @coalesced_connection = @altsvc_connection = @ping_timer = @family = @io = @ssl_session = @timeout = @connected_at = @response_received_at = nil @exhausted = @cloned = @main_sibling = false @options = Options.new() @type = initialize_type(uri, @options) @origins = [uri.origin] @origin = Utils.to_uri(uri.origin) @window_size = @options.window_size @read_buffer = Buffer.new(@options.buffer_size) @write_buffer = Buffer.new(@options.buffer_size) @pending = [] @inflight = 0 @keep_alive_timeout = @options.timeout[:keep_alive_timeout] @no_more_requests_counter = 0 if @options.io # if there's an already open IO, get its # peer address, and force-initiate the parser transition(:already_open) @io = build_socket parser else transition(:idle) end self.addresses = @options.addresses if @options.addresses end |
Instance Attribute Details
#current_selector=(value) ⇒ Object (writeonly)
Sets the attribute current_selector
41 42 43 |
# File 'lib/httpx/connection.rb', line 41 def current_selector=(value) @current_selector = value end |
#current_session ⇒ Session?
Returns the value of attribute current_session.
43 44 45 |
# File 'lib/httpx/connection.rb', line 43 def current_session @current_session end |
#family ⇒ Integer?
Returns the value of attribute family.
43 44 45 |
# File 'lib/httpx/connection.rb', line 43 def family @family end |
#io ⇒ TCP, ... (readonly)
Returns the value of attribute io.
39 40 41 |
# File 'lib/httpx/connection.rb', line 39 def io @io end |
#options ⇒ Options (readonly)
Returns the value of attribute options.
39 40 41 |
# File 'lib/httpx/connection.rb', line 39 def @options end |
#origin ⇒ http_uri (readonly)
Returns the value of attribute origin.
39 40 41 |
# File 'lib/httpx/connection.rb', line 39 def origin @origin end |
#origins ⇒ Array[String] (readonly)
Returns the value of attribute origins.
39 40 41 |
# File 'lib/httpx/connection.rb', line 39 def origins @origins end |
#pending ⇒ Array[Request] (readonly)
Returns the value of attribute pending.
39 40 41 |
# File 'lib/httpx/connection.rb', line 39 def pending @pending end |
#sibling ⇒ instance?
Returns the value of attribute sibling.
39 40 41 |
# File 'lib/httpx/connection.rb', line 39 def sibling @sibling end |
#ssl_session ⇒ OpenSSL::SSL::Session? (readonly)
Returns the value of attribute ssl_session.
39 40 41 |
# File 'lib/httpx/connection.rb', line 39 def ssl_session @ssl_session end |
#state ⇒ Symbol (readonly)
Returns the value of attribute state.
39 40 41 |
# File 'lib/httpx/connection.rb', line 39 def state @state end |
#type ⇒ io_type (readonly)
Returns the value of attribute type.
39 40 41 |
# File 'lib/httpx/connection.rb', line 39 def type @type end |
Instance Method Details
#addresses ⇒ Array[Resolver::Entry]?
93 94 95 |
# File 'lib/httpx/connection.rb', line 93 def addresses @io && @io.addresses end |
#addresses=(addrs) ⇒ void
This method returns an undefined value.
this is a semi-private method, to be used by the resolver to initiate the io object.
85 86 87 88 89 90 91 |
# File 'lib/httpx/connection.rb', line 85 def addresses=(addrs) if @io @io.add_addresses(addrs) else @io = build_socket(addrs) end end |
#addresses? ⇒ Boolean
97 98 99 |
# File 'lib/httpx/connection.rb', line 97 def addresses? @io && @io.addresses? end |
#build_altsvc_connection(alt_origin, origin, alt_params) ⇒ void
This method returns an undefined value.
returns an HTTPX::Connection for the negotiated Alternative Service (or none).
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 |
# File 'lib/httpx/connection.rb', line 923 def build_altsvc_connection(alt_origin, origin, alt_params) return if @altsvc_connection # do not allow security downgrades on altsvc negotiation return if @origin.scheme == "https" && alt_origin.scheme != "https" altsvc = AltSvc.cached_altsvc_set(origin, alt_params.merge("origin" => alt_origin)) # altsvc already exists, somehow it wasn't advertised, probably noop return unless altsvc = @options.merge(ssl: @options.ssl.merge(hostname: URI(origin).host)) connection = @current_session.find_connection(alt_origin, @current_selector, ) # advertised altsvc is the same origin being used, ignore return if connection == self connection.extend(AltSvc::ConnectionMixin) unless connection.is_a?(AltSvc::ConnectionMixin) @altsvc_connection = connection log(level: 1) { "#{origin}: alt-svc connection##{connection.object_id} established to #{alt_origin}" } connection.merge(self) rescue UnsupportedSchemeError altsvc["noop"] = true nil end |
#build_parser(protocol = @io.protocol) ⇒ Object & _Parser
679 680 681 682 683 684 |
# File 'lib/httpx/connection.rb', line 679 def build_parser(protocol = @io.protocol) parser = parser_type(protocol).new(@write_buffer, @options) set_parser_callbacks(parser) parser.max_concurrent_requests = @max_concurrent_requests if @max_concurrent_requests && parser.respond_to?(:max_concurrent_requests=) parser end |
#build_socket(addrs = nil) ⇒ TCP, ...
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 |
# File 'lib/httpx/connection.rb', line 953 def build_socket(addrs = nil) case @type when "tcp" TCP.new(peer, addrs, @options) when "ssl" SSL.new(peer, addrs, @options) do |sock| sock.ssl_session = @ssl_session sock.session_new_cb do |sess| @ssl_session = sess sock.ssl_session = sess end end when "unix" path = Array(addrs).first path = String(path) if path UNIX.new(peer, path, @options) else raise Error, "unsupported transport (#{@type})" end end |
#call ⇒ void
This method returns an undefined value.
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 |
# File 'lib/httpx/connection.rb', line 217 def call case @state when :idle return if no_more_requests? connect # when opening the tcp or ssl socket fails return if @state == :closed consume when :closed return if no_more_requests? # there are pending requests to send, restart the state machine. idling # @fiber-switch-guard # fiber may have switch after ensuring that @io is closed. return unless @state == :idle call when :closing consume transition(:closed) # @fiber-switch-guard # fiber may have switch while closing @io. return if @state == :closed && # only remain here if there are pending requests. @pending.empty? call when :open consume end nil rescue Errno::ECONNRESET, Errno::EINVAL, SocketError, IOError, TLSError => e @write_buffer.clear on_io_error(e) rescue Error => e @write_buffer.clear on_error(e) rescue Exception => e # rubocop:disable Lint/RescueException force_close(true) raise e end |
#close ⇒ void
This method returns an undefined value.
273 274 275 276 277 |
# File 'lib/httpx/connection.rb', line 273 def close transition(:active) if @state == :inactive @parser.close if @parser end |
#close_sibling ⇒ void
This method returns an undefined value.
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 |
# File 'lib/httpx/connection.rb', line 877 def close_sibling sibling = @sibling return unless sibling if sibling.io_connected? reset # TODO: transition connection to closed end unless sibling.state == :closed merge(sibling) unless @main_sibling sibling.force_reset(true) end @sibling = nil end |
#coalescable?(connection) ⇒ Boolean
coalescable connections need to be mergeable! but internally, #mergeable? is called before #coalescable?
138 139 140 141 142 143 144 145 146 147 |
# File 'lib/httpx/connection.rb', line 138 def coalescable?(connection) if @io.protocol == "h2" && @origin.scheme == "https" && connection.origin.scheme == "https" && @io.can_verify_peer? @io.verify_hostname(connection.origin.host) else @origin == connection.origin end end |
#coalesce!(connection) ⇒ void
This method returns an undefined value.
coalesces self into connection.
125 126 127 128 129 130 |
# File 'lib/httpx/connection.rb', line 125 def coalesce!(connection) @coalesced_connection = connection close_sibling connection.merge(self) end |
#coalesced? ⇒ Boolean
132 133 134 |
# File 'lib/httpx/connection.rb', line 132 def coalesced? @coalesced_connection end |
#connect ⇒ void
This method returns an undefined value.
493 494 495 |
# File 'lib/httpx/connection.rb', line 493 def connect transition(:open) end |
#connecting? ⇒ Boolean
184 185 186 |
# File 'lib/httpx/connection.rb', line 184 def connecting? @state == :idle end |
#consume ⇒ void
This method returns an undefined value.
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 |
# File 'lib/httpx/connection.rb', line 497 def consume return unless @io catch(:called) do epiped = false loop do # connection may have return if @state == :idle parser.consume # we exit if there's no more requests to process # # this condition takes into account: # # * the number of pending requests # * the number of inflight requests # * whether the write buffer has bytes (i.e. for close handshake) if no_more_requests? && @write_buffer.empty? no_more_requests_loop_check if @parser && @parser.pending.any? # terminate if an altsvc connection has been established terminate if @altsvc_connection return end @timeout = @current_timeout read_drained = false write_drained = nil # # tight read loop. # # read as much of the socket as possible. # # this tight loop reads all the data it can from the socket and pipes it to # its parser. # loop do siz = @io.read(@window_size, @read_buffer) log(level: 3, color: :cyan) { "IO READ: #{siz} bytes... (wsize: #{@window_size}, rbuffer: #{@read_buffer.bytesize})" } unless siz @write_buffer.clear ex = EOFError.new("descriptor closed") ex.set_backtrace(caller) on_error(ex) return end # socket has been drained. mark and exit the read loop. if siz.zero? read_drained = @read_buffer.empty? epiped = false break end parser << @read_buffer.to_s # continue reading if possible. break if interests == :w && !epiped # exit the read loop if connection is preparing to be closed break if @state == :closing || @state == :closed # exit #consume altogether if all outstanding requests have been dealt with if no_more_requests? && @write_buffer.empty? # rubocop:disable Style/Next no_more_requests_loop_check if @parser && @parser.pending.any? # terminate if an altsvc connection has been established terminate if @altsvc_connection return end end unless ((ints = interests).nil? || ints == :w || @state == :closing) && !epiped # # tight write loop. # # flush as many bytes as the sockets allow. # loop do # buffer has been drained, mark and exit the write loop. if @write_buffer.empty? # we only mark as drained on the first loop write_drained = write_drained.nil? && @inflight.positive? break end begin 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. log(level: 2) { "pipe broken, could not flush buffer..." } epiped = true read_drained = false break end log(level: 3, color: :cyan) { "IO WRITE: #{siz} bytes..." } unless siz @write_buffer.clear ex = EOFError.new("descriptor closed") ex.set_backtrace(caller) on_error(ex) return end # socket closed for writing. mark and exit the write loop. if siz.zero? write_drained = !@write_buffer.empty? break end # exit write loop if marked to consume from peer, or is closing. break if interests == :r || @state == :closing || @state == :closed write_drained = false end unless (ints = interests) == :r send_pending if @state == :open # return if socket is drained 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; log(level: 3) { "(#{ints}): WAITING FOR EVENTS..." } return end end end |
#current_context? ⇒ Boolean
83 |
# File 'sig/connection.rbs', line 83
def current_context?: () -> bool
|
#deactivate ⇒ void
This method returns an undefined value.
398 399 400 |
# File 'lib/httpx/connection.rb', line 398 def deactivate transition(:inactive) end |
#disconnect ⇒ void
This method returns an undefined value.
disconnects from the current session it's attached to
433 434 435 436 437 438 439 440 441 |
# File 'lib/httpx/connection.rb', line 433 def disconnect return if @exhausted # it'll reset return unless (current_session = @current_session) && (current_selector = @current_selector) @current_session = @current_selector = nil current_session.deselect_connection(self, current_selector, @cloned) end |
#enqueue_pending_requests_from_parser(parser) ⇒ void
This method returns an undefined value.
665 666 667 668 669 670 671 672 673 674 675 676 677 |
# File 'lib/httpx/connection.rb', line 665 def enqueue_pending_requests_from_parser(parser) parser.reset_requests # move sequential requests back to pending queue. parser_pending_requests = parser.pending return if parser_pending_requests.empty? # the connection will be reused, so parser requests must come # back to the pending list before the parser is reset. @inflight -= parser_pending_requests.size @pending.unshift(*parser_pending_requests) parser.pending.clear end |
#exhausted? ⇒ boolish
139 |
# File 'sig/connection.rbs', line 139
def exhausted?: () -> boolish
|
#force_close(delete_pending = false) ⇒ void
This method returns an undefined value.
bypasses state machine rules while setting the connection in the :closed state.
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 |
# File 'lib/httpx/connection.rb', line 298 def force_close(delete_pending = false) force_purge return unless @state == :closed if delete_pending @pending.clear elsif (parser = @parser) enqueue_pending_requests_from_parser(parser) end return unless @pending.empty? disconnect emit(:force_closed, delete_pending) end |
#force_purge ⇒ void
This method returns an undefined value.
863 864 865 866 867 868 869 870 871 872 873 874 875 |
# File 'lib/httpx/connection.rb', line 863 def force_purge return if @state == :closed @state = :closed @write_buffer.clear begin purge_after_closed rescue IOError # may be raised when closing the socket. # due to connection reuse / fiber scheduling, it may # have been reopened, to bail out in that case. end end |
#force_reset(cloned = false) ⇒ void
This method returns an undefined value.
bypasses the state machine to force closing of connections still connecting. only used for Happy Eyeballs v2.
316 317 318 319 320 |
# File 'lib/httpx/connection.rb', line 316 def force_reset(cloned = false) @state = :closing @cloned = cloned transition(:closed) end |
#handle_connect_error(error) ⇒ void
This method returns an undefined value.
424 425 426 427 428 429 430 |
# File 'lib/httpx/connection.rb', line 424 def handle_connect_error(error) return on_error(error) unless @sibling && @sibling.connecting? @sibling.merge(self) force_reset(true) end |
#handle_error(error, request = nil) ⇒ void
This method returns an undefined value.
recover internal state and emit all relevant error responses when error was raised.
this takes an optiona request which may have already been handled and can be opted out
in the state recovery process.
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 |
# File 'lib/httpx/connection.rb', line 1020 def handle_error(error, request = nil) if request @inflight -= 1 response = ErrorResponse.new(request, error) request.response = response request.emit_response(response) end pending = @pending if (parser = @parser) && parser.respond_to?(:handle_error) # parser.handle_error may disconnect the connection pending = @pending.dup @pending = [] parser.handle_error(error, request) end while (req = pending.shift) next if request && req == request resp = ErrorResponse.new(req, error) req.response = resp req.emit_response(resp) end end |
#handle_socket_timeout(interval) ⇒ void
This method returns an undefined value.
406 407 408 409 410 |
# File 'lib/httpx/connection.rb', line 406 def handle_socket_timeout(interval) error = OperationTimeoutError.new(interval, "timed out while waiting on select") error.set_backtrace(caller) on_error(error) end |
#handle_transition(nextstate) ⇒ void
This method returns an undefined value.
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 |
# File 'lib/httpx/connection.rb', line 792 def handle_transition(nextstate) case nextstate when :idle @timeout = @current_timeout = @options.timeout[:connect_timeout] @connected_at = @response_received_at = nil when :open return if @state == :closed @io.connect close_sibling if @io.state == :connected return unless @io.connected? @connected_at = Utils.now send_pending @timeout = @current_timeout = parser.timeout emit(:open) when :inactive return unless @state == :open # @type ivar @parser: HTTP1 | HTTP2 # do not deactivate connection in use return if @inflight.positive? || @parser.waiting_for_ping? when :closing return unless connecting? || @state == :open when :closed return unless @state == :closing return unless @write_buffer.empty? purge_after_closed # @fiber-switch-guard return unless @state == :closing && (@io.nil? || @io.can_disconnect?) when :already_open nextstate = :open # the first check for given io readiness must still use a timeout. # connect is the reasonable choice in such a case. @timeout = @options.timeout[:connect_timeout] send_pending when :active return unless @state == :inactive nextstate = :open # activate @current_session.select_connection(self, @current_selector) end log(level: 3) { "#{@state} -> #{nextstate}" } @state = nextstate # post state change case nextstate when :inactive disconnect when :closing return if @write_buffer.empty? # try flushing termination handshakes consume @write_buffer.clear when :closed # TODO: should this raise an error instead? return unless @pending.empty? disconnect end end |
#idling ⇒ void
This method returns an undefined value.
381 382 383 384 385 386 387 388 389 390 391 392 |
# File 'lib/httpx/connection.rb', line 381 def idling purge_after_closed return unless @state == :closed @write_buffer.clear transition(:idle) return unless @parser enqueue_pending_requests_from_parser(parser) @parser = nil end |
#inflight? ⇒ Boolean
188 189 190 191 192 193 194 195 |
# File 'lib/httpx/connection.rb', line 188 def inflight? @parser && ( # parser may be dealing with other requests (possibly started from a different fiber) !@parser.empty? || # connection may be doing connection termination handshake !@write_buffer.empty? ) end |
#initial_call ⇒ void
This method returns an undefined value.
269 270 271 |
# File 'lib/httpx/connection.rb', line 269 def initial_call call end |
#initialize_type(uri, options) ⇒ io_type
909 910 911 912 913 914 915 916 917 918 919 920 |
# File 'lib/httpx/connection.rb', line 909 def initialize_type(uri, ) .transport || begin case uri.scheme when "http" "tcp" when "https" "ssl" else raise UnsupportedSchemeError, "#{uri}: #{uri.scheme}: unsupported URI scheme" end end end |
#inspect ⇒ Object
simplecov:disable
482 483 484 485 486 487 488 |
# File 'lib/httpx/connection.rb', line 482 def inspect "#<#{self.class}:#{object_id} " \ "@origin=#{@origin} " \ "@state=#{@state} " \ "@pending=#{@pending.size} " \ "@io=#{@io}>" end |
#interests ⇒ io_interests?
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 |
# File 'lib/httpx/connection.rb', line 197 def interests # connecting if connecting? connect return @io.interests if connecting? end return @parser.interests if @parser nil rescue Error => e on_error(e) nil end |
#io_connected? ⇒ Boolean
178 179 180 181 182 |
# File 'lib/httpx/connection.rb', line 178 def io_connected? return @coalesced_connection.io_connected? if @coalesced_connection @io && @io.state == :connected end |
#match?(uri, options) ⇒ Boolean
101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/httpx/connection.rb', line 101 def match?(uri, ) return false if !used? && (@state == :closing || @state == :closed) @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 (@origins.size == 1 || @origin == uri.origin || (@io.is_a?(SSL) && @io.verify_hostname(uri.host))) && @options.() end |
#merge(connection) ⇒ void
This method returns an undefined value.
149 150 151 152 153 154 155 156 157 158 159 160 161 |
# File 'lib/httpx/connection.rb', line 149 def merge(connection) @origins |= connection.instance_variable_get(:@origins) if @ssl_session.nil? && connection.ssl_session @ssl_session = connection.ssl_session @io.session_new_cb do |sess| @ssl_session = sess end if @io end connection.purge_pending do |req| req.transition(:idle) send(req) end end |
#mergeable?(connection) ⇒ Boolean
113 114 115 116 117 118 119 120 121 122 |
# File 'lib/httpx/connection.rb', line 113 def mergeable?(connection) return false if @state == :closing || @state == :closed || !@io return false unless connection.addresses ( (open? && @origin == connection.origin) || !(@io.addresses & (connection.addresses || [])).empty? ) && @options.(connection.) end |
#no_more_requests? ⇒ Boolean
true when there are no more pending nor inflight (in parser) requests
1013 1014 1015 |
# File 'lib/httpx/connection.rb', line 1013 def no_more_requests? @pending.empty? && @inflight.zero? end |
#no_more_requests_loop_check ⇒ void
This method returns an undefined value.
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 |
# File 'lib/httpx/connection.rb', line 1001 def no_more_requests_loop_check log(level: 3) { "NO MORE REQUESTS..." } @no_more_requests_counter += 1 return if @no_more_requests_counter < 50 raise Error, "connection corrupted, aborted after looping for a while, " \ "please report this https://gitlab.com/os85/httpx/-/work_items " \ "along with debug logs" end |
#on_connect_error(e) ⇒ void
This method returns an undefined value.
443 444 445 446 447 448 449 |
# File 'lib/httpx/connection.rb', line 443 def on_connect_error(e) # connect errors, exit gracefully error = ConnectionError.new(e.) error.set_backtrace(e.backtrace) handle_connect_error(error) if connecting? force_close end |
#on_error(error, request = nil) ⇒ void
This method returns an undefined value.
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 |
# File 'lib/httpx/connection.rb', line 461 def on_error(error, request = nil) if error.is_a?(OperationTimeoutError) # inactive connections do not contribute to the select loop, therefore # they should not fail due to such errors. return if @state == :inactive if @timeout @timeout -= error.timeout return unless @timeout <= 0 @timeout = nil end error = error.to_connection_error if connecting? end handle_error(error, request) reset end |
#on_io_error(e) ⇒ void
This method returns an undefined value.
451 452 453 454 455 456 457 458 459 |
# File 'lib/httpx/connection.rb', line 451 def on_io_error(e) on_error(e) # do not force close if parser resets the connection. # can happen i.e. when HTTP/1.1 pipelining is disabled. return if @state == :idle && @pending.any? force_close(true) end |
#open? ⇒ Boolean
402 403 404 |
# File 'lib/httpx/connection.rb', line 402 def open? @state == :open || @state == :inactive end |
#parser ⇒ Object & _Parser
645 646 647 |
# File 'lib/httpx/connection.rb', line 645 def parser @parser ||= build_parser end |
#parser_type(protocol) ⇒ singleton(HTTP1), singleton(HTTP2)
1143 1144 1145 1146 1147 1148 1149 1150 |
# File 'lib/httpx/connection.rb', line 1143 def parser_type(protocol) case protocol when "h2" then @options.http2_class when "http/1.1" then @options.http1_class else raise Error, "unsupported protocol (##{protocol})" end end |
#peer ⇒ URI::Generic
79 80 81 |
# File 'lib/httpx/connection.rb', line 79 def peer @origin end |
#ping(_request) ⇒ void
This method returns an undefined value.
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 |
# File 'lib/httpx/connection.rb', line 977 def ping(_request) return if parser.waiting_for_ping? parser.ping ping_timeout = @options.timeout[:ping_timeout] @ping_timer = @current_selector.after(ping_timeout) do log(level: 3) { "ping timeout expired..." } error = PingTimeoutError.new(ping_timeout, "Timed out after #{ping_timeout} seconds") on_error(error) end call end |
#pong ⇒ void
This method returns an undefined value.
993 994 995 996 997 998 999 |
# File 'lib/httpx/connection.rb', line 993 def pong @ping_timer.cancel @ping_timer = nil @response_received_at = Utils.now @no_more_requests_counter = 0 send_pending end |
#purge_after_closed ⇒ void
This method returns an undefined value.
895 896 897 898 899 900 901 902 903 904 905 906 907 |
# File 'lib/httpx/connection.rb', line 895 def purge_after_closed if @io @io.close # @fiber-switch-guard # due to fiber scheduler, multiple fibers may be listening on the same connection # and moving the state machine forward; in such cases, when the control flow reaches # this line, the io object may not be closed anymore. return unless @io&.can_disconnect? end @read_buffer.clear @timeout = nil end |
#purge_pending {|request| ... } ⇒ void
This method returns an undefined value.
163 164 165 166 167 168 169 170 171 172 173 174 175 176 |
# File 'lib/httpx/connection.rb', line 163 def purge_pending(&block) if @parser pending = @parser.pending @inflight -= pending.size pending.reject! do |req| block.call(req) true end end @pending.reject! do |req| block.call(req) true end end |
#read_timeout_callback(request, timeout, error_type = ReadTimeoutError) ⇒ void
This method returns an undefined value.
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 |
# File 'lib/httpx/connection.rb', line 1093 def read_timeout_callback(request, timeout, error_type = ReadTimeoutError) response = request.response return if response && response.finished? @write_buffer.clear error = error_type.new(request, response, timeout) request.handle_error(error) end |
#reset ⇒ void
This method returns an undefined value.
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 |
# File 'lib/httpx/connection.rb', line 322 def reset return if @state == :closing || @state == :closed # do not reset a connection which may have restarted back to :idle, such when the parser resets # (example: HTTP/1 parser disabling pipelining) return if @state == :idle && @pending.any? if @ping_timer @ping_timer.cancel @ping_timer = nil end parser = @parser if parser && parser.respond_to?(:max_concurrent_requests) # if connection being reset has at some downgraded the number of concurrent # requests, such as in the case where an attempt to use HTTP/1 pipelining failed, # keep that information around. @max_concurrent_requests = parser.max_concurrent_requests end transition(:closing) transition(:closed) end |
#send(request) ⇒ void
This method returns an undefined value.
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
# File 'lib/httpx/connection.rb', line 348 def send(request) return @coalesced_connection.send(request) if @coalesced_connection if @parser && !@write_buffer.full? 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. log(level: 3) { "keep alive timeout expired, pinging connection..." } @pending << request transition(:active) if @state == :inactive request.ping! ping(request) return end send_request_to_parser(request) else @pending << request end end |
#send_pending ⇒ void
This method returns an undefined value.
639 640 641 642 643 |
# File 'lib/httpx/connection.rb', line 639 def send_pending while !@write_buffer.full? && (request = @pending.shift) send_request_to_parser(request) end end |
#send_request_to_parser(request) ⇒ void
This method returns an undefined value.
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 |
# File 'lib/httpx/connection.rb', line 649 def send_request_to_parser(request) @inflight += 1 request.peer_address = @io.ip && @io.ip.address set_request_timeouts(request) parser.send(request) return unless @state == :inactive transition(:active) # mark request as ping, as this inactive connection may have been # closed by the server, and we don't want that to influence retry # bookkeeping. request.ping! end |
#set_parser_callbacks(parser) ⇒ void
This method returns an undefined value.
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 |
# File 'lib/httpx/connection.rb', line 686 def set_parser_callbacks(parser) parser.on(:response) do |request, response| AltSvc.emit(request, response) do |alt_origin, origin, alt_params| build_altsvc_connection(alt_origin, origin, alt_params) end @response_received_at = Utils.now @no_more_requests_counter = 0 @inflight -= 1 response.finish! request.emit_response(response) end parser.on(:altsvc) do |alt_origin, origin, alt_params| build_altsvc_connection(alt_origin, origin, alt_params) end parser.on(:pong, &method(:pong)) parser.on(:promise) do |request, stream| request.emit(:promise, parser, stream) end parser.on(:exhausted) do enqueue_pending_requests_from_parser(parser) @exhausted = true parser.close # @fiber-switch-guard # fiber may have switched while closing @io, check whether still in the exhausted loop. next unless @exhausted idling @exhausted = false end parser.on(:origin) do |origin| @origins |= [origin] end parser.on(:close) do reset end parser.on(:close_handshake) do consume unless @state == :closed end parser.on(:reset) do enqueue_pending_requests_from_parser(parser) reset next unless @state == :closed # :reset event only fired in http/1.1, so this guarantees # that the connection will be closed here. idling unless @pending.empty? end parser.on(:current_timeout) do @current_timeout = @timeout = parser.timeout end parser.on(:timeout) do |tout| @timeout = tout end parser.on(:error) do |request, error| case error when :http_1_1_required current_session = @current_session current_selector = @current_selector parser.close other_connection = current_session.find_connection(@origin, current_selector, @options.merge(ssl: { alpn_protocols: %w[http/1.1] })) other_connection.merge(self) request.transition(:idle) other_connection.send(request) next when OperationTimeoutError # request level timeouts should take precedence next unless request.active_timeouts.empty? end @inflight -= 1 response = ErrorResponse.new(request, error) request.response = response request.emit_response(response) end end |
#set_request_read_timeout(request) ⇒ void
This method returns an undefined value.
1054 1055 1056 1057 1058 1059 1060 1061 1062 |
# File 'lib/httpx/connection.rb', line 1054 def set_request_read_timeout(request) read_timeout = request.read_timeout return if read_timeout.nil? || read_timeout.infinite? set_request_timeout(:read_timeout, request, read_timeout, :done, :response) do read_timeout_callback(request, read_timeout) end end |
#set_request_request_timeout(request) ⇒ void
This method returns an undefined value.
1074 1075 1076 1077 1078 1079 1080 1081 1082 |
# File 'lib/httpx/connection.rb', line 1074 def set_request_request_timeout(request) request_timeout = request.request_timeout return if request_timeout.nil? || request_timeout.infinite? set_request_timeout(:request_timeout, request, request_timeout, :headers, :complete) do read_timeout_callback(request, request_timeout, RequestTimeoutError) end end |
#set_request_timeout(label, request, timeout, start_event, finish_events) { ... } ⇒ void
This method returns an undefined value.
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 |
# File 'lib/httpx/connection.rb', line 1116 def set_request_timeout(label, request, timeout, start_event, finish_events, &callback) request.set_timeout_callback(start_event) do unless (selector = @current_selector) raise Error, "request has been resend to an out-of-session connection, and this " \ "should never happen!!! Please report this error! " \ "(state:#{@state}, " \ "parser?:#{!!@parser}, " \ "bytes in write buffer?:#{!@write_buffer.empty?}, " \ "cloned?:#{@cloned}, " \ "sibling?:#{!!@sibling}, " \ "coalesced?:#{coalesced?})" end timer = selector.after(timeout, callback) timer.label = label request.active_timeouts << timer Array(finish_events).each do |event| # clean up request timeouts if the connection errors out request.set_timeout_callback(event) do timer.cancel request.active_timeouts.delete(timer) end end end end |
#set_request_timeouts(request) ⇒ void
This method returns an undefined value.
1046 1047 1048 1049 1050 1051 1052 |
# File 'lib/httpx/connection.rb', line 1046 def set_request_timeouts(request) request.connection = self set_request_write_timeout(request) set_request_read_timeout(request) set_request_request_timeout(request) set_request_total_request_timeout(request) end |
#set_request_total_request_timeout(request) ⇒ void
This method returns an undefined value.
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 |
# File 'lib/httpx/connection.rb', line 1104 def set_request_total_request_timeout(request) return if request.started? total_request_timeout = request.total_request_timeout return if total_request_timeout.nil? || total_request_timeout.infinite? set_request_timeout(:total_request_timeout, request, total_request_timeout, :headers, :complete) do read_timeout_callback(request, total_request_timeout, TotalRequestTimeoutError) end end |
#set_request_write_timeout(request) ⇒ void
This method returns an undefined value.
1064 1065 1066 1067 1068 1069 1070 1071 1072 |
# File 'lib/httpx/connection.rb', line 1064 def set_request_write_timeout(request) write_timeout = request.write_timeout return if write_timeout.nil? || write_timeout.infinite? set_request_timeout(:write_timeout, request, write_timeout, :headers, %i[done response]) do write_timeout_callback(request, write_timeout) end end |
#terminate ⇒ void
This method returns an undefined value.
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 |
# File 'lib/httpx/connection.rb', line 279 def terminate case @state when :idle purge_after_closed # @fiber-switch-guard if @io.can_disconnect? && @pending.empty? disconnect return end when :closed @connected_at = nil end close end |
#timeout ⇒ interval?
371 372 373 374 375 376 377 378 379 |
# File 'lib/httpx/connection.rb', line 371 def timeout return if @state == :closed || @state == :inactive return @timeout if @timeout return @options.timeout[:connect_timeout] if @state == :idle @options.timeout[:operation_timeout] end |
#to_io ⇒ IO
213 214 215 |
# File 'lib/httpx/connection.rb', line 213 def to_io @io.to_io end |
#transition(nextstate) ⇒ void
This method returns an undefined value.
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 |
# File 'lib/httpx/connection.rb', line 771 def transition(nextstate) 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 on_connect_error(e) rescue TLSError, ::HTTP2::Error::ProtocolError, ::HTTP2::Error::HandshakeError => e # connect errors, exit gracefully handle_error(e) handle_connect_error(e) if connecting? force_close end |
#used? ⇒ Boolean
394 395 396 |
# File 'lib/httpx/connection.rb', line 394 def used? @connected_at end |
#write_timeout_callback(request, timeout) ⇒ void
This method returns an undefined value.
1084 1085 1086 1087 1088 1089 1090 1091 |
# File 'lib/httpx/connection.rb', line 1084 def write_timeout_callback(request, timeout) return if request.state == :done @write_buffer.clear error = WriteTimeoutError.new(request, nil, timeout) request.handle_error(error) end |