lib/skylight/util/http.rb in skylight-0.3.11 vs lib/skylight/util/http.rb in skylight-0.3.12
- old
+ new
@@ -17,25 +17,37 @@
GZIP = 'gzip'.freeze
DEFAULT_CA_FILE = File.expand_path('../../data/cacert.pem', __FILE__)
include Logging
- attr_accessor :authentication, :config
+ attr_accessor :authentication
attr_reader :host, :port
class StartError < StandardError; end
class ReadResponseError < StandardError; end
- def initialize(config, service = :report)
+ def initialize(config, service = :report, opts = {})
@config = config
@ssl = config["#{service}.ssl"]
@host = config["#{service}.host"]
@port = config["#{service}.port"]
+
@proxy_addr = config["#{service}.proxy_addr"]
@proxy_port = config["#{service}.proxy_port"]
@proxy_user = config["#{service}.proxy_user"]
@proxy_pass = config["#{service}.proxy_pass"]
+
+ @timeout = opts[:timeout] || 15
+
+ unless @proxy_addr
+ if http_proxy = ENV['HTTP_PROXY'] || ENV['http_proxy']
+ uri = URI.parse(http_proxy)
+ @proxy_addr, @proxy_port = uri.host, uri.port
+ @proxy_user, @proxy_pass = (uri.userinfo || '').split(/:/)
+ end
+ end
+
@deflate = config["#{service}.deflate"]
@authentication = config[:'authentication']
end
def self.detect_ca_cert_file!
@@ -84,29 +96,29 @@
end
type.new(endpoint, headers)
end
- def start(http)
+ def do_request(http, req)
begin
client = http.start
rescue => e
# TODO: Retry here
raise StartError, e.inspect
end
- yield client
+ begin
+ res = client.request(req)
+ rescue Net::ReadTimeout, Timeout::Error, EOFError => e
+ raise ReadResponseError, e.inspect
+ end
+
+ yield res
ensure
client.finish if client
end
- def read_code_and_body(res)
- code, body = res.code, res.body
- rescue Net::ReadTimeout, Timeout::Error, EOFError => e
- raise ReadResponseError, e.inspect
- end
-
def execute(req, body=nil)
t { fmt "executing HTTP request; host=%s; port=%s; path=%s, body=%s",
@host, @port, req.path, body && body.bytesize }
if body
@@ -114,29 +126,25 @@
req.body = body
end
http = Net::HTTP.new(@host, @port, @proxy_addr, @proxy_port, @proxy_user, @proxy_pass)
- # Default is 60, but we don't want to wait that long.
- # This path is also used on app boot and Heroku will timeout at 60
- http.read_timeout = 15
+ http.open_timeout = @timeout
+ http.read_timeout = @timeout
if @ssl
http.use_ssl = true
http.ca_file = DEFAULT_CA_FILE unless HTTP.ca_cert_file?
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
- start(http) do |client|
- res = client.request(req)
- code, body = read_code_and_body(res)
-
- unless code =~ /2\d\d/
- debug "server responded with #{code}"
- t { fmt "body=%s", body }
+ do_request(http, req) do |res|
+ unless res.code =~ /2\d\d/
+ debug "server responded with #{res.code}"
+ t { fmt "body=%s", res.body }
end
- Response.new(code.to_i, res, body)
+ Response.new(res.code.to_i, res, res.body)
end
rescue Exception => e
error "http %s %s failed; error=%s; msg=%s", req.method, req.path, e.class, e.message
t { e.backtrace.join("\n") }
ErrorResponse.new(req, e)