class RainforestCli::HttpClient

Constants

API_URL
RETRY_INTERVAL

Public Class Methods

new(options) click to toggle source
# File lib/rainforest_cli/http_client.rb, line 12
def initialize(options)
  @token = options.fetch(:token)
end

Public Instance Methods

api_token_set?() click to toggle source
# File lib/rainforest_cli/http_client.rb, line 62
def api_token_set?
  !@token.nil?
end
delete(path, body = {}, options = {}) click to toggle source
# File lib/rainforest_cli/http_client.rb, line 16
def delete(path, body = {}, options = {})
  request(:delete, path, body, options)
end
get(path, body = {}, options = {}) click to toggle source
# File lib/rainforest_cli/http_client.rb, line 24
def get(path, body = {}, options = {})
  request(:get, path, body, options)
end
post(path, body = {}, options = {}) click to toggle source
# File lib/rainforest_cli/http_client.rb, line 20
def post(path, body = {}, options = {})
  request(:post, path, body, options)
end
request(method, path, body, options) click to toggle source
# File lib/rainforest_cli/http_client.rb, line 28
def request(method, path, body, options)
  url = File.join(API_URL, path)

  loop do
    begin
      response = Http::Exceptions.wrap_exception do
        HTTParty.send(method, url, { body: body, headers: headers, verify: false })
      end

      if response.code.between?(200, 299)
        return JSON.parse(response.body)
      elsif options[:retries_on_failures] && response.code >= 500
        delay = retry_delay
        logger.warn "HTTP request was unsuccessful. URL: #{url}. Status: #{response.code}"
        logger.warn "Retrying again in #{delay} seconds..."
        Kernel.sleep delay
      else
        logger.fatal "Non 200 code received for request to #{url}"
        logger.fatal "Server response: #{response.body}"
        exit 1
      end
    rescue Http::Exceptions::HttpException, Timeout::Error => e
      raise e unless options[:retries_on_failures]

      delay = retry_delay
      logger.warn 'Exception Encountered while trying to contact Rainforest API:'
      logger.warn "\t\t#{e.message}"
      logger.warn "Retrying again in #{delay} seconds..."

      Kernel.sleep delay
    end
  end
end

Private Instance Methods

headers() click to toggle source
# File lib/rainforest_cli/http_client.rb, line 72
def headers
  {
    'CLIENT_TOKEN' => @token,
    'User-Agent' => "Rainforest-cli-#{RainforestCli::VERSION}",
  }
end
logger() click to toggle source
# File lib/rainforest_cli/http_client.rb, line 84
def logger
  RainforestCli.logger
end
make_url(url) click to toggle source
# File lib/rainforest_cli/http_client.rb, line 68
def make_url(url)
  File.join(API_URL, url)
end
retry_delay() click to toggle source
# File lib/rainforest_cli/http_client.rb, line 79
def retry_delay
  # make retry delay random to desynchronize multiple threads
  RETRY_INTERVAL + rand(RETRY_INTERVAL)
end