Class: Verifalia::Rest::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/verifalia/rest/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(authenticator, user_agent, base_urls) ⇒ Client

Returns a new instance of Client.



44
45
46
47
48
49
50
# File 'lib/verifalia/rest/client.rb', line 44

def initialize(authenticator, user_agent, base_urls)
  @authenticator = authenticator
  @user_agent = user_agent
  @base_urls = base_urls.shuffle

  @current_base_url_idx = 0
end

Instance Attribute Details

#logger=(value) ⇒ Object (writeonly)

Optional debug logger



42
43
44
# File 'lib/verifalia/rest/client.rb', line 42

def logger=(value)
  @logger = value
end

Instance Method Details

#invoke(method, resource, options = nil) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/verifalia/rest/client.rb', line 52

def invoke(method, resource, options = nil)
  errors = []

  # Performs a maximum of as many attempts as the number of configured base API endpoints, keeping track
  # of the last used endpoint after each call, in order to try to distribute the load evenly across the
  # available endpoints.

  (0...@base_urls.length).each {
    base_url = @base_urls[@current_base_url_idx % @base_urls.length]
    @current_base_url_idx += 1

    # Build the final URL

    final_url = "#{base_url}/#{resource}"

    @logger&.info("Invoking #{method.upcase} #{final_url}")

    # Init the HTTP request

    connection = Faraday.new(
      headers: { 'User-Agent' => @user_agent }
    )

    request = connection.build_request(method)
    request.url(final_url)

    # Options

    unless options.nil?
      request.body = options[:body] unless options[:body].nil?
      request.headers = request.headers.merge(options[:headers]) unless options[:headers].nil?
    end

    # Authenticate the underlying client, if needed

    @authenticator.authenticate connection, request

    begin
      # Send the request to the Verifalia servers

      connection.builder.build_response(connection, request).on_complete do |response|
        if (500...599).include?(response.status)
          raise "Server error (HTTP status #{response.status}) while invoking #{final_url}"
        end

        return response
      end
    rescue => e
      @logger&.warn("Error while invoking #{method.upcase} #{final_url}. #{e.to_s}")
      errors.append(e)
    end
  }

  # Generate an error out of the potentially multiple invocation errors

  raise "All the base URIs are unreachable:\n#{errors.map { |error| error.to_s }.join("\n")}"
end