Class: HTTPX::Connection

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Callbacks, Loggable
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

Instance Method Summary collapse

Methods included from Callbacks

#callbacks, #callbacks_for?, #emit, #on, #once

Methods included from Loggable

#log, #log_exception, log_identifiers

Instance Attribute Details

#current_selector ⇒ Object

Returns the value of attribute current_selector.



42
43
44
# File 'lib/httpx/connection.rb', line 42

def current_selector
  @current_selector
end

#current_session ⇒ Session?

Returns the value of attribute current_session.

Returns:



42
43
44
# File 'lib/httpx/connection.rb', line 42

def current_session
  @current_session
end

#family ⇒ Integer?

Returns the value of attribute family.

Returns:

  • (Integer, nil)


42
43
44
# File 'lib/httpx/connection.rb', line 42

def family
  @family
end

#io ⇒ TCP, ... (readonly)

Returns the value of attribute io.

Returns:



39
40
41
# File 'lib/httpx/connection.rb', line 39

def io
  @io
end

#options ⇒ Options (readonly)

Returns the value of attribute options.

Returns:



39
40
41
# File 'lib/httpx/connection.rb', line 39

def options
  @options
end

#origin ⇒ http_uri (readonly)

Returns the value of attribute origin.

Returns:

  • (http_uri)


39
40
41
# File 'lib/httpx/connection.rb', line 39

def origin
  @origin
end

#origins ⇒ Array[String] (readonly)

Returns the value of attribute origins.

Returns:

  • (Array[String])


39
40
41
# File 'lib/httpx/connection.rb', line 39

def origins
  @origins
end

#pending ⇒ Array[Request] (readonly)

Returns the value of attribute pending.

Returns:



39
40
41
# File 'lib/httpx/connection.rb', line 39

def pending
  @pending
end

#read_buffer ⇒ Buffer (readonly)

Returns the value of attribute read_buffer.

Returns:



39
40
41
# File 'lib/httpx/connection.rb', line 39

def read_buffer
  @read_buffer
end

#sibling ⇒ instance?

Returns the value of attribute sibling.

Returns:

  • (instance, nil)


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.

Returns:

  • (OpenSSL::SSL::Session, nil)


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.

Returns:

  • (Symbol)


39
40
41
# File 'lib/httpx/connection.rb', line 39

def state
  @state
end

#type ⇒ io_type (readonly)

Returns the value of attribute type.

Returns:

  • (io_type)


39
40
41
# File 'lib/httpx/connection.rb', line 39

def type
  @type
end

#write_buffer ⇒ Buffer (readonly)

Returns the value of attribute write_buffer.

Returns:



39
40
41
# File 'lib/httpx/connection.rb', line 39

def write_buffer
  @write_buffer
end

Instance Method Details

#addresses ⇒ Array[Resolver::Entry]?

Returns:



124
125
126
# File 'lib/httpx/connection.rb', line 124

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.

Parameters:



116
117
118
119
120
121
122
# File 'lib/httpx/connection.rb', line 116

def addresses=(addrs)
  if @io
    @io.add_addresses(addrs)
  else
    @io = build_socket(addrs)
  end
end

#addresses? ⇒ Boolean

Returns:

  • (Boolean)


128
129
130
# File 'lib/httpx/connection.rb', line 128

def addresses?
  @io && @io.addresses?
end

#call ⇒ void

This method returns an undefined value.



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/httpx/connection.rb', line 251

def call
  if @reset_timeout_on_call
    @timeout = nil
    @reset_timeout_on_call = false
  end

  case @state
  when :idle
    return if no_more_requests?

    try_connect

    # when opening the tcp or ssl socket fails
    return if @state == :closed

    consume
  when :closed
    return if no_requests_to_handle?

    # 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
    # if bytes are available, that's the client GOAWAY frame. Otherwise, the peer closed it.
    sending_goaway = !@write_buffer.empty?

    consume

    if sending_goaway
      # parser may have inflight streams which need terminating.
      @parser&.close
      transition(:closed)
    elsif @state == :closing
      return
    end

    # @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.



322
323
324
325
326
# File 'lib/httpx/connection.rb', line 322

def close
  transition(:active) if @state == :inactive

  @parser&.close
end

#closed_for_select? ⇒ Boolean

whether the connection can be removed from the selector.

Returns:

  • (Boolean)


220
221
222
# File 'lib/httpx/connection.rb', line 220

def closed_for_select?
  @state == :closed
end

#coalescable?(connection) ⇒ Boolean

coalescable connections need to be mergeable! but internally, #mergeable? is called before #coalescable?

Parameters:

Returns:

  • (Boolean)


172
173
174
175
176
177
178
179
180
181
# File 'lib/httpx/connection.rb', line 172

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.

Parameters:

  • connection (instance)


159
160
161
162
163
164
# File 'lib/httpx/connection.rb', line 159

def coalesce!(connection)
  @coalesced_connection = connection

  close_sibling
  connection.merge(self)
end

#coalesced? ⇒ Boolean

Returns:

  • (Boolean)


166
167
168
# File 'lib/httpx/connection.rb', line 166

def coalesced?
  @coalesced_connection
end

#connecting?(state = @state) ⇒ Boolean

Parameters:

  • state (Symbol) (defaults to: @state)

Returns:

  • (Boolean)


215
216
217
# File 'lib/httpx/connection.rb', line 215

def connecting?(state = @state)
  state == :idle
end

#current_context? ⇒ Boolean

Returns:

  • (Boolean)


87
# File 'sig/connection.rbs', line 87

def current_context?: () -> bool

#deactivate ⇒ void

This method returns an undefined value.



452
453
454
455
456
457
# File 'lib/httpx/connection.rb', line 452

def deactivate
  # safety net so that connection state does not corrupt.
  clear_pending_requests

  transition(:inactive)
end

#disconnect ⇒ Boolean

disconnects from the current session it's attached to

Returns:

  • (Boolean)


490
491
492
493
494
495
496
497
498
499
500
501
502
# File 'lib/httpx/connection.rb', line 490

def disconnect # rubocop:disable Naming/PredicateMethod
  return false if @exhausted # it'll reset

  return false unless (current_session = @current_session) && (current_selector = @current_selector)

  @current_session = @current_selector = nil

  # NOTE: don't change state of the connection after this call!
  # the connection is checked back into the pool, and may be checked out by
  # another thread before the next statement.
  current_session.deselect_connection(self, current_selector, @cloned)
  true
end

#force_close(delete_pending = false) ⇒ void

This method returns an undefined value.

bypasses state machine rules while setting the connection in the :closed state.

Parameters:

  • delete_pending (Boolean) (defaults to: false)


348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/httpx/connection.rb', line 348

def force_close(delete_pending = false)
  force_purge
  return unless @state == :closed

  if delete_pending
    @pending.clear
  elsif (parser = @parser)
    parser.reset_requests if parser.respond_to?(:reset_requests)
    return unless @pending.empty?
  end

  disconnect
  emit(:force_closed, delete_pending)
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.

Parameters:

  • cloned (Boolean) (defaults to: false)


365
366
367
368
369
# File 'lib/httpx/connection.rb', line 365

def force_reset(cloned = false)
  @state = :closing
  @cloned = cloned
  transition(:closed)
end

#handle_connect_error(error) ⇒ void

This method returns an undefined value.

Parameters:

  • error (StandardError)


481
482
483
484
485
486
487
# File 'lib/httpx/connection.rb', line 481

def handle_connect_error(error)
  return on_error(error) unless @sibling && @sibling.connecting?

  @sibling.merge(self)

  force_reset(true)
end

#handle_socket_timeout(interval) ⇒ void

This method returns an undefined value.

Parameters:

  • interval (interval)


463
464
465
466
467
# File 'lib/httpx/connection.rb', line 463

def handle_socket_timeout(interval)
  error = OperationTimeoutError.new(interval, "timed out while waiting on select")
  error.set_backtrace(caller)
  on_error(error)
end

#idling ⇒ void

This method returns an undefined value.



435
436
437
438
439
440
441
442
443
444
445
446
# File 'lib/httpx/connection.rb', line 435

def idling
  purge_after_closed

  return unless @state == :closed

  @write_buffer.clear
  transition(:idle)
  return unless @parser

  @parser.reset_requests if @parser.respond_to?(:reset_requests)
  @parser = nil
end

#inflight? ⇒ Boolean

Returns:

  • (Boolean)


224
225
226
227
228
229
230
231
# File 'lib/httpx/connection.rb', line 224

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.



318
319
320
# File 'lib/httpx/connection.rb', line 318

def initial_call
  call
end

#initialize_dup(orig) ⇒ Object

dupped initialization



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/httpx/connection.rb', line 89

def initialize_dup(orig)
  super
  @callbacks = @parser = @sibling = @coalesced_connection = @altsvc_connection = nil
  @origins = orig.origins.dup
  @read_buffer = orig.read_buffer.dup
  @write_buffer = orig.write_buffer.dup
  @pending = []
  transition(:idle)

  if @io
    # initialize new IO object with the same set of addresses
    addresses = @io.addresses
    @io = nil
    self.addresses = addresses
  end

  return unless @current_session && @current_selector

  @current_session.pin(self, @current_selector)
end

#inspect ⇒ Object

simplecov:disable



564
565
566
567
568
569
570
# File 'lib/httpx/connection.rb', line 564

def inspect
  "#<#{self.class}:#{object_id} " \
    "@origin=#{@origin} " \
    "@state=#{@state} " \
    "@pending=#{@pending.size} " \
    "@io=#{@io}>"
end

#interests ⇒ io_interests?

Returns:

  • (io_interests, nil)


233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/httpx/connection.rb', line 233

def interests
  # connecting
  if connecting?
    try_connect

    return @io.interests if connecting?
  end

  @parser&.interests
rescue Error => e
  on_error(e)
  nil
end

#io_connected? ⇒ Boolean

Returns:

  • (Boolean)


209
210
211
212
213
# File 'lib/httpx/connection.rb', line 209

def io_connected?
  return @coalesced_connection.io_connected? if @coalesced_connection

  @io && @io.state == :connected
end

#match?(uri, options) ⇒ Boolean

Parameters:

Returns:

  • (Boolean)


132
133
134
135
136
137
138
139
140
141
142
# File 'lib/httpx/connection.rb', line 132

def match?(uri, options)
  return false if @state == :closing || (!used? && @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.connection_options_match?(options)
end

#merge(connection) ⇒ void

This method returns an undefined value.

Parameters:



183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/httpx/connection.rb', line 183

def merge(connection)
  @origins |= connection.instance_variable_get(:@origins)
  if @ssl_session.nil? && (ssl_session = connection.ssl_session)
    @ssl_session = ssl_session
    # the socket only needs the merged session if it can still resume it,
    # i.e. if TLS hasn't been negotiated yet.
    @io.ssl_session = ssl_session if @io.is_a?(SSL) && !@io.connected?
  end
  connection.purge_pending do |req|
    req.transition(:idle)
    send(req)
  end
end

#mergeable?(connection) ⇒ Boolean

Parameters:

Returns:

  • (Boolean)


144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/httpx/connection.rb', line 144

def mergeable?(connection)
  return false if @state == :closing || @state == :closed || !@io

  # do not coalesce with HEv2 sibling
  return false if @sibling.equal?(connection)

  return false unless connection.addresses

  (
    (open? && @origin == connection.origin) ||
    !(@io.addresses & (connection.addresses || [])).empty?
  ) && @options.connection_options_match?(connection.options)
end

#on_connect_error(e) ⇒ void

This method returns an undefined value.

Parameters:

  • error (Exception)


504
505
506
507
508
509
510
# File 'lib/httpx/connection.rb', line 504

def on_connect_error(e)
  # connect errors, exit gracefully
  error = ConnectionError.new(e.message)
  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.

Parameters:



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
# File 'lib/httpx/connection.rb', line 522

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

    attempt_timeout = connect_attempt_time_left if connecting?

    current_timeout = @timeout
    current_timeout ||= @options.timeout.operation_timeout unless @state == :closed

    if current_timeout
      # if @timeout isn't set, it's not a completion-based timeout, i.e.
      # operation timeout; in such a case, we have to reset it once it piggybacks.
      @reset_timeout_on_call ||= @timeout.nil?

      @timeout = current_timeout - error.timeout

      if @timeout.positive?
        # if this was a connect timeout error and there are more addresses to try.
        connect_next(error) if attempt_timeout && !attempt_timeout.positive?
        return
      end

      @timeout = nil
      @reset_timeout_on_call = false
    elsif attempt_timeout
      # when request timeouts are set instead.
      connect_next(error) unless attempt_timeout.positive?
      return
    else
      # the select interval came from another selectable, as this one has no timeout set.
      return
    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.

Parameters:

  • error (SocketError, IOError, TLSError)


512
513
514
515
516
517
518
519
520
# File 'lib/httpx/connection.rb', line 512

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

Returns:

  • (Boolean)


459
460
461
# File 'lib/httpx/connection.rb', line 459

def open?
  @state == :open || @state == :inactive
end

#peer ⇒ URI::Generic

Returns:

  • (URI::Generic)


110
111
112
# File 'lib/httpx/connection.rb', line 110

def peer
  @origin
end

#pending_count ⇒ Integer

returns the number of pending requests both in the connection as well as parser pending queues

Returns:

  • (Integer)


199
200
201
# File 'lib/httpx/connection.rb', line 199

def pending_count
  @pending.size
end

#purge_pending {|request| ... } ⇒ void

This method returns an undefined value.

Yields:

Yield Parameters:

Yield Returns:

  • (void)


203
204
205
206
207
# File 'lib/httpx/connection.rb', line 203

def purge_pending(&block)
  pending = @pending.dup
  @pending.clear
  pending.each(&block)
end

#reset ⇒ void

This method returns an undefined value.



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# File 'lib/httpx/connection.rb', line 371

def reset
  return if @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?

  reset_ping_timer

  parser = @parser

  if parser && parser.respond_to?(:max_concurrent_requests)
    # @type var parser: HTTP1

    # 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.

Parameters:



395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/httpx/connection.rb', line 395

def send(request)
  return @coalesced_connection.send(request) if @coalesced_connection

  request.connection = self

  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
    set_connection_timeouts(request) if connecting?

    @pending << request
  end
end

#terminate ⇒ void

This method returns an undefined value.



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/httpx/connection.rb', line 328

def terminate
  case @state
  when :idle
    purge_after_closed

    # @fiber-switch-guard
    if @io.can_disconnect? && @pending.empty?
      @state = :closed
      disconnect
      return
    end
  when :closed
    @connected_at = nil
  end

  close
end

#timeout ⇒ interval?

Returns:

  • (interval, nil)


422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/httpx/connection.rb', line 422

def timeout
  return if @state == :closed || @state == :inactive

  timeout = @timeout || @options.timeout.operation_timeout

  return timeout unless connecting? && (attempt_timeout = connect_attempt_time_left)

  # the attempt may already be overdue
  attempt_timeout = 0 unless attempt_timeout.positive?

  timeout && timeout < attempt_timeout ? timeout : attempt_timeout
end

#to_io ⇒ IO

Returns:

  • (IO)


247
248
249
# File 'lib/httpx/connection.rb', line 247

def to_io
  @io.to_io
end

#used? ⇒ Boolean

Returns:

  • (Boolean)


448
449
450
# File 'lib/httpx/connection.rb', line 448

def used?
  @connected_at
end