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
# 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
  )
  @response_reader = ResponseReader.new(@processor)
end

Instance Method Details

#closevoid

This method returns an undefined value.

Close all clients and release resources.



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

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



21
22
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
# File 'lib/patient_http/client.rb', line 21

def make_request(request, request_id)
  async_response = nil

  begin
    headers = request_headers(request, request_id)
    url = config.secret_manager.resolve_url(request.url, request.secret_params)
    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)
      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