Class: PatientHttp::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/patient_http/client.rb

Instance Method Summary collapse

Constructor Details

#initialize(processor) ⇒ Client

Returns a new instance of Client.



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/patient_http/client.rb', line 5

def initialize(processor)
  @processor = processor
  @client_pool = ClientPool.new(
    max_size: config.connection_pool_size,
    connection_timeout: config.connection_timeout,
    proxy_url: config.proxy_url,
    retries: config.retries,
    protocol: config.protocol
  )
  @response_reader = ResponseReader.new(@processor)
  @request_preparer = RequestPreparer.new(config)
end

Instance Method Details

#closevoid

This method returns an undefined value.

Close all clients and release resources.



60
61
62
# File 'lib/patient_http/client.rb', line 60

def close
  @client_pool.close
end

#make_request(request, request_id) ⇒ Hash

Make an asynchronous HTTP request.

Parameters:

  • request (Request)

    the request to make

  • request_id (String)

    unique request identifier

Returns:

  • (Hash)

    the response data with keys for :status, :headers, and :body



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/patient_http/client.rb', line 23

def make_request(request, request_id)
  async_response = nil

  begin
    outgoing = @request_preparer.prepare(request, request_id)
    url = outgoing.url
    headers = outgoing.headers.to_h
    body = Protocol::HTTP::Body::Buffered.wrap([request.body.to_s]) if request.body
    timeout = request.timeout || config.request_timeout

    Async::Task.current.with_timeout(timeout) do
      async_response = @client_pool.request(request.http_method, url, headers, body)
      # Note: headers that appear multiple times (e.g. set-cookie) are
      # flattened to a single joined string value.
      headers_hash = async_response.headers.to_h.transform_values(&:to_s)
      body = @response_reader.read_body(async_response, headers_hash)

      {
        status: async_response.status,
        headers: headers_hash,
        body: body
      }
    end
  rescue => e
    # Close the response and evict the client for this host to ensure the
    # stale connection is not reused for subsequent requests.
    async_response&.close
    if connection_error?(e)
      @client_pool.evict(request.url)
    end
    raise
  end
end