Class: HTTP2::Connection
- Inherits:
-
Object
- Object
- HTTP2::Connection
- Includes:
- BufferUtils, Emitter, Error, FlowBuffer
- Defined in:
- lib/http/2/connection.rb,
sig/connection.rbs
Overview
Connection encapsulates all of the connection, stream, flow-control, error management, and other processing logic required for a well-behaved HTTP 2.0 endpoint.
Note that this class should not be used directly. Instead, you want to use either Client or Server class to drive the HTTP 2.0 exchange.
Constant Summary
Constants included from FlowBuffer
Instance Attribute Summary collapse
-
#active_stream_count ⇒ Integer
Number of active streams between client and server (reserved streams are not counted towards the stream limit).
-
#local_settings ⇒ Settings
readonly
Current settings value for local and peer.
-
#local_window ⇒ Integer
(also: #window)
readonly
Size of current connection flow control window (by default, set to infinity, but is automatically updated on receipt of peer settings).
-
#pending_settings ⇒ settings_ary
readonly
Pending settings value Sent but not ack'ed settings.
-
#remote_settings ⇒ Settings
readonly
Returns the value of attribute remote_settings.
-
#remote_window ⇒ Integer
readonly
Returns the value of attribute remote_window.
-
#state ⇒ Symbol
readonly
Connection state (:waiting_magic, :waiting_connection_preface, :connected, :closing, :closed).
Attributes included from FlowBuffer
Instance Method Summary collapse
- #close! ⇒ void
-
#closed? ⇒ Boolean
No new streams may be opened (a GOAWAY was sent or received).
-
#closing? ⇒ Boolean
Graceful GOAWAY received: tracked streams may still complete, but no new ones can be opened.
-
#goaway(error = :no_error, payload = nil) ⇒ void
Sends a GOAWAY frame indicating that the peer should stop creating new streams for current connection.
-
#initialize(settings = {}) ⇒ Connection
constructor
Initializes new connection object.
-
#new_stream(**args) ⇒ Stream
Allocates new stream for current connection.
-
#ping(payload, &blk) { ... } ⇒ Object
Sends PING frame to the peer.
-
#receive(data) ⇒ void
(also: #<<)
Decodes incoming bytes into HTTP 2.0 frames and routes them to appropriate receivers: connection frames are handled directly, and stream frames are passed to appropriate stream objects.
-
#settings(payload) ⇒ void
Sends a connection SETTINGS frame to the peer.
-
#window_update(increment) ⇒ void
Sends a WINDOW_UPDATE frame to the peer.
Methods included from BufferUtils
#append_str, #read_str, #read_uint32, #shift_byte
Methods included from Emitter
Methods included from FlowBuffer
Constructor Details
#initialize(settings = {}) ⇒ Connection
Initializes new connection object.
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/http/2/connection.rb', line 59 def initialize(settings = {}) @local_settings = Settings.new(**settings) @remote_settings = Settings.new(settings_max_concurrent_streams: Framer::MAX_STREAM_ID) @compressor = Header::Compressor.new(@local_settings) @decompressor = Header::Decompressor.new(@local_settings) @active_stream_count = @promised_stream_count = @last_promised_stream_id = @last_stream_id = 0 @streams = {} @streams_recently_closed = {} @oldest_stream_recently_closed = nil @pending_settings = [] @framer = Framer.new(@local_settings.settings_max_frame_size) @local_window = @local_window_limit = @local_settings.settings_initial_window_size @remote_window = @remote_window_limit = @remote_settings.settings_initial_window_size @recv_buffer = "".b @continuation = [] @continuation_size = 0 @error = nil @h2c_upgrade = nil @closed_since = nil @received_frame = false # from mixins @listeners = Hash.new { |hash, key| hash[key] = [] } @send_buffer = FrameBuffer.new end |
Instance Attribute Details
#active_stream_count ⇒ Integer
Number of active streams between client and server (reserved streams are not counted towards the stream limit).
56 57 58 |
# File 'lib/http/2/connection.rb', line 56 def active_stream_count @active_stream_count end |
#local_settings ⇒ Settings (readonly)
Current settings value for local and peer
48 49 50 |
# File 'lib/http/2/connection.rb', line 48 def local_settings @local_settings end |
#local_window ⇒ Integer (readonly) Also known as: window
Size of current connection flow control window (by default, set to infinity, but is automatically updated on receipt of peer settings).
43 44 45 |
# File 'lib/http/2/connection.rb', line 43 def local_window @local_window end |
#pending_settings ⇒ settings_ary (readonly)
Pending settings value Sent but not ack'ed settings
52 53 54 |
# File 'lib/http/2/connection.rb', line 52 def pending_settings @pending_settings end |
#remote_settings ⇒ Settings (readonly)
Returns the value of attribute remote_settings.
44 45 46 |
# File 'lib/http/2/connection.rb', line 44 def remote_settings @remote_settings end |
#remote_window ⇒ Integer (readonly)
Returns the value of attribute remote_window.
44 45 46 |
# File 'lib/http/2/connection.rb', line 44 def remote_window @remote_window end |
#state ⇒ Symbol (readonly)
Connection state (:waiting_magic, :waiting_connection_preface, :connected, :closing, :closed).
39 40 41 |
# File 'lib/http/2/connection.rb', line 39 def state @state end |
Instance Method Details
#close! ⇒ void
This method returns an undefined value.
857 858 859 860 |
# File 'lib/http/2/connection.rb', line 857 def close! @state = :closed @closed_since = Process.clock_gettime(Process::CLOCK_MONOTONIC) end |
#closed? ⇒ Boolean
No new streams may be opened (a GOAWAY was sent or received).
95 96 97 |
# File 'lib/http/2/connection.rb', line 95 def closed? @state == :closed || @state == :closing end |
#closing? ⇒ Boolean
Graceful GOAWAY received: tracked streams may still complete, but no new ones can be opened.
101 102 103 |
# File 'lib/http/2/connection.rb', line 101 def closing? @state == :closing end |
#goaway(error = :no_error, payload = nil) ⇒ void
This method returns an undefined value.
Sends a GOAWAY frame indicating that the peer should stop creating new streams for current connection.
Endpoints MAY append opaque data to the payload of any GOAWAY frame. Additional debug data is intended for diagnostic purposes only and carries no semantic value. Debug data MUST NOT be persistently stored, since it could contain sensitive information.
146 147 148 149 150 |
# File 'lib/http/2/connection.rb', line 146 def goaway(error = :no_error, payload = nil) send(type: :goaway, stream: 0, last_stream: @last_stream_id, error: error, payload: payload) close! end |
#new_stream(**args) ⇒ Stream
Allocates new stream for current connection.
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
# File 'lib/http/2/connection.rb', line 110 def new_stream(**args) raise ConnectionClosed if closed? connection_error(:protocol_error, msg: "id is smaller than previous") if @stream_id < @last_stream_id stream = activate_stream( id: @stream_id, max_concurrent_streams: @remote_settings.settings_max_concurrent_streams, **args ) @last_stream_id = stream.id @stream_id += 2 stream end |
#ping(arg0) ⇒ void #ping(arg0) ⇒ void
Sends PING frame to the peer.
131 132 133 134 |
# File 'lib/http/2/connection.rb', line 131 def ping(payload, &blk) send(type: :ping, stream: 0, payload: payload) once(:ack, &blk) if blk end |
#receive(data) ⇒ void Also known as: <<
This method returns an undefined value.
Decodes incoming bytes into HTTP 2.0 frames and routes them to appropriate receivers: connection frames are handled directly, and stream frames are passed to appropriate stream objects.
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 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 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 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 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 |
# File 'lib/http/2/connection.rb', line 175 def receive(data) append_str(@recv_buffer, data) # Upon establishment of a TCP connection and determination that # HTTP/2.0 will be used by both peers, each endpoint MUST send a # connection header as a final confirmation and to establish the # initial settings for the HTTP/2.0 connection. # # Client connection header is 24 byte connection header followed by # SETTINGS frame. Server connection header is SETTINGS frame only. if @state == :waiting_magic if @recv_buffer.size < 24 raise HandshakeError unless CONNECTION_PREFACE_MAGIC.start_with? @recv_buffer return # maybe next time elsif read_str(@recv_buffer, 24) == CONNECTION_PREFACE_MAGIC # MAGIC is OK. Send our settings @state = :waiting_connection_preface payload = @local_settings.connection_settings.reject { |k, v| v == SPEC_DEFAULT_CONNECTION_SETTINGS[k] } settings(payload) else raise HandshakeError end end while (frame = @framer.parse(@recv_buffer)) stream_id = frame[:stream] #: Integer frame_type = frame[:type] #: Symbol? if is_a?(Client) && !@received_frame connection_error(:protocol_error, msg: "didn't receive settings") if frame_type != :settings @received_frame = true end # Implementations MUST discard frames # that have unknown or unsupported types. if frame_type.nil? # However, extension frames that appear in # the middle of a header block (Section 4.3) are not permitted; these # MUST be treated as a connection error (Section 5.4.1) of type # PROTOCOL_ERROR. connection_error(:protocol_error) unless @continuation.empty? next end emit(:frame_received, frame) # Header blocks MUST be transmitted as a contiguous sequence of frames # with no interleaved frames of any other type, or from any other stream. unless @continuation.empty? # @type var frame: continuation_frame connection_error unless frame_type == :continuation && stream_id == @continuation.first[:stream] @continuation << frame @continuation_size += frame[:payload].bytesize unless frame[:flags].anybits?(END_HEADERS) # prevent HTTP/2 CONTINUATION FLOOD # same heuristic as the one from HAProxy: https://www.haproxy.com/blog/haproxy-is-resilient-to-the-http-2-continuation-flood # different mitigation (connection closed, instead of 400 response) unless @continuation_size < @local_settings.settings_max_frame_size connection_error(:protocol_error, msg: "too many continuations received") end next end payload = @continuation.map { |f| f[:payload] }.join frame = @continuation.shift frame_type = frame[:type] @continuation.clear @continuation_size = 0 frame.delete(:length) frame[:payload] = payload frame[:flags] |= END_HEADERS end # SETTINGS frames always apply to a connection, never a single stream. # The stream identifier for a settings frame MUST be zero. If an # endpoint receives a SETTINGS frame whose stream identifier field is # anything other than 0x0, the endpoint MUST respond with a connection # error (Section 5.4.1) of type PROTOCOL_ERROR. if connection_frame?(frame) # @type var frame: connection_frame connection_error(:protocol_error) unless stream_id.zero? connection_management(frame) else case frame_type when :headers # @type var frame: headers_frame # When server receives even-numbered stream identifier, # the endpoint MUST respond with a connection error of type PROTOCOL_ERROR. connection_error if stream_id.even? && is_a?(Server) # The last frame in a sequence of HEADERS/CONTINUATION # frames MUST have the END_HEADERS flag set. unless frame[:flags].anybits?(END_HEADERS) @continuation << frame next end # After sending a GOAWAY frame, the sender can discard frames # for new streams. However, any frames that alter connection # state cannot be completely ignored. For instance, HEADERS, # PUSH_PROMISE and CONTINUATION frames MUST be minimally # processed to ensure a consistent compression state decode_headers(frame) # After a GOAWAY, HEADERS may only complete a tracked stream at # or below the highest id seen (Section 6.8); anything else is # discarded - decoded above, so the compression state is intact. # Skip only this frame: later ones may serve completing streams. next if closed? && (stream_id > @last_stream_id || !@streams.key?(stream_id)) unless (stream = @streams[stream_id]) verify_pseudo_headers(frame) verify_stream_order(stream_id) # TODO: remove EMPTY_HASH after dropping support for ruby < 3.4 (recent rubies can # receive nil as kwarg splat) priority = EMPTY_HASH if frame[:flags].anybits?(PRIORITY) connection_error(:protocol_error, msg: "stream can't depend on itself") if stream_id == frame[:dependency] priority = frame.slice(:weight, :dependency, :exclusive) end stream = activate_stream(id: stream_id, **priority) end # streams are only emitted in a non-idle state. emit(:stream, stream) stream << frame when :push_promise # @type var frame: push_promise_frame # The last frame in a sequence of PUSH_PROMISE/CONTINUATION # frames MUST have the END_HEADERS flag set unless frame[:flags].anybits?(END_HEADERS) @continuation << frame return end decode_headers(frame) next if closed? # PUSH_PROMISE frames MUST be associated with an existing, peer- # initiated stream... A receiver MUST treat the receipt of a # PUSH_PROMISE on a stream that is neither "open" nor # "half-closed (local)" as a connection error (Section 5.4.1) of # type PROTOCOL_ERROR. Similarly, a receiver MUST treat the # receipt of a PUSH_PROMISE that promises an illegal stream # identifier (Section 5.1.1) (that is, an identifier for a stream # that is not currently in the "idle" state) as a connection error # (Section 5.4.1) of type PROTOCOL_ERROR, unless the receiver # recently sent a RST_STREAM frame to cancel the associated stream. parent = @streams[stream_id] pid = frame[:promise_stream] validate_push_promise(pid) # if PUSH parent is recently closed, RST_STREAM the push if @streams_recently_closed[stream_id] send(type: :rst_stream, stream: pid, error: :refused_stream) return end connection_error(msg: "missing parent ID") if parent.nil? unless STREAM_OPEN_STATES.include?(parent.state) # An endpoint might receive a PUSH_PROMISE frame after it sends # RST_STREAM. PUSH_PROMISE causes a stream to become "reserved". # The RST_STREAM does not cancel any promised stream. Therefore, if # promised streams are not desired, a RST_STREAM can be used to # close any of those streams. if parent.closed == :local_rst # We can either (a) 'resurrect' the parent, or (b) RST_STREAM # ... sticking with (b), might need to revisit later. send(type: :rst_stream, stream: pid, error: :refused_stream) else connection_error end end _verify_pseudo_headers(frame, REQUEST_MANDATORY_HEADERS) verify_stream_order(pid) if @promised_stream_count >= @local_settings.settings_max_concurrent_streams send(type: :rst_stream, stream: pid, error: :refused_stream) next end stream = activate_stream(id: pid, parent: parent) emit(:promise, stream) stream << frame else if (stream = @streams[stream_id]) stream << frame if frame_type == :data update_local_window(frame) calculate_window_update(@local_window_limit) end else case frame_type # Priority signaling is deprecated (RFC 9113 Section 5.3.2), but # a PRIORITY frame may still name a stream id not opened yet: # retain its priority without creating a stream until it opens. when :priority # After a GOAWAY, a PRIORITY for a stream already used and # closed must not resurrect it: reprioritizing a closed # parent is a no-op here, and a phantom stream would hold # the draining connection open. next if closed? && stream_id <= @last_stream_id connection_error(:protocol_error, msg: "stream can't depend on itself") if frame[:stream] == frame[:dependency] priority = frame.slice(:weight, :dependency, :exclusive) stream = activate_stream(id: stream_id, **priority) stream << frame # WINDOW_UPDATE can be sent by a peer that has sent a frame # bearing the END_STREAM flag. This means that a receiver could # receive a WINDOW_UPDATE frame on a "half-closed (remote)" or # "closed" stream. A receiver MUST NOT treat this as an error # (see Section 5.1). when :window_update unless @streams_recently_closed.key?(stream_id) connection_error(:protocol_error, msg: "sent window update on idle stream") end process_window_update(frame: frame, encode: true) # Endpoints MUST ignore # WINDOW_UPDATE or RST_STREAM frames received in this state (closed), though # endpoints MAY choose to treat frames that arrive a significant # time after sending END_STREAM as a connection error. when :rst_stream unless @streams_recently_closed.key?(stream_id) connection_error(:protocol_error, msg: "sent window update on idle stream") end else # An endpoint that receives an unexpected stream identifier # MUST respond with a connection error of type PROTOCOL_ERROR. connection_error(msg: "stream does not exist") end end end end end rescue StandardError => e raise if e.is_a?(Error::Error) connection_error(e: e) end |
#settings(payload) ⇒ void
This method returns an undefined value.
Sends a connection SETTINGS frame to the peer. The values are reflected when the corresponding ACK is received.
164 165 166 167 168 |
# File 'lib/http/2/connection.rb', line 164 def settings(payload) validate_settings(@local_role, payload) @pending_settings << payload send(type: :settings, stream: 0, payload: payload) end |
#window_update(increment) ⇒ void
This method returns an undefined value.
Sends a WINDOW_UPDATE frame to the peer.
155 156 157 158 |
# File 'lib/http/2/connection.rb', line 155 def window_update(increment) @local_window += increment send(type: :window_update, stream: 0, increment: increment) end |