Class: Grifter::HTTPService

Inherits:
Object show all
Includes:
JsonHelpers, Log
Defined in:
lib/grifter/http_service.rb

Constant Summary collapse

RequestLogSeperator =
'-'*40

Constants included from Log

Log::GrifterFormatter

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from JsonHelpers

#jsonify, #objectify

Methods included from Log

#add_logger, #level=, #log, #logger, #loggers

Constructor Details

#initialize(config) ⇒ HTTPService

Returns a new instance of HTTPService.



16
17
18
19
20
21
22
23
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
# File 'lib/grifter/http_service.rb', line 16

def initialize config

  @config = config
  @name = config[:name]
  @base_uri = config[:base_uri]
  @log_headers = config.fetch(:log_headers, true)
  @log_bodies = config.fetch(:log_bodies, true)

  logger.debug "Configuring service '#{@name}' with:\n\t#{@config.inspect}"

  #@conn = Net::HTTP.new(@config[:hostname], @config[:port])
  #@conn.use_ssl = @config[:ssl]
  @conn = Faraday.new @config[:faraday_url] do |conn_builder|
    #do our own logging
    #conn_builder.response logger: logger
    #conn_builder.adapter  Faraday.default_adapter  # make requests with Net::HTTP
    conn_builder.adapter  @config.fetch(:adapter, :typhoeus).intern
    conn_builder.ssl[:verify] = false if @config[:ignore_ssl_cert]

    #defaulting this to flat adapter avoids issues when duplicating parameters
    conn_builder.options[:params_encoder] = Faraday.const_get(@config.fetch(:params_encoder, 'FlatParamsEncoder'))

    #this nonsense dont work?!  https://github.com/lostisland/faraday_middleware/issues/76
    #conn_builder.use :instrumentation
  end

  @headers = {
    'accept' => 'application/json',
    'content-type' => 'application/json',
  }
  if @config[:default_headers]
    logger.debug "Default headers configured: " + @config[:default_headers].inspect
    @config[:default_headers].each_pair do |k, v|
      @headers[k.to_s] = v.to_s
    end
  end
  @default_timeout = @config.fetch(:timeout, 10)
  logger.info "Initialized grifter service '#{@name}'"
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



66
67
68
# File 'lib/grifter/http_service.rb', line 66

def config
  @config
end

#connObject (readonly)

Returns the value of attribute conn.



66
67
68
# File 'lib/grifter/http_service.rb', line 66

def conn
  @conn
end

#headersObject

allows for doing some fancy stuff in threading



67
68
69
# File 'lib/grifter/http_service.rb', line 67

def headers
  @headers
end

#httpObject (readonly)

allow stubbing http if we are testing



65
66
67
# File 'lib/grifter/http_service.rb', line 65

def http
  @http
end

#last_requestObject (readonly)

this is useful for testing apis, and other times you want to interrogate the http details of a response



71
72
73
# File 'lib/grifter/http_service.rb', line 71

def last_request
  @last_request
end

#last_responseObject (readonly)

this is useful for testing apis, and other times you want to interrogate the http details of a response



71
72
73
# File 'lib/grifter/http_service.rb', line 71

def last_response
  @last_response
end

#nameObject (readonly)

Returns the value of attribute name.



66
67
68
# File 'lib/grifter/http_service.rb', line 66

def name
  @name
end

Instance Method Details

#delete(path, options = {}) ⇒ Object



188
189
190
# File 'lib/grifter/http_service.rb', line 188

def delete path, options={}
  do_request :delete, path, nil, options
end

#do_request(method, path, obj = nil, options = {}) ⇒ Object

do_request performs the actual request, and does associated logging options can include:

  • :timeout, which specifies num secs the request should timeout in (this turns out to be kind of annoying to implement)

Raises:



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
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
# File 'lib/grifter/http_service.rb', line 79

def do_request method, path, obj=nil, options={}

  #grifter clients pass in path possibly including query params.
  #Faraday needs the query and path seperately.
  parsed = URI.parse make_path(path)
  #faraday needs the request params as a hash.
  #this turns out to be non-trivial
  query_hash = if parsed.query
                 cgi_hash = CGI.parse(parsed.query)
                 #make to account for one param having multiple values
                 cgi_hash.inject({}) { |h,(k,v)| h[k] = v[1] ? v : v.first; h }
               else
                 nil
               end

  req_headers = make_headers(options)

  body = if options[:form]
    URI.encode_www_form obj
  else
    jsonify(obj)
  end

  #log the request
  logger.debug [
    "Doing request: #{@name}: #{method.to_s.upcase} #{path}",
    @log_headers ? ["Request Headers:",
    req_headers.map{ |k, v| "#{k}: #{v.inspect}" }] : nil,
    @log_bodies ? ["Request Body:", body] : nil,
  ].flatten.compact.join("\n")

  #doing it this way avoids problem with OPTIONS method: https://github.com/lostisland/faraday/issues/305
  response = nil
  metrics_obj = { method: method, service: @name, path: path }
  ActiveSupport::Notifications.instrument('request.grifter', metrics_obj) do
    response = @conn.run_request(method, nil, nil, nil) do |req|
      req.path = parsed.path
      req.params = metrics_obj[:params] = query_hash if query_hash

      req.headers = req_headers
      req.body = body
      req.options[:timeout] = options.fetch(:timeout, @default_timeout)
    end
    metrics_obj[:response] = response
  end

  logger.info "Request status: (#{response.status}) #{@name}: #{method.to_s.upcase} #{path}"
  #@last_request = req
  @last_response = response

  response_obj = objectify response.body
  if response.headers['content-type'] =~ /json/
    logger.debug [
      "Response Details:",
      @log_headers ? ["Response Headers:",
                      response.headers.map { |k, v| "#{k}: #{v.inspect}" }] : nil,
      @log_bodies ? [ "Response Body:", jsonify(response_obj)] : nil,
      ''
    ].flatten.compact.join("\n")
  end

  raise RequestException.new(nil, response) unless response.status >= 200 and response.status < 300

  return response_obj
end

#get(path, options = {}) ⇒ Object



176
177
178
# File 'lib/grifter/http_service.rb', line 176

def get path, options={}
  do_request :get, path, nil, options
end

#head(path, options = {}) ⇒ Object



180
181
182
# File 'lib/grifter/http_service.rb', line 180

def head path, options={}
  do_request :head, path, nil, options
end

#in_parallel(&blk) ⇒ Object



145
146
147
148
# File 'lib/grifter/http_service.rb', line 145

def in_parallel &blk
  @conn.headers = @headers
  @conn.in_parallel &blk
end

#make_headers(options) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
# File 'lib/grifter/http_service.rb', line 160

def make_headers options
  headers = if options[:additional_headers]
    @headers.merge options[:additional_headers]
  elsif options[:headers]
    options[:headers]
  else
    @headers.clone
  end
  headers['content-type'] = 'application/x-www-form-urlencoded' if options[:form]
  headers
end

#make_path(path_suffix, base_uri = nil) ⇒ Object

add base uri to request



151
152
153
154
155
156
157
158
# File 'lib/grifter/http_service.rb', line 151

def make_path path_suffix, base_uri=nil
  base_uri_to_use = base_uri ? base_uri : @base_uri
  if base_uri_to_use
    base_uri_to_use + path_suffix
  else
    path_suffix
  end
end

#options(path, options = {}) ⇒ Object



184
185
186
# File 'lib/grifter/http_service.rb', line 184

def options path, options={}
  do_request :options, path, nil, options
end

#patch(path, obj, options = {}) ⇒ Object



200
201
202
# File 'lib/grifter/http_service.rb', line 200

def patch path, obj, options={}
  do_request :patch, path, obj, options
end

#post(path, obj, options = {}) ⇒ Object



192
193
194
# File 'lib/grifter/http_service.rb', line 192

def post path, obj, options={}
  do_request :post, path, obj, options
end

#post_form(path, params, options = {}) ⇒ Object



204
205
206
207
208
209
# File 'lib/grifter/http_service.rb', line 204

def post_form path, params, options={}
  do_request :post, path, params, options.merge(form: true)
  #request_obj = Net::HTTP::Post.new(*req_args(path, options))
  #request_obj.set_form_data params
  #do_request request_obj, options
end

#put(path, obj, options = {}) ⇒ Object



196
197
198
# File 'lib/grifter/http_service.rb', line 196

def put path, obj, options={}
  do_request :put, path, obj, options
end

#req_args(path, options) ⇒ Object



172
173
174
# File 'lib/grifter/http_service.rb', line 172

def req_args path, options
  [make_path(path, options[:base_uri]), make_headers(options)]
end

#stubs(&blk) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/grifter/http_service.rb', line 56

def stubs &blk
  stubs = Faraday::Adapter::Test::Stubs.new
  @conn = Faraday.new @config[:faraday_url] do |conn_builder|
    conn_builder.adapter :test, stubs
  end
  stubs
end