Class: Hedra::HttpClient

Inherits:
Object
  • Object
show all
Defined in:
lib/hedra/http_client.rb

Constant Summary collapse

DEFAULT_USER_AGENT =
"Hedra/#{VERSION} Security Header Analyzer".freeze
MAX_RETRIES =
3
RETRY_DELAY =
1
MAX_REDIRECTS =
10

Instance Method Summary collapse

Constructor Details

#initialize(timeout: 10, proxy: nil, user_agent: nil, follow_redirects: true, verbose: false, max_retries: MAX_RETRIES) ⇒ HttpClient

rubocop:disable Metrics/ParameterLists



13
14
15
16
17
18
19
20
21
22
# File 'lib/hedra/http_client.rb', line 13

def initialize( # rubocop:disable Metrics/ParameterLists
  timeout: 10, proxy: nil, user_agent: nil, follow_redirects: true, verbose: false, max_retries: MAX_RETRIES
)
  @timeout = timeout
  @proxy = proxy
  @user_agent = user_agent || DEFAULT_USER_AGENT
  @follow_redirects = follow_redirects
  @verbose = verbose
  @max_retries = max_retries
end

Instance Method Details

#get(url, redirect_count: 0) ⇒ Object



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
56
57
# File 'lib/hedra/http_client.rb', line 24

def get(url, redirect_count: 0)
  retries = 0

  begin
    log "Fetching #{url}..."

    client = build_client
    response = client.get(url)

    if @follow_redirects && response.status.redirect?
      raise NetworkError, "Too many redirects (#{MAX_REDIRECTS})" if redirect_count >= MAX_REDIRECTS

      location = response.headers['Location']
      location = resolve_redirect_url(url, location)
      log "Following redirect to #{location}"
      return get(location, redirect_count: redirect_count + 1)
    end

    raise NetworkError, "HTTP #{response.status}: #{response.status.reason}" unless response.status.success?

    log "Success: #{response.status}"
    response
  rescue HTTP::Error, Errno::ECONNREFUSED, Errno::ETIMEDOUT, Errno::EHOSTUNREACH => e
    retries += 1
    if retries <= @max_retries && retryable_error?(e)
      delay = RETRY_DELAY * (2**(retries - 1))
      log "Retry #{retries}/#{@max_retries} after #{delay}s: #{e.message}"
      sleep delay
      retry
    end

    raise NetworkError, "Failed after #{@max_retries} retries: #{e.message}"
  end
end