Files
swift-nio-http2/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift
T
Cory Benfield 3c90345c36 Pure-Swift HTTP/2 implementation (#40)
* Updated to use SwiftNIO 1.10+ to gain access to HTTPHeaders internals.

* Add pure-Swift HTTP/2 protocol implementation.

Motivation:

Currently we use nghttp2 for our basic protocol implementation. This is
plenty workable, but provides us a number of limitations. It adds
complexity to our build system, provides us with external dependencies we
have little control over, limits our users' ability to express low-level
protocol semantics if they so wish, causes us to heap-allocate like crazy over
the lifetime of a connection, and brings a world of pain around reentrancy.

This set of limitations has motivated a desire to move away from using
nghttp2. This is a part of that dream.

Modifications:

- Add pure Swift protocol implementations.
- Test them.

Results:

Another step towards protocol independence.

* Initial basic parser code.

* Adding unit tests.

* Add NIOHTTP2FlowControlHandler

Motivation:

One of the things that nghttp2 used to do for us was to handle buffering
DATA frames until flow control allowed them to go out. For users that
want that behaviour, we need to replace the nghttp2 code with a new
ChannelHandler that can do this work.

Modifications:

- Added NIOHTTP2FlowControlHandler.

Result:

Users will have the same feature set as they did with nghttp2.

* Generate Linux test information.

* Documentation comment.

* Updated new tests from master to use new payload types.

* Updated following review.

Notable changes:

- Implemented unit tests for the ALTSVC (0xa) and ORIGIN (0xc) frame types.
- Additional DATA frames are synthesized to wrap individual payload chunks as they arrive. If the payload of a DATA frame with 4MB data arrives in 4 separate 1MB chunks, the decoder will emit 4 DATA frames, with only the last containing the END_STREAM flag (if that was set on the incoming frame).
- HEADERS / PUSH_PROMISE frames and any following CONTINUATION frames are now handled properly: header fragments from all frames are gathered up into a single buffer. Once a frame with END_HEADERS is encountered, the resultant accumulated buffer is sent for decoding along with the flags and stream ID of the original HEADERS / PUSH_PROMISE frame.
- HPACK encoders/decoders now live in the frame encoder/decoder types, rather than being attached to a stream.

* Updated Linux tests.

* Headers placed in relevant files.

* Add pure-Swift HTTP/2 protocol implementation.

Motivation:

Currently we use nghttp2 for our basic protocol implementation. This is
plenty workable, but provides us a number of limitations. It adds
complexity to our build system, provides us with external dependencies we
have little control over, limits our users' ability to express low-level
protocol semantics if they so wish, causes us to heap-allocate like crazy over
the lifetime of a connection, and brings a world of pain around reentrancy.

This set of limitations has motivated a desire to move away from using
nghttp2. This is a part of that dream.

Modifications:

- Add pure Swift protocol implementations.
- Test them.

Results:

Another step towards protocol independence.

* Revamped frame decoder state machine and API. Now uses separate input and output methods to manage multiple frames in a single buffer.

* Updated Linux tests.

* Bumped swift-nio version to 1.12.0 and updated `HTTPHeaders` -> `HPACKHeaders` conversion initializer to directly copy the buffer and map the header name/value indices.

* Set up HTTP2Parser in handlerAdded if the channel had been previously activated. (#36)

By setting up the handler in the handlerAdded hook, HTTP2Parser supports
being added dynamically in a channelRead event, after the channel has sent
the channelActive event.

(cherry picked from commit 88bd6d369a)

* Minor tweaks to get the tests passing

* Initial integration here

* Minor clearing up of the handler

* Get the tests compiling

* Fix header issues.

We now pass the frame parser to the various setting operations to let it
update the state. We also fixed some issues with specific settings.

* Remove ngthttp2-based impl, clean up stream ID

* Tests with new HTTP2StreamID

* Simple test cleanup

* Get remaining non-core tests passing

* Allow GOAWAY even when fully quiesced

* We don't buffer outbound frames any more

* Emit StreamClosed events on GoAway frame

* Notify stream creation and closure

* This test started failing

* Goodbye, C code! 🎉

* Send PING ACK automatically

* Updated based on PR feedback.

* Correctly handle 1XX responses

* Add SETTINGS_MAX_FRAME_SIZE support to flow controller

* Correctly account for flow control

* Define ConcurrentStreamsHandler

* Prepare for signalling connection state changes

* Better state change message propagation

* Refactor to use result with effect everywhere

* Don't lose flow control info on stream error

* Add basic flow control management to stream multiplexer

* Better pipeline in sample server

* Clean up some reentrancy concerns

* Move to Swift 5 and NIO 2

* Move to new Swift 5 for CI

* Allow wider range of choices of years

* Catch up to NIO 2 again
2019-02-21 11:52:49 +00:00

184 lines
8.6 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIO
/// A channel handler that creates a child channel for each HTTP/2 stream.
///
/// In general in NIO applications it is helpful to consider each HTTP/2 stream as an
/// independent stream of HTTP/2 frames. This multiplexer achieves this by creating a
/// number of in-memory `HTTP2StreamChannel` objects, one for each stream. These operate
/// on `HTTP2Frame` objects as their base communication atom, as opposed to the regular
/// NIO `SelectableChannel` objects which use `ByteBuffer` and `IOData`.
public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboundHandler {
public typealias InboundIn = HTTP2Frame
public typealias InboundOut = HTTP2Frame
public typealias OutboundIn = HTTP2Frame
public typealias OutboundOut = HTTP2Frame
private var streams: [HTTP2StreamID: HTTP2StreamChannel] = [:]
private let inboundStreamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture<Void>)?
private let channel: Channel
private var nextOutboundStreamID: HTTP2StreamID
private let connectionFlowControlManager: InboundWindowManager
public func handlerAdded(ctx: ChannelHandlerContext) {
// We now need to check that we're on the same event loop as the one we were originally given.
// If we weren't, this is a hard failure, as there is a thread-safety issue here.
self.channel.eventLoop.preconditionInEventLoop()
}
public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
let frame = self.unwrapInboundIn(data)
let streamID = frame.streamID
guard streamID != .rootStream else {
// For stream 0 we forward all frames on to the main channel.
ctx.fireChannelRead(data)
return
}
if let channel = streams[streamID] {
channel.receiveInboundFrame(frame)
} else if case .headers = frame.payload {
let channel = HTTP2StreamChannel(allocator: self.channel.allocator,
parent: self.channel,
streamID: streamID,
targetWindowSize: 65535, // TODO: make configurable
initiatedRemotely: true)
channel.configure(initializer: self.inboundStreamStateInitializer)
self.streams[streamID] = channel
channel.closeFuture.whenComplete { _ in
self.childChannelClosed(streamID: streamID)
}
channel.receiveInboundFrame(frame)
} else {
// This frame is for a stream we know nothing about. We can't do much about it, so we
// are going to fire an error and drop the frame.
let error = NIOHTTP2Errors.NoSuchStream(streamID: streamID)
ctx.fireErrorCaught(error)
}
}
public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
/* for now just forward */
ctx.write(data, promise: promise)
}
public func channelActive(ctx: ChannelHandlerContext) {
// We just got channelActive. Any previously existing channels may be marked active.
for channel in self.streams.values {
// We double-check the channel activity here, because it's possible action taken during
// the activation of one of the child channels will cause the parent to close!
if ctx.channel.isActive {
channel.performActivation()
}
}
}
public func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) {
switch event {
case let evt as StreamClosedEvent:
if let channel = self.streams[evt.streamID] {
channel.receiveStreamClosed(evt.reason)
}
case let evt as NIOHTTP2WindowUpdatedEvent where evt.streamID == .rootStream:
// This force-unwrap is safe: we always have a connection window.
self.newConnectionWindowSize(newSize: evt.inboundWindowSize!, ctx: ctx)
case let evt as NIOHTTP2WindowUpdatedEvent:
if let channel = self.streams[evt.streamID], let windowSize = evt.inboundWindowSize {
channel.receiveWindowUpdatedEvent(windowSize)
}
default:
break
}
ctx.fireUserInboundEventTriggered(event)
}
private func childChannelClosed(streamID: HTTP2StreamID) {
self.streams.removeValue(forKey: streamID)
}
private func newConnectionWindowSize(newSize: Int, ctx: ChannelHandlerContext) {
guard let increment = self.connectionFlowControlManager.newWindowSize(newSize) else {
return
}
// This is too much flushing, but for now it'll have to do.
let frame = HTTP2Frame(streamID: .rootStream, payload: .windowUpdate(windowSizeIncrement: increment))
ctx.writeAndFlush(self.wrapOutboundOut(frame), promise: nil)
}
/// Create a new `HTTP2StreamMultiplexer`.
///
/// - parameters:
/// - mode: The mode of the HTTP/2 connection being used: server or client.
/// - channel: The Channel to which this `HTTP2StreamMultiplexer` belongs.
/// - targetWindowSize: The target inbound connection and stream window size. Defaults to 65535 bytes.
/// - inboundStreamStateInitializer: A block that will be invoked to configure each new child stream
/// channel that is created by the remote peer. For servers, these are channels created by
/// receiving a `HEADERS` frame from a client. For clients, these are channels created by
/// receiving a `PUSH_PROMISE` frame from a server. To initiate a new outbound channel, use
/// `createStreamChannel`.
public init(mode: NIOHTTP2Handler.ParserMode, channel: Channel, targetWindowSize: Int = 65535, inboundStreamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture<Void>)? = nil) {
self.inboundStreamStateInitializer = inboundStreamStateInitializer
self.channel = channel
self.connectionFlowControlManager = InboundWindowManager(targetSize: Int32(targetWindowSize))
switch mode {
case .client:
self.nextOutboundStreamID = 1
case .server:
self.nextOutboundStreamID = 2
}
}
}
extension HTTP2StreamMultiplexer {
/// Create a new `Channel` for a new stream initiated by this peer.
///
/// This method is intended for situations where the NIO application is initiating the stream. For clients,
/// this is for all request streams. For servers, this is for pushed streams.
///
/// - note:
/// Resources for the stream will be freed after it has been closed.
///
/// - parameters:
/// - promise: An `EventLoopPromise` that will be succeeded with the new activated channel, or
/// failed if an error occurs.
/// - streamStateInitializer: A callback that will be invoked to allow you to configure the
/// `ChannelPipeline` for the newly created channel.
public func createStreamChannel(promise: EventLoopPromise<Channel>?, _ streamStateInitializer: @escaping (Channel, HTTP2StreamID) -> EventLoopFuture<Void>) {
self.channel.eventLoop.execute {
let streamID = self.nextOutboundStreamID
self.nextOutboundStreamID = HTTP2StreamID(Int32(streamID) + 2)
let channel = HTTP2StreamChannel(allocator: self.channel.allocator,
parent: self.channel,
streamID: streamID,
targetWindowSize: 65535, // TODO: make configurable
initiatedRemotely: false)
let activationFuture = channel.configure(initializer: streamStateInitializer)
self.streams[streamID] = channel
channel.closeFuture.whenComplete { _ in
self.childChannelClosed(streamID: streamID)
}
if let promise = promise {
activationFuture.map { channel }.cascade(to: promise)
}
}
}
}