lib/skylight/util/http.rb in skylight-0.3.10 vs lib/skylight/util/http.rb in skylight-0.3.11

- old
+ new

@@ -20,10 +20,13 @@ include Logging attr_accessor :authentication, :config attr_reader :host, :port + class StartError < StandardError; end + class ReadResponseError < StandardError; end + def initialize(config, service = :report) @config = config @ssl = config["#{service}.ssl"] @host = config["#{service}.host"] @port = config["#{service}.port"] @@ -81,10 +84,29 @@ end type.new(endpoint, headers) end + def start(http) + begin + client = http.start + rescue => e + # TODO: Retry here + raise StartError, e.inspect + end + + yield client + 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 @@ -102,18 +124,19 @@ http.use_ssl = true http.ca_file = DEFAULT_CA_FILE unless HTTP.ca_cert_file? http.verify_mode = OpenSSL::SSL::VERIFY_PEER end - http.start do |client| + start(http) do |client| res = client.request(req) + code, body = read_code_and_body(res) - unless res.code =~ /2\d\d/ - debug "server responded with #{res.code}" - t { fmt "body=%s", res.body } + unless code =~ /2\d\d/ + debug "server responded with #{code}" + t { fmt "body=%s", body } end - Response.new(res.code.to_i, res, res.body) + Response.new(code.to_i, 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)