Class: Excon::Connection
- Inherits:
-
Object
- Object
- Excon::Connection
- Defined in:
- lib/excon/connection.rb
Constant Summary collapse
- VALID_CONNECTION_KEYS =
[:body, :headers, :host, :host_port, :path, :port, :query, :scheme, :user, :password, :instrumentor, :instrumentor_name, :ssl_ca_file, :ssl_verify_peer, :chunk_size, :nonblock, :retry_limit, :connect_timeout, :read_timeout, :write_timeout, :captures, :exception, :expects, :mock, :proxy, :method, :idempotent, :request_block, :response_block, :middlewares, :retries_remaining, :connection, :stack, :response, :pipeline]
Instance Attribute Summary collapse
-
#data ⇒ Object
readonly
Returns the value of attribute data.
Instance Method Summary collapse
-
#initialize(url, params = {}) ⇒ Connection
constructor
Initializes a new Connection instance @param [String] url The destination URL @param [Hash<Symbol, >] params One or more optional params @option params [String] :body Default text to be sent over a socket.
- #inspect ⇒ Object
- #params ⇒ Object
- #params=(new_params) ⇒ Object
- #proxy ⇒ Object
- #proxy=(new_proxy) ⇒ Object
-
#request(params, &block) ⇒ Object
Sends the supplied request to the destination host.
- #request_call(datum) ⇒ Object
-
#requests(pipeline_params) ⇒ Object
Sends the supplied requests to the destination host using pipelining.
- #reset ⇒ Object
- #response_call(datum) ⇒ Object
- #retry_limit ⇒ Object
- #retry_limit=(new_retry_limit) ⇒ Object
Constructor Details
#initialize(url, params = {}) ⇒ Connection
Initializes a new Connection instance
@param [String] url The destination URL
@param [Hash<Symbol, >] params One or more optional params
@option params [String] :body Default text to be sent over a socket. Only used if :body absent in Connection#request params
@option params [Hash<Symbol, String>] :headers The default headers to supply in a request. Only used if params[:headers] is not supplied to Connection#request
@option params [String] :host The destination host's reachable DNS name or IP, in the form of a String
@option params [String] :path Default path; appears after 'scheme://host:port/'. Only used if params[:path] is not supplied to Connection#request
@option params [Fixnum] :port The port on which to connect, to the destination host
@option params [Hash] :query Default query; appended to the 'scheme://host:port/path/' in the form of '?key=value'. Will only be used if params[:query] is not supplied to Connection#request
@option params [String] :scheme The protocol; 'https' causes OpenSSL to be used
@option params [String] :proxy Proxy server; e.g. 'http://myproxy.com:8888'
@option params [Fixnum] :retry_limit Set how many times we'll retry a failed request. (Default 4)
@option params [Class] :instrumentor Responds to #instrument as in ActiveSupport::Notifications
@option params [String] :instrumentor_name Name prefix for #instrument events. Defaults to 'excon'
49 50 51 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 |
# File 'lib/excon/connection.rb', line 49 def initialize(url, params = {}) assert_valid_keys_for_argument!(params, VALID_CONNECTION_KEYS) uri = URI.parse(url) @data = Excon.defaults.merge({ :host => uri.host, :path => uri.path, :port => uri.port.to_s, :query => uri.query, :scheme => uri.scheme, :user => (URI.decode(uri.user) if uri.user), :password => (URI.decode(uri.password) if uri.password), }).merge!(params) # merge does not deep-dup, so make sure headers is not the original @data[:headers] = @data[:headers].dup if @data[:scheme] == HTTPS && (ENV.has_key?('https_proxy') || ENV.has_key?('HTTPS_PROXY')) @data[:proxy] = setup_proxy(ENV['https_proxy'] || ENV['HTTPS_PROXY']) elsif (ENV.has_key?('http_proxy') || ENV.has_key?('HTTP_PROXY')) @data[:proxy] = setup_proxy(ENV['http_proxy'] || ENV['HTTP_PROXY']) elsif @data.has_key?(:proxy) @data[:proxy] = setup_proxy(@data[:proxy]) end if @data[:proxy] @data[:headers]['Proxy-Connection'] ||= 'Keep-Alive' # https credentials happen in handshake if @data[:scheme] == 'http' && (@data[:proxy][:user] || @data[:proxy][:password]) auth = ['' << @data[:proxy][:user].to_s << ':' << @data[:proxy][:password].to_s].pack('m').delete(Excon::CR_NL) @data[:headers]['Proxy-Authorization'] = 'Basic ' << auth end end if ENV.has_key?('EXCON_DEBUG') || ENV.has_key?('EXCON_STANDARD_INSTRUMENTOR') @data[:instrumentor] = Excon::StandardInstrumentor end # Use Basic Auth if url contains a login if uri.user || uri.password @data[:headers]['Authorization'] ||= 'Basic ' << ['' << uri.user.to_s << ':' << uri.password.to_s].pack('m').delete(Excon::CR_NL) end @socket_key = '' << @data[:host] << ':' << @data[:port] reset end |
Instance Attribute Details
#data ⇒ Object (readonly)
Returns the value of attribute data.
8 9 10 |
# File 'lib/excon/connection.rb', line 8 def data @data end |
Instance Method Details
#inspect ⇒ Object
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 |
# File 'lib/excon/connection.rb', line 293 def inspect vars = instance_variables.inject({}) do |accum, var| accum.merge!(var.to_sym => instance_variable_get(var)) end if vars[:'@data'][:headers].has_key?('Authorization') vars[:'@data'] = vars[:'@data'].dup vars[:'@data'][:headers] = vars[:'@data'][:headers].dup vars[:'@data'][:headers]['Authorization'] = REDACTED end inspection = '#<Excon::Connection:' inspection << (object_id << 1).to_s(16) vars.each do |key, value| inspection << ' ' << key.to_s << '=' << value.inspect end inspection << '>' inspection end |
#params ⇒ Object
10 11 12 13 |
# File 'lib/excon/connection.rb', line 10 def params $stderr.puts("Excon::Connection#params is deprecated use Excon::Connection#data instead (#{caller.first})") @data end |
#params=(new_params) ⇒ Object
14 15 16 17 |
# File 'lib/excon/connection.rb', line 14 def params=(new_params) $stderr.puts("Excon::Connection#params= is deprecated use Excon::Connection#data= instead (#{caller.first})") @data = new_params end |
#proxy ⇒ Object
19 20 21 22 |
# File 'lib/excon/connection.rb', line 19 def proxy $stderr.puts("Excon::Connection#proxy is deprecated use Excon::Connection#data[:proxy] instead (#{caller.first})") @data[:proxy] end |
#proxy=(new_proxy) ⇒ Object
23 24 25 26 |
# File 'lib/excon/connection.rb', line 23 def proxy=(new_proxy) $stderr.puts("Excon::Connection#proxy= is deprecated use Excon::Connection#data[:proxy]= instead (#{caller.first})") @data[:proxy] = new_proxy end |
#request(params, &block) ⇒ Object
Sends the supplied request to the destination host.
@yield [chunk] @see Response#self.parse
@param [Hash<Symbol, >] params One or more optional params, override defaults set in Connection.new
@option params [String] :body text to be sent over a socket
@option params [Hash<Symbol, String>] :headers The default headers to supply in a request
@option params [String] :host The destination host's reachable DNS name or IP, in the form of a String
@option params [String] :path appears after 'scheme://host:port/'
@option params [Fixnum] :port The port on which to connect, to the destination host
@option params [Hash] :query appended to the 'scheme://host:port/path/' in the form of '?key=value'
@option params [String] :scheme The protocol; 'https' causes OpenSSL to be used
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 |
# File 'lib/excon/connection.rb', line 208 def request(params, &block) # @data has defaults, merge in new params to override datum = @data.merge(params) assert_valid_keys_for_argument!(params, VALID_CONNECTION_KEYS) datum[:headers] = @data[:headers].merge(datum[:headers] || {}) datum[:headers]['Host'] ||= '' << datum[:host] << ':' << datum[:port] datum[:retries_remaining] ||= datum[:retry_limit] # if path is empty or doesn't start with '/', insert one unless datum[:path][0, 1] == '/' datum[:path].insert(0, '/') end if block_given? $stderr.puts("Excon requests with a block are deprecated, pass :response_block instead (#{caller.first})") datum[:response_block] = Proc.new end datum[:connection] = self datum[:stack] = datum[:middlewares].map do |middleware| lambda {|stack| middleware.new(stack)} end.reverse.inject(self) do |middlewares, middleware| middleware.call(middlewares) end datum = datum[:stack].request_call(datum) unless datum[:pipeline] datum = response(datum) if datum[:response][:headers]['Connection'] == 'close' reset end Excon::Response.new(datum[:response]) else datum end rescue => request_error reset if datum[:idempotent] && [Excon::Errors::Timeout, Excon::Errors::SocketError, Excon::Errors::HTTPStatusError].any? {|ex| request_error.kind_of? ex } && datum[:retries_remaining] > 1 datum[:retries_remaining] -= 1 request(datum, &block) else if datum.has_key?(:instrumentor) datum[:instrumentor].instrument("#{datum[:instrumentor_name]}.error", :error => request_error) end raise(request_error) end end |
#request_call(datum) ⇒ Object
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 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
# File 'lib/excon/connection.rb', line 94 def request_call(datum) begin if datum.has_key?(:response) # we already have data from a middleware, so bail return datum else socket.data = datum # start with "METHOD /path" request = datum[:method].to_s.upcase << ' ' if @data[:proxy] request << datum[:scheme] << '://' << @data[:host] << ':' << @data[:port].to_s end request << datum[:path] # add query to path, if there is one case datum[:query] when String request << '?' << datum[:query] when Hash request << '?' datum[:query].each do |key, values| if values.nil? request << key.to_s << '&' else [values].flatten.each do |value| request << key.to_s << '=' << CGI.escape(value.to_s) << '&' end end end request.chop! # remove trailing '&' end # finish first line with "HTTP/1.1\r\n" request << HTTP_1_1 if datum.has_key?(:request_block) datum[:headers]['Transfer-Encoding'] = 'chunked' elsif ! (datum[:method].to_s.casecmp('GET') == 0 && datum[:body].nil?) # The HTTP spec isn't clear on it, but specifically, GET requests don't usually send bodies; # if they don't, sending Content-Length:0 can cause issues. datum[:headers]['Content-Length'] = detect_content_length(datum[:body]) end # add headers to request datum[:headers].each do |key, values| [values].flatten.each do |value| request << key.to_s << ': ' << value.to_s << CR_NL end end # add additional "\r\n" to indicate end of headers request << CR_NL # write out the request, sans body socket.write(request) # write out the body if datum.has_key?(:request_block) while true chunk = datum[:request_block].call if FORCE_ENC chunk.force_encoding('BINARY') end if chunk.length > 0 socket.write(chunk.length.to_s(16) << CR_NL << chunk << CR_NL) else socket.write('0' << CR_NL << CR_NL) break end end elsif !datum[:body].nil? if datum[:body].is_a?(String) unless datum[:body].empty? socket.write(datum[:body]) end else if datum[:body].respond_to?(:binmode) datum[:body].binmode end if datum[:body].respond_to?(:pos=) datum[:body].pos = 0 end while chunk = datum[:body].read(datum[:chunk_size]) socket.write(chunk) end end end end rescue => error case error when Excon::Errors::StubNotFound, Excon::Errors::Timeout raise(error) else raise(Excon::Errors::SocketError.new(error)) end end datum end |
#requests(pipeline_params) ⇒ Object
Sends the supplied requests to the destination host using pipelining.
@pipeline_params [Array<Hash>] pipeline_params An array of one or more optional params, override defaults set in Connection.new, see #request for details
262 263 264 265 266 267 268 |
# File 'lib/excon/connection.rb', line 262 def requests(pipeline_params) pipeline_params.map do |params| request(params.merge!(:pipeline => true)) end.map do |datum| Excon::Response.new(response(datum)[:response]) end end |
#reset ⇒ Object
270 271 272 |
# File 'lib/excon/connection.rb', line 270 def reset (old_socket = sockets.delete(@socket_key)) && old_socket.close end |
#response_call(datum) ⇒ Object
194 195 196 |
# File 'lib/excon/connection.rb', line 194 def response_call(datum) datum end |
#retry_limit ⇒ Object
288 289 290 291 |
# File 'lib/excon/connection.rb', line 288 def retry_limit $stderr.puts("Excon::Connection#retry_limit is deprecated, pass :retry_limit to the initializer (#{caller.first})") @data[:retry_limit] ||= DEFAULT_RETRY_LIMIT end |
#retry_limit=(new_retry_limit) ⇒ Object
283 284 285 286 |
# File 'lib/excon/connection.rb', line 283 def retry_limit=(new_retry_limit) $stderr.puts("Excon::Connection#retry_limit= is deprecated, pass :retry_limit to the initializer (#{caller.first})") @data[:retry_limit] = new_retry_limit end |