Class: HTTP2::Stream

Inherits:
Object
  • Object
show all
Includes:
Emitter, Error, FlowBuffer
Defined in:
lib/http/2/stream.rb,
sig/stream.rbs

Overview

A single HTTP 2.0 connection can multiplex multiple streams in parallel: multiple requests and responses can be in flight simultaneously and stream data can be interleaved and prioritized.

This class encapsulates all of the state, transition, flow-control, and error management as defined by the HTTP 2.0 specification. All you have to do is subscribe to appropriate events (marked with ":" prefix in diagram below) and provide your application logic to handle request and response processing.

                    +--------+
               PP   |        |   PP
           ,--------|  idle  |--------.
          /         |        |         \
         v          +--------+          v
  +----------+          |           +----------+
  |          |          | H         |          |
,---|:reserved |          |           |:reserved |---.
|   | (local)  |          v           | (remote) |   |
|   +----------+      +--------+      +----------+   |
|      | :active      |        |      :active |      |
|      |      ,-------|:active |-------.      |      |
|      | H   /   ES   |        |   ES   \   H |      |
|      v    v         +--------+         v    v      |
|   +-----------+          |          +-----------+  |
|   |:half_close|          |          |:half_close|  |
|   |  (remote) |          |          |  (local)  |  |
|   +-----------+          |          +-----------+  |
|        |                 v                |        |
|        |    ES/R    +--------+    ES/R    |        |
|        `----------->|        |<-----------'        |
| R                   | :close |                   R |
`-------------------->|        |<--------------------'
                    +--------+

Constant Summary collapse

DEFAULT_WEIGHT =

Default stream priority (lower values are higher priority).

Returns:

  • (Integer)
16
STREAM_OPEN_STATES =

Returns:

  • (Array[Symbol])
%i[open half_closed_local half_closing closing].freeze

Constants included from FlowBuffer

FlowBuffer::MAX_WINDOW_SIZE

Instance Attribute Summary collapse

Attributes included from FlowBuffer

#send_buffer

Instance Method Summary collapse

Methods included from Emitter

#emit, #on, #once

Methods included from FlowBuffer

#buffered_amount, #flush

Instance Attribute Details

#closed ⇒ Symbol? (readonly)

Reason why connection was closed.

Returns:

  • (Symbol, nil)


66
67
68
# File 'lib/http/2/stream.rb', line 66

def closed
  @closed
end

#dependency ⇒ Integer (readonly)

Returns the value of attribute dependency.

Returns:

  • (Integer)


59
60
61
# File 'lib/http/2/stream.rb', line 59

def dependency
  @dependency
end

#id ⇒ Integer (readonly)

Stream ID (odd for client initiated streams, even otherwise).

Returns:

  • (Integer)


49
50
51
# File 'lib/http/2/stream.rb', line 49

def id
  @id
end

#local_window ⇒ Integer (readonly) Also known as: window

Size of current stream flow control window.

Returns:

  • (Integer)


62
63
64
# File 'lib/http/2/stream.rb', line 62

def local_window
  @local_window
end

#parent ⇒ Stream? (readonly)

Request parent stream of push stream.

Returns:



55
56
57
# File 'lib/http/2/stream.rb', line 55

def parent
  @parent
end

#remote_window ⇒ Integer (readonly)

Returns the value of attribute remote_window.

Returns:

  • (Integer)


59
60
61
# File 'lib/http/2/stream.rb', line 59

def remote_window
  @remote_window
end

#state ⇒ Symbol (readonly)

Stream state as defined by HTTP 2.0.

Returns:

  • (Symbol)


52
53
54
# File 'lib/http/2/stream.rb', line 52

def state
  @state
end

#weight ⇒ Integer (readonly)

Stream priority as set by initiator.

Returns:

  • (Integer)


58
59
60
# File 'lib/http/2/stream.rb', line 58

def weight
  @weight
end

Instance Method Details

#calculate_content_length(data_length) ⇒ void

This method returns an undefined value.

Parameters:

  • (Integer, nil)


190
191
192
193
194
195
196
197
# File 'lib/http/2/stream.rb', line 190

def calculate_content_length(data_length)
  return unless @_content_length && data_length

  @_content_length -= data_length
  return if @_content_length >= 0

  stream_error(:protocol_error, msg: "received more data than what was defined in content-length")
end

#cancel ⇒ void

This method returns an undefined value.

Sends a RST_STREAM indicating that the stream is no longer needed.



294
295
296
# File 'lib/http/2/stream.rb', line 294

def cancel
  send(type: :rst_stream, error: :cancel)
end

#chunk_data(payload, max_size) {|arg0| ... } ⇒ String

Chunk data into max_size, yield each chunk, then return final chunk

Parameters:

  • payload (String)
  • max_size (Integer)

Yields:

Yield Parameters:

  • arg0 (String)

Yield Returns:

  • (void)

Returns:

  • (String)


275
276
277
278
279
280
281
282
283
# File 'lib/http/2/stream.rb', line 275

def chunk_data(payload, max_size)
  total = payload.bytesize
  cursor = 0
  while (total - cursor) > max_size
    yield payload.byteslice(cursor, max_size)
    cursor += max_size
  end
  payload.byteslice(cursor, total - cursor)
end

#close(error) ⇒ void #close ⇒ void

Sends a RST_STREAM frame which closes current stream - this does not close the underlying connection.

Overloads:

  • #close(error) ⇒ void

    This method returns an undefined value.

    Parameters:

    • error (Symbol)
  • #close ⇒ void

    This method returns an undefined value.

Parameters:

  • error (:Symbol) (defaults to: :stream_closed) —

    optional reason why stream was closed



289
290
291
# File 'lib/http/2/stream.rb', line 289

def close(error = :stream_closed)
  send(type: :rst_stream, error: error)
end

#closed? ⇒ Boolean

Returns:

  • (Boolean)


108
109
110
# File 'lib/http/2/stream.rb', line 108

def closed?
  @state == :closed
end

#data(payload, end_stream: true) ⇒ void

This method returns an undefined value.

Sends DATA frame containing response payload.

Parameters:

  • payload (String)
  • end_stream (Boolean) (defaults to: true) —

    indicates last response DATA frame

  • end_stream: (Boolean) (defaults to: true)


257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/http/2/stream.rb', line 257

def data(payload, end_stream: true)
  # Split data according to each frame is smaller enough
  # TODO: consider padding?
  max_size = @connection.remote_settings[:settings_max_frame_size]

  if payload.bytesize > max_size
    payload = chunk_data(payload, max_size) do |chunk|
      send(type: :data, flags: 0, payload: chunk)
    end
  end

  flags = 0
  flags |= END_STREAM if end_stream
  send(type: :data, flags: flags, payload: payload)
end

#headers(headers, end_headers: true, end_stream: false) ⇒ void

This method returns an undefined value.

Sends a HEADERS frame containing HTTP response headers. All pseudo-header fields MUST appear in the header block before regular header fields.

Parameters:

  • headers (Array or Hash) —

    Array of key-value pairs or Hash

  • end_headers (Boolean) (defaults to: true) —

    indicates that no more headers will be sent

  • end_stream (Boolean) (defaults to: false) —

    indicates that no payload will be sent

  • end_headers: (Boolean) (defaults to: true)
  • end_stream: (Boolean) (defaults to: false)


229
230
231
232
233
234
# File 'lib/http/2/stream.rb', line 229

def headers(headers, end_headers: true, end_stream: false)
  flags = end_headers ? END_HEADERS : 0
  flags |= END_STREAM  if end_stream || @_method == "HEAD"

  send(type: :headers, flags: flags, payload: headers)
end

#promise(headers, end_headers: true) {|arg0| ... } ⇒ void

This method returns an undefined value.

Parameters:

  • headers (Enumerable[header_pair])
  • end_headers: (Boolean) (defaults to: true)

Yields:

Yield Parameters:

Yield Returns:

  • (void)

Raises:

  • (ArgumentError)


236
237
238
239
240
241
# File 'lib/http/2/stream.rb', line 236

def promise(headers, end_headers: true, &block)
  raise ArgumentError, "must provide callback" unless block

  flags = end_headers ? END_HEADERS : 0
  emit(:promise, self, headers, flags, &block)
end

#receive(frame) ⇒ void Also known as: <<

This method returns an undefined value.

Processes incoming HTTP 2.0 frames. The frames must be decoded upstream.

Parameters:

  • frame (Hash)


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
# File 'lib/http/2/stream.rb', line 115

def receive(frame)
  transition(frame, false)

  frame_type = frame[:type] #: Symbol
  case frame_type
  when :data
    # @type var frame: data_frame
    # 6.1. DATA
    # If a DATA frame is received whose stream is not in "open" or
    # "half closed (local)" state, the recipient MUST respond with a
    # stream error (Section 5.4.2) of type STREAM_CLOSED.
    stream_error(:stream_closed) unless STREAM_OPEN_STATES.include?(@state) ||
                                        (@state == :closed && @closed == :local_rst)
    @received_data = true
    calculate_content_length(frame[:length])
    update_local_window(frame)
    # Emit DATA frame
    emit(:data, frame[:payload]) unless frame[:ignore]
    calculate_window_update(@local_window_max_size)
  when :headers
    # @type var frame: headers_frame
    stream_error(:stream_closed) if (@state == :closed && @closed != :local_rst) ||
                                    @state == :remote_closed
    @_method ||= frame[:method]
    @_status_code ||= frame[:status]
    @_content_length ||= frame[:content_length]
    @_trailers ||= frame[:trailer]
    if @_waiting_on_trailers ||
       (@received_data &&
           (!@_status_code || @_status_code >= 200))

      # An endpoint that receives a HEADERS frame without the END_STREAM flag set after receiving a final
      # (non-informational) status code MUST treat the corresponding request or response as malformed.
      verify_trailers(frame)
    end
    emit(:headers, frame[:payload]) unless frame[:ignore]
    @_waiting_on_trailers = !@_trailers.nil?
  when :push_promise
    emit(:promise_headers, frame[:payload]) unless frame[:ignore]
  when :continuation
    stream_error(:stream_closed) if (@state == :closed && @closed != :local_rst) || @state == :remote_closed
    stream_error(:protocol_error) if @received_data
  when :priority
    # @type var frame: priority_frame
    process_priority(frame)
  when :window_update
    # @type var frame: window_update_frame
    process_window_update(frame: frame)
  when :altsvc
    # @type var frame: origin_frame
    # 4.  The ALTSVC HTTP/2 Frame
    # An ALTSVC frame on a
    # stream other than stream 0 containing non-empty "Origin" information
    # is invalid and MUST be ignored.
    emit(frame_type, frame) if !frame[:origin] || frame[:origin].empty?
  end

  complete_transition(frame)
end

#refuse ⇒ void

This method returns an undefined value.

Sends a RST_STREAM indicating that the stream has been refused prior to performing any application processing.



300
301
302
# File 'lib/http/2/stream.rb', line 300

def refuse
  send(type: :rst_stream, error: :refused_stream)
end

#reprioritize(weight: 16, dependency: 0, exclusive: false) ⇒ void

This method returns an undefined value.

Sends a PRIORITY frame with new stream priority value (can only be performed by the client).

Parameters:

  • weight (Integer) (defaults to: 16) —

    new stream weight value

  • dependency (Integer) (defaults to: 0) —

    new stream dependency stream

  • weight: (Integer) (defaults to: 16)
  • dependency: (Integer) (defaults to: 0)
  • exclusive: (Boolean) (defaults to: false)


248
249
250
251
# File 'lib/http/2/stream.rb', line 248

def reprioritize(weight: 16, dependency: 0, exclusive: false)
  stream_error if @id.even?
  send(type: :priority, weight: weight, dependency: dependency, exclusive: exclusive)
end

#send(frame) ⇒ void

This method returns an undefined value.

Processes outgoing HTTP 2.0 frames. Data frames may be automatically split and buffered based on maximum frame size and current stream flow control window size.

Parameters:

  • frame (Hash)


204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/http/2/stream.rb', line 204

def send(frame)
  case frame[:type]
  when :data
    # @type var frame: data_frame
    # stream state management is maintained in send_data
    return send_data(frame)
  when :window_update
    # @type var frame: window_update_frame
    @local_window += frame[:increment]
  when :priority
    # @type var frame: priority_frame
    process_priority(frame)
  end

  manage_state(frame) do
    emit(:frame, frame)
  end
end

#verify_trailers(frame) ⇒ void

This method returns an undefined value.

Parameters:

  • frame (headers_frame)


176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/http/2/stream.rb', line 176

def verify_trailers(frame)
  stream_error(:protocol_error, msg: "trailer headers frame must close the stream") unless end_stream?(frame)
  return unless @_trailers

  trailers = frame[:payload]
  return unless trailers.respond_to?(:each)

  trailers.each do |field, _| # rubocop:disable Style/HashEachMethods
    @_trailers.delete(field)
    break if @_trailers.empty?
  end
  stream_error(:protocol_error, msg: "didn't receive all expected trailer headers") unless @_trailers.empty?
end

#window_update(increment) ⇒ void

This method returns an undefined value.

Sends a WINDOW_UPDATE frame to the peer.

Parameters:

  • increment (Integer)


307
308
309
310
311
312
# File 'lib/http/2/stream.rb', line 307

def window_update(increment)
  # emit stream-level WINDOW_UPDATE unless stream is closed
  return if @state == :closed || @state == :remote_closed

  send(type: :window_update, increment: increment)
end