Class: HTTPX::Request

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Callbacks, Loggable
Defined in:
lib/httpx/request.rb

Overview

Defines how an HTTP request is handled internally, both in terms of making attributes accessible, as well as maintaining the state machine which manages streaming the request onto the wire.

Direct Known Subclasses

Plugins::Proxy::HTTP::ConnectRequest

Defined Under Namespace

Classes: Body

Constant Summary collapse

ALLOWED_URI_SCHEMES =
%w[https http].freeze

Constants included from Loggable

Loggable::COLORS, Loggable::USE_DEBUG_LOG

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Callbacks

#callbacks_for?, #emit, #on, #once

Methods included from Loggable

#log, #log_exception, #log_redact, #log_redact_body, #log_redact_headers

Constructor Details

#initialize(verb, uri, options, params = EMPTY_HASH) ⇒ Request

initializes the instance with the given verb (an upppercase String, ex. ‘GEt’), an absolute or relative uri (either as String or URI::HTTP object), the request options (instance of HTTPX::Options) and an optional Hash of params.

Besides any of the options documented in HTTPX::Options (which would override or merge with what options sets), it accepts also the following:

:params

hash or array of key-values which will be encoded and set in the query string of request uris.

:body

to be encoded in the request body payload. can be a String, an IO object (i.e. a File), or an Enumerable.

:form

hash of array of key-values which will be form-urlencoded- or multipart-encoded in requests body payload.

:json

hash of array of key-values which will be JSON-encoded in requests body payload.

:xml

Nokogiri XML nodes which will be encoded in requests body payload.

:body, :form, :json and :xml are all mutually exclusive, i.e. only one of them gets picked up.



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/httpx/request.rb', line 72

def initialize(verb, uri, options, params = EMPTY_HASH)
  @verb    = verb.to_s.upcase
  @uri     = Utils.to_uri(uri)

  @headers = options.headers.dup
  merge_headers(params.delete(:headers)) if params.key?(:headers)

  @query_params = params.delete(:params) if params.key?(:params)

  @body = options.request_body_class.new(@headers, options, **params)

  @options = @body.options

  if @uri.relative? || @uri.host.nil?
    origin = @options.origin
    raise(Error, "invalid URI: #{@uri}") unless origin

    base_path = @options.base_path

    @uri = origin.merge("#{base_path}#{@uri}")
  end

  raise UnsupportedSchemeError, "#{@uri}: #{@uri.scheme}: unsupported URI scheme" unless ALLOWED_URI_SCHEMES.include?(@uri.scheme)

  @state = :idle
  @connection = @response = @drainer = @peer_address = @informational_status = nil
  @ping = false
  @persistent = @options.persistent
  @active_timeouts = []
end

Instance Attribute Details

#active_timeoutsObject (readonly)

Returns the value of attribute active_timeouts.



50
51
52
# File 'lib/httpx/request.rb', line 50

def active_timeouts
  @active_timeouts
end

#bodyObject (readonly)

an HTTPX::Request::Body object containing the request body payload (or nil, whenn there is none).



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

def body
  @body
end

#connection=(value) ⇒ Object (writeonly)

the connection the request is currently being sent to (none if before or after transaction)



46
47
48
# File 'lib/httpx/request.rb', line 46

def connection=(value)
  @connection = value
end

#drain_errorObject (readonly)

Exception raised during enumerable body writes.



40
41
42
# File 'lib/httpx/request.rb', line 40

def drain_error
  @drain_error
end

#headersObject (readonly)

an HTTPX::Headers object containing the request HTTP headers.



25
26
27
# File 'lib/httpx/request.rb', line 25

def headers
  @headers
end

#optionsObject (readonly)

an HTTPX::Options object containing request options.



34
35
36
# File 'lib/httpx/request.rb', line 34

def options
  @options
end

#peer_addressObject

The IP address from the peer server.



43
44
45
# File 'lib/httpx/request.rb', line 43

def peer_address
  @peer_address
end

#persistent=(value) ⇒ Object (writeonly)

Sets the attribute persistent

Parameters:

  • value

    the value to set the attribute persistent to.



48
49
50
# File 'lib/httpx/request.rb', line 48

def persistent=(value)
  @persistent = value
end

#responseObject

the corresponding HTTPX::Response object, when there is one.



37
38
39
# File 'lib/httpx/request.rb', line 37

def response
  @response
end

#stateObject (readonly)

a symbol describing which frame is currently being flushed.



31
32
33
# File 'lib/httpx/request.rb', line 31

def state
  @state
end

#uriObject (readonly)

the absolute URI object for this request.



22
23
24
# File 'lib/httpx/request.rb', line 22

def uri
  @uri
end

#verbObject (readonly)

the upcased string HTTP verb for this request.



19
20
21
# File 'lib/httpx/request.rb', line 19

def verb
  @verb
end

Instance Method Details

#authorityObject

returs the URI authority of the request.

session.build_request("GET", "https://google.com/query").authority #=> "google.com"
session.build_request("GET", "http://internal:3182/a").authority #=> "internal:3182"


219
220
221
# File 'lib/httpx/request.rb', line 219

def authority
  @uri.authority
end

#can_buffer?Boolean

Returns:

  • (Boolean)


161
162
163
# File 'lib/httpx/request.rb', line 161

def can_buffer?
  @state != :done
end

#complete!(response = @response) ⇒ Object



111
112
113
# File 'lib/httpx/request.rb', line 111

def complete!(response = @response)
  emit(:complete, response)
end

#drain_bodyObject

consumes and returns the next available chunk of request body that can be sent



249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/httpx/request.rb', line 249

def drain_body
  return nil if @body.nil?

  @drainer ||= @body.each
  chunk = @drainer.next.dup

  emit(:body_chunk, chunk)
  chunk
rescue StopIteration
  nil
rescue StandardError => e
  @drain_error = e
  nil
end

#expects?Boolean

whether the request supports the 100-continue handshake and already processed the 100 response.

Returns:

  • (Boolean)


314
315
316
# File 'lib/httpx/request.rb', line 314

def expects?
  @headers["expect"] == "100-continue" && @informational_status == 100 && !@response
end

#handle_error(error) ⇒ Object



327
328
329
330
331
332
333
334
335
# File 'lib/httpx/request.rb', line 327

def handle_error(error)
  if (connection = @connection)
    connection.on_error(error, self)
  else
    response = ErrorResponse.new(self, error)
    self.response = response
    emit(:response, response)
  end
end

#initialize_dup(orig) ⇒ Object

dupped initialization



104
105
106
107
108
109
# File 'lib/httpx/request.rb', line 104

def initialize_dup(orig)
  super
  @uri = orig.instance_variable_get(:@uri).dup
  @headers = orig.instance_variable_get(:@headers).dup
  @body = orig.instance_variable_get(:@body).dup
end

#inspectObject

:nocov:



265
266
267
268
269
270
271
# File 'lib/httpx/request.rb', line 265

def inspect
  "#<#{self.class}:#{object_id} " \
    "#{@verb} " \
    "#{uri} " \
    "@headers=#{@headers} " \
    "@body=#{@body}>"
end

#interestsObject

returns :r or :w, depending on whether the request is waiting for a response or flushing.



155
156
157
158
159
# File 'lib/httpx/request.rb', line 155

def interests
  return :r if @state == :done || @state == :expect

  :w
end

#merge_headers(h) ⇒ Object

merges h into the instance of HTTPX::Headers of the request.



166
167
168
169
170
171
# File 'lib/httpx/request.rb', line 166

def merge_headers(h)
  @headers = @headers.merge(h)
  return unless @headers.key?("range")

  @headers.delete("accept-encoding")
end

#originObject

returs the URI origin of the request.

session.build_request("GET", "https://google.com/query").authority #=> "https://google.com"
session.build_request("GET", "http://internal:3182/a").authority #=> "http://internal:3182"


227
228
229
# File 'lib/httpx/request.rb', line 227

def origin
  @uri.origin
end

#pathObject

returnns the URI path of the request uri.



207
208
209
210
211
212
213
# File 'lib/httpx/request.rb', line 207

def path
  path = uri.path.dup
  path =  +"" if path.nil?
  path << "/" if path.empty?
  path << "?#{query}" unless query.empty?
  path
end

#persistent?Boolean

Returns:

  • (Boolean)


140
141
142
# File 'lib/httpx/request.rb', line 140

def persistent?
  @persistent
end

#ping!Object

marks the request as having been buffered with a ping



121
122
123
# File 'lib/httpx/request.rb', line 121

def ping!
  @ping = true
end

#ping?Boolean

whether request has been buffered with a ping

Returns:

  • (Boolean)


116
117
118
# File 'lib/httpx/request.rb', line 116

def ping?
  @ping
end

#queryObject

returs the URI query string of the request (when available).

session.build_request("GET", "https://search.com").query #=> ""
session.build_request("GET", "https://search.com?q=a").query #=> "q=a"
session.build_request("GET", "https://search.com", params: { q: "a"}).query #=> "q=a"
session.build_request("GET", "https://search.com?q=a", params: { foo: "bar"}).query #=> "q=a&foo&bar"


237
238
239
240
241
242
243
244
245
246
# File 'lib/httpx/request.rb', line 237

def query
  return @query if defined?(@query)

  query = []
  if (q = @query_params) && !q.empty?
    query << Transcoder::Form.encode(q)
  end
  query << @uri.query if @uri.query
  @query = query.join("&")
end

#read_timeoutObject

the read timeout defined for this request.



126
127
128
# File 'lib/httpx/request.rb', line 126

def read_timeout
  @options.timeout[:read_timeout]
end

#request_timeoutObject

the request timeout defined for this request.



136
137
138
# File 'lib/httpx/request.rb', line 136

def request_timeout
  @options.timeout[:request_timeout]
end

#schemeObject

the URI scheme of the request uri.



174
175
176
# File 'lib/httpx/request.rb', line 174

def scheme
  @uri.scheme
end

#set_timeout_callback(event, &callback) ⇒ Object



318
319
320
321
322
323
324
325
# File 'lib/httpx/request.rb', line 318

def set_timeout_callback(event, &callback)
  clb = once(event, &callback)

  # reset timeout callbacks when requests get rerouted to a different connection
  once(:idle) do
    callbacks(event).delete(clb)
  end
end

#trailersObject

returns an instance of HTTPX::Headers containing the trailer headers



150
151
152
# File 'lib/httpx/request.rb', line 150

def trailers
  @trailers ||= @options.headers_class.new
end

#trailers?Boolean

if the request contains trailer headers

Returns:

  • (Boolean)


145
146
147
# File 'lib/httpx/request.rb', line 145

def trailers?
  defined?(@trailers)
end

#transition(nextstate) ⇒ Object

moves on to the nextstate of the request state machine (when all preconditions are met)



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/httpx/request.rb', line 275

def transition(nextstate)
  case nextstate
  when :idle
    @body.rewind
    @ping = false
    @response = @drainer = nil
    @active_timeouts.clear
  when :headers
    return unless @state == :idle

  when :body
    return unless @state == :headers ||
                  @state == :expect

    if @headers.key?("expect")
      if @informational_status && @informational_status == 100
        # check for 100 Continue response, and deallocate the var
        # if @informational_status == 100
        #   @response = nil
        # end
      else
        return if @state == :expect # do not re-set it

        nextstate = :expect
      end
    end
  when :trailers
    return unless @state == :body
  when :done
    return if @state == :expect

  end
  log(level: 3) { "#{@state}] -> #{nextstate}" }
  @state = nextstate
  emit(@state, self)
  nil
end

#write_timeoutObject

the write timeout defined for this request.



131
132
133
# File 'lib/httpx/request.rb', line 131

def write_timeout
  @options.timeout[:write_timeout]
end