Module: RestfulClient

Defined in:
lib/restful_client.rb

Defined Under Namespace

Classes: RestError

Constant Summary collapse

SERVER_SIDE_ERRORS_RANGE =
500
CLIENT_SIDE_ERRORS_RANGE =
400
@@configuration =
nil
@@logger =
nil
@@timeout_occured_count =
0

Class Method Summary collapse

Class Method Details

.callerr_config(caller) ⇒ Object



72
73
74
75
76
# File 'lib/restful_client.rb', line 72

def callerr_config(caller)
  caller_setup = configuration.data["#{caller}#{legacy_postfix}"]
  fail "Couldn't find ['#{caller}#{legacy_postfix}'] in the configuration YAML !!" unless caller_setup
  caller_setup
end

.configurationObject



28
29
30
# File 'lib/restful_client.rb', line 28

def configuration
  @@configuration
end

.configure {|configuration| ... } ⇒ Object

Yields:



21
22
23
24
25
26
# File 'lib/restful_client.rb', line 21

def self.configure
  @@configuration ||= RestfulClientConfiguration.new
  yield(configuration)
  @@configuration.run!
  @@logger = RestfulClientLogger.logger
end

.delete(caller, path, payload = {}, extra = {}, &on_error_block) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/restful_client.rb', line 57

def delete(caller, path, payload = {}, extra = {}, &on_error_block)
  url = RestfulClientUri.uri_join(callerr_config(caller)['url'], path)
  headers, payload_as_str = prepare_payload_with_headers(payload, extra.fetch('headers', {}))
  request_args = { headers: headers, method: 'DELETE', body: payload_as_str, timeout: timeout }
  request = Typhoeus::Request.new(url, request_args.merge(extra.fetch('args', {})))
  run_safe_request(caller, request, true, &on_error_block)
end

.fake(caller, path, _options = {}, &block) ⇒ Object



178
179
180
181
# File 'lib/restful_client.rb', line 178

def fake(caller, path, _options = {}, &block)
  url = RestfulClientUri.uri_join(callerr_config(caller)['url'], path)
  Typhoeus.stub(url, {}, &block)
end

.get(caller, path, params = {}, extra = {}, &on_error_block) ⇒ Object



40
41
42
43
44
45
46
47
# File 'lib/restful_client.rb', line 40

def get(caller, path, params = {}, extra = {}, &on_error_block)
  url = RestfulClientUri.uri_join(callerr_config(caller)['url'], path)
  headers = { 'Accept' => 'application/json' }
  headers.merge!(extra.fetch('headers', {}))
  request_args = { headers: headers, method: 'GET', timeout: timeout, params: params }.merge(extra.fetch('args', {}))
  request = Typhoeus::Request.new(url, request_args.merge(extra.fetch('args', {})))
  run_safe_request(caller, request, true, &on_error_block)
end

.legacy_postfixObject



195
196
197
# File 'lib/restful_client.rb', line 195

def legacy_postfix
  configuration.legacy_postfix
end

.loggerObject



32
33
34
# File 'lib/restful_client.rb', line 32

def logger
  @@logger
end

.post(caller, path, payload, extra = {}, &on_error_block) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/restful_client.rb', line 49

def post(caller, path, payload, extra = {}, &on_error_block)
  url = RestfulClientUri.uri_join(callerr_config(caller)['url'], path)
  headers, payload_as_str = prepare_payload_with_headers(payload, extra.fetch('headers', {}))
  request_args = { headers: headers, method: 'POST', body: payload_as_str, timeout: timeout }
  request = Typhoeus::Request.new(url, request_args.merge(extra.fetch('args', {})))
  run_safe_request(caller, request, false, &on_error_block)
end

.prepare_payload_with_headers(payload, custom_headers) ⇒ Object



164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/restful_client.rb', line 164

def prepare_payload_with_headers(payload, custom_headers)
  headers = {}
  if payload.is_a?(Hash) && payload.any?
    payload_as_str = payload.to_json(root: false)
    headers.merge!('Content-Type' => 'application/json')
  else
    payload_as_str = payload
  end

  headers.merge!(custom_headers)

  [headers, payload_as_str]
end

.prettify_logger(type, request, response) ⇒ Object



207
208
209
210
211
# File 'lib/restful_client.rb', line 207

def prettify_logger(type, request, response)
  return "#{type} with no request or response." unless request || response
  "#{type} #{response.code}/#{response.return_code} for: #{request.options.fetch(:method)}, "\
  "#{request.base_url}, Total time: #{response.total_time} seconds"
end

.put(caller, path, payload, extra = {}, &on_error_block) ⇒ Object



65
66
67
68
69
70
# File 'lib/restful_client.rb', line 65

def put(caller, path, payload, extra = {}, &on_error_block)
  url = RestfulClientUri.uri_join(callerr_config(caller)['url'], path)
  headers, payload_as_str = prepare_payload_with_headers(payload, extra.fetch('headers', {}))
  request = Typhoeus::Request.new(url, headers: headers, method: 'PUT', body: payload_as_str, timeout: timeout)
  run_safe_request(caller, request, false, &on_error_block)
end

.report_methodObject



203
204
205
# File 'lib/restful_client.rb', line 203

def report_method
  configuration.report_method
end

.retriesObject



199
200
201
# File 'lib/restful_client.rb', line 199

def retries
  configuration.retries
end

.run_request(request, method, retry_if_needed) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/restful_client.rb', line 102

def run_request(request, method, retry_if_needed)
  logger.debug { "#{__method__} :: Request :: #{request.inspect}" }
  request.options[:headers].merge!('X-Forwarded-For' => $client_ip) if $client_ip
  request.options[:headers].merge!('User-Agent' => user_agent)
  request.on_complete do |response|
    # 200, OK
    if response.success?
      logger.debug { "Success in #{method} :: Code: #{response.response_code}, #{response.body}" }
      return '' if response.body.empty? || response.body == ' '
      begin
        return JSON.parse(response.body)
      rescue => e
        logger.error { "Response from #{response.effective_url} is not a valid json  - [#{response.body}]" }
        raise e
      end
      # Timeout occured
    elsif response.timed_out?
      @@timeout_occured_count += 1
      skip_raise = (retry_if_needed && @@timeout_occured_count <= retries)

      error_type = 'TimeoutOccured'
      error_description = prettify_logger(error_type, request, response)
      logger.error { "Time out in #{method} for: #{error_description}" }

      exception = RuntimeError.new(error_description)
      exception.set_backtrace(caller)
      report_method.call('RestError', error_description, exception)

      fail RestError.new(response.return_code.to_sym) unless skip_raise
      # Could not get an http response, something's wrong.
    elsif response.code == 0

      error_type = :HttpError
      error_description = prettify_logger(error_type, request, response)
      logger.error { "HttpError Error #{response.code}/#{response.return_code} for: #{error_description}" }

      exception = RuntimeError.new(error_description)
      exception.set_backtrace(caller)
      report_method.call('RestError', error_description, exception)
      fail RestError.new(error_type)
      # Received a non-successful http response.
    elsif response.code >= SERVER_SIDE_ERRORS_RANGE

      error_type = :BadReturnCode
      error_description = prettify_logger(error_type, request, response)
      logger.error { "#{error_type} #{response.code}/#{response.return_code} for: #{error_description}" }

      exception = RuntimeError.new(error_description)
      exception.set_backtrace(caller)
      report_method.call('RestError', error_description, exception)

      fail RestError.new(error_type)
    elsif response.code.between?(CLIENT_SIDE_ERRORS_RANGE, (SERVER_SIDE_ERRORS_RANGE - 1))
      logger.error { "#{error_type} #{response.code}/#{response.return_code} for: #{error_description}" }
      return ''
    else
      fail RestError.new(:BadReturnCode)
    end
  end
  request.run
end

.run_safe_request(caller, request, retry_if_needed, &on_error_block) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/restful_client.rb', line 78

def run_safe_request(caller, request, retry_if_needed, &on_error_block)
  @@timeout_occured_count = 0
  if !use_jynx?
    response = run_request(request.dup, __method__, false)
  elsif ServiceJynx.alive?(caller)
    begin
      response = run_request(request.dup, __method__, retry_if_needed)
    end while response.is_a?(Typhoeus::Response)

    response
  else
    response = on_error_block.call("#{caller} set as down.") if on_error_block
  end
  response
rescue => e
  res = ServiceJynx.failure!(caller) if use_jynx?

  if res == :WENT_DOWN
    report_method.call('ServiceJynx', "Service #{caller} was taken down as a result of exception", e)
  end

  on_error_block.call("Exception in #{caller} execution - #{e.message}") if on_error_block
end

.srv_url(caller) ⇒ Object



36
37
38
# File 'lib/restful_client.rb', line 36

def srv_url(caller)
  callerr_config(caller)['url']
end

.timeoutObject



183
184
185
# File 'lib/restful_client.rb', line 183

def timeout
  configuration.timeout
end

.use_jynx?Boolean

Returns:

  • (Boolean)


191
192
193
# File 'lib/restful_client.rb', line 191

def use_jynx?
  configuration.use_jynx
end

.user_agentObject



187
188
189
# File 'lib/restful_client.rb', line 187

def user_agent
  configuration.user_agent
end