Class: Async::HTTP::Client

Inherits:
Object
  • Object
show all
Includes:
Verbs
Defined in:
lib/async/http/client.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(endpoint, protocol = nil, authority = nil, **options) ⇒ Client

Returns a new instance of Client.



30
31
32
33
34
35
36
37
# File 'lib/async/http/client.rb', line 30

def initialize(endpoint, protocol = nil, authority = nil, **options)
  @endpoint = endpoint
  
  @protocol = protocol || endpoint.protocol
  @authority = authority || endpoint.hostname
  
  @connections = connect(**options)
end

Instance Attribute Details

#authorityObject (readonly)

Returns the value of attribute authority.



41
42
43
# File 'lib/async/http/client.rb', line 41

def authority
  @authority
end

#endpointObject (readonly)

Returns the value of attribute endpoint.



39
40
41
# File 'lib/async/http/client.rb', line 39

def endpoint
  @endpoint
end

#protocolObject (readonly)

Returns the value of attribute protocol.



40
41
42
# File 'lib/async/http/client.rb', line 40

def protocol
  @protocol
end

Class Method Details

.open(*args, &block) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/async/http/client.rb', line 43

def self.open(*args, &block)
  client = self.new(*args)
  
  return client unless block_given?
  
  begin
    yield client
  ensure
    client.close
  end
end

Instance Method Details

#call(request) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/async/http/client.rb', line 61

def call(request)
  request.authority ||= @authority
  
  # As we cache connections, it's possible these connections go bad (e.g. closed by remote host). In this case, we need to try again. It's up to the caller to impose a timeout on this.
  while true
    connection = @connections.acquire
    
    if response = connection.call(request)
      # The connection won't be released until the body is completely read/released.
      Body::Streamable.wrap(response) do
        @connections.release(connection)
      end
      
      return response
    else
      # The connection failed for some reason, we close it.
      connection.close
    end
  end
end

#closeObject



55
56
57
# File 'lib/async/http/client.rb', line 55

def close
  @connections.close
end