module Johac::Connection

Provides {#connection}.

Uses the {github.com/lostisland/faraday faraday} lib to handle HTTP requests.

@see github.com/lostisland/faraday

Private Instance Methods

connection() click to toggle source
# File lib/johac/connection.rb, line 12
def connection
  @connection ||= Faraday.new(:url => uri) do |faraday|
    faraday.use :johac_connection_exceptions

    faraday.request :json
    faraday.request :johac_headers
    faraday.request :johac_auth, @config.auth_scheme, @config.access_key, @config.secret_key

    # Allow caller to tap into the request before it is sent
    if @config.request_tap
      faraday.request :request_tap, @config.request_tap
    end

    # Captures requests when client calls are made
    # within a capture block
    faraday.request :request_capture

    # Retry requests
    faraday.request :retry, {
      max: 2,
      interval: 0.5,
      backoff_factor: 3,
      interval_randomness: 0.5,

      # All connection errors + 429, 503, and 504
      exceptions: [
        Johac::Error::ConnectionError,
        Johac::Error::RetryableError
      ]
    }

    # apparently the response middleware acts like a stack, not a queue
    faraday.response :json

    # Raise connection errors as exceptions
    faraday.response :johac_raise_error

    faraday.adapter :johac_persistent do |http|
      # http param is an instance of Net::HTTP::Persistent
      #
      http.open_timeout = 2
      http.read_timeout = 60
      http.idle_timeout = 120

      # http.keep_alive
      # http.max_requests
      # http.socket_options
      http.debug_output = STDOUT if env == 'development'
    end
  end
end