Sha256: 06a5cbd755b7f2b10eb2ea9e61cac217a1575c3d901307905c4675fa0ac2db03

Contents?: true

Size: 1.45 KB

Versions: 10

Compression:

Stored size: 1.45 KB

Contents

# frozen_string_literal: true

module Spandx
  module Core
    class Http
      attr_reader :driver, :retries

      def initialize(driver: Http.default_driver, retries: 3)
        @driver = driver
        @retries = retries
        semaphore = Mutex.new
        @circuits = Hash.new do |hash, key|
          semaphore.synchronize do
            hash[key] = Circuit.new(key)
          end
        end
      end

      def get(uri, default: nil, escape: true)
        return default if Spandx.airgap?

        circuit = circuit_for(uri)
        return default if circuit.open?

        circuit.attempt do
          driver.with_retry(retries: retries) do |client|
            client.get(escape ? Addressable::URI.escape(uri) : uri)
          end
        end
      rescue *Net::Hippie::CONNECTION_ERRORS, URI::InvalidURIError
        default
      end

      def ok?(response)
        response.is_a?(Net::HTTPSuccess)
      end

      def self.default_driver
        @default_driver ||= Net::Hippie::Client.new(
          follow_redirects: 3,
          logger: Spandx.logger,
          open_timeout: 1,
          read_timeout: 5
        )
      end

      private

      def circuit_breaker_for(host, default)
        return default unless @circuits[host]

        @circuits[host] = false
        result = yield
        @circuits[host] = true
        result
      end

      def circuit_for(url)
        uri = URI.parse(url.to_s)
        @circuits[uri.host]
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
spandx-0.18.3 lib/spandx/core/http.rb
spandx-0.18.2 lib/spandx/core/http.rb
spandx-0.18.1 lib/spandx/core/http.rb
spandx-0.18.0 lib/spandx/core/http.rb
spandx-0.17.0 lib/spandx/core/http.rb
spandx-0.16.1 lib/spandx/core/http.rb
spandx-0.16.0 lib/spandx/core/http.rb
spandx-0.15.1 lib/spandx/core/http.rb
spandx-0.15.0 lib/spandx/core/http.rb
spandx-0.14.0 lib/spandx/core/http.rb