Make multiplexer's targetWindowSize configurable and use configurability when creating stream channels. (#202)

Motivation:
Infow target window size constrains throughput. The default hardcoded 65535 is low for some use cases and so needs to be configrable. A TODO in the code stated 'Make configurable'.

Modifications:
- In HTTP2StreamMultiplexer, responding to a TODO where stream multiplexer creates a stream channel, created a multiplexr stored property to be used which is set in the default initilaizer.
- In HTTP2PipelineHelpers, added versions of configureHTTP2Pipeline(..) and configureCommonHTTP2ServerPipeline that require an activeTargetWindow arg.

Result:
Clients, such as GRPCClient, can configure pipelines with targetWindowSizes to their liking.

Co-authored-by: Cory Benfield <lukasa@apple.com>
This commit is contained in:
John KassebaumandCory Benfield authored and GitHub committed 2020-05-11 12:34:43 +01:00
1 parent 32db4dd7c2
commit 0ca9705831
4 files changed
+253 -3

No files matched your search

+50 -2
View File
@@ -97,10 +97,33 @@ extension Channel {
initialLocalSettings: [HTTP2Setting] = nioDefaultSettings,
position: ChannelPipeline.Position = .last,
inboundStreamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture<Void>)? = nil) -> EventLoopFuture<HTTP2StreamMultiplexer> {
return self.configureHTTP2Pipeline(mode: mode, initialLocalSettings: initialLocalSettings, position: position, targetWindowSize: 65535, inboundStreamStateInitializer: inboundStreamStateInitializer)
}
/// Configures a `ChannelPipeline` to speak HTTP/2.
///
/// In general this is not entirely useful by itself, as HTTP/2 is a negotiated protocol. This helper does not handle negotiation.
/// Instead, this simply adds the handlers required to speak HTTP/2 after negotiation has completed, or when agreed by prior knowledge.
/// Whenever possible use this function to setup a HTTP/2 server pipeline, as it allows that pipeline to evolve without breaking your code.
///
/// - parameters:
/// - mode: The mode this pipeline will operate in, server or client.
/// - initialLocalSettings: The settings that will be used when establishing the connection. These will be sent to the peer as part of the
/// handshake.
/// - position: The position in the pipeline into which to insert these handlers.
/// - targetWindowSize: The target size of the HTTP/2 flow control window.
/// - inboundStreamStateInitializer: A closure that will be called whenever the remote peer initiates a new stream. This should almost always
/// be provided, especially on servers.
/// - returns: An `EventLoopFuture` containing the `HTTP2StreamMultiplexer` inserted into this pipeline, which can be used to initiate new streams.
public func configureHTTP2Pipeline(mode: NIOHTTP2Handler.ParserMode,
initialLocalSettings: [HTTP2Setting] = nioDefaultSettings,
position: ChannelPipeline.Position = .last,
targetWindowSize: Int,
inboundStreamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture<Void>)? = nil) -> EventLoopFuture<HTTP2StreamMultiplexer> {
var handlers = [ChannelHandler]()
handlers.reserveCapacity(2) // Update this if we need to add more handlers, to avoid unnecessary reallocation.
handlers.append(NIOHTTP2Handler(mode: mode, initialSettings: initialLocalSettings))
let multiplexer = HTTP2StreamMultiplexer(mode: mode, channel: self, inboundStreamStateInitializer: inboundStreamStateInitializer)
let multiplexer = HTTP2StreamMultiplexer(mode: mode, channel: self, targetWindowSize: targetWindowSize, inboundStreamStateInitializer: inboundStreamStateInitializer)
handlers.append(multiplexer)
return self.pipeline.addHandlers(handlers, position: position).map { multiplexer }
@@ -170,8 +193,32 @@ extension Channel {
public func configureCommonHTTPServerPipeline(
h2ConnectionChannelConfigurator: ((Channel) -> EventLoopFuture<Void>)? = nil,
_ configurator: @escaping (Channel) -> EventLoopFuture<Void>) -> EventLoopFuture<Void> {
return self.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: h2ConnectionChannelConfigurator, targetWindowSize: 65535, configurator)
}
/// Configures a `ChannelPipeline` to speak either HTTP or HTTP/2 according to what can be negotiated with the client.
///
/// This helper takes care of configuring the server pipeline such that it negotiates whether to
/// use HTTP/1.1 or HTTP/2. Once the protocol to use for the channel has been negotiated, the
/// provided callback will configure the application-specific handlers in a protocol-agnostic way.
///
/// This function doesn't configure the TLS handler. Callers of this function need to add a TLS
/// handler appropriately configured to perform protocol negotiation.
///
/// - parameters:
/// - h2ConnectionChannelConfigurator: An optional callback that will be invoked only
/// when the negotiated protocol is H2 to configure the connection channel.
/// - targetWindowSize: The target size of the HTTP/2 flow control window.
/// - configurator: A callback that will be invoked after a protocol has been negotiated.
/// The callback only needs to add application-specific handlers and must return a future
/// that completes when the channel has been fully mutated.
/// - returns: `EventLoopFuture<Void>` that completes when the channel is ready.
public func configureCommonHTTPServerPipeline(
h2ConnectionChannelConfigurator: ((Channel) -> EventLoopFuture<Void>)? = nil,
targetWindowSize: Int,
_ configurator: @escaping (Channel) -> EventLoopFuture<Void>) -> EventLoopFuture<Void> {
let h2ChannelConfigurator = { (channel: Channel) -> EventLoopFuture<Void> in
channel.configureHTTP2Pipeline(mode: .server) { (streamChannel, streamID) -> EventLoopFuture<Void> in
channel.configureHTTP2Pipeline(mode: .server, targetWindowSize: targetWindowSize) { (streamChannel, streamID) -> EventLoopFuture<Void> in
streamChannel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID)).flatMap { () -> EventLoopFuture<Void> in
configurator(streamChannel)
}
@@ -191,4 +238,5 @@ extension Channel {
return self.configureHTTP2SecureUpgrade(h2ChannelConfigurator: h2ChannelConfigurator,
http1ChannelConfigurator: http1ChannelConfigurator)
}
}
@@ -37,6 +37,7 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun
private var didReadChannels: StreamChannelList = StreamChannelList()
private let streamChannelOutboundBytesHighWatermark: Int
private let streamChannelOutboundBytesLowWatermark: Int
private let targetWindowSize: Int
public func handlerAdded(context: ChannelHandlerContext) {
// We now need to check that we're on the same event loop as the one we were originally given.
@@ -239,6 +240,7 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun
inboundStreamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture<Void>)? = nil) {
self.inboundStreamStateInitializer = inboundStreamStateInitializer
self.channel = channel
self.targetWindowSize = max(0, min(targetWindowSize, Int(Int32.max)))
self.connectionFlowControlManager = InboundWindowManager(targetSize: Int32(targetWindowSize))
self.streamChannelOutboundBytesHighWatermark = outboundBufferSizeHighWatermark
self.streamChannelOutboundBytesLowWatermark = outboundBufferSizeLowWatermark
@@ -301,7 +303,7 @@ extension HTTP2StreamMultiplexer {
parent: self.channel,
multiplexer: self,
streamID: streamID,
targetWindowSize: 65535, // TODO: make configurable
targetWindowSize: Int32(self.targetWindowSize),
outboundBytesHighWatermark: self.streamChannelOutboundBytesHighWatermark,
outboundBytesLowWatermark: self.streamChannelOutboundBytesLowWatermark)
self.streams[streamID] = channel
@@ -27,10 +27,15 @@ extension ConfiguringPipelineTests {
static var allTests : [(String, (ConfiguringPipelineTests) -> () throws -> Void)] {
return [
("testBasicPipelineCommunicates", testBasicPipelineCommunicates),
("testBasicPipelineCommunicatesWithTargetWindowSize", testBasicPipelineCommunicatesWithTargetWindowSize),
("testPipelineRespectsPositionRequest", testPipelineRespectsPositionRequest),
("testPipelineRespectsPositionRequestWithTargetWindowSize", testPipelineRespectsPositionRequestWithTargetWindowSize),
("testPreambleGetsWrittenOnce", testPreambleGetsWrittenOnce),
("testPreambleGetsWrittenOnceWithTargetWindowSize", testPreambleGetsWrittenOnceWithTargetWindowSize),
("testClosingParentChannelClosesStreamChannel", testClosingParentChannelClosesStreamChannel),
("testClosingParentChannelClosesStreamChannelWithTargetWindowSize", testClosingParentChannelClosesStreamChannelWithTargetWindowSize),
("testNegotiatedHTTP2BasicPipelineCommunicates", testNegotiatedHTTP2BasicPipelineCommunicates),
("testNegotiatedHTTP2BasicPipelineCommunicatesWithTargetWindowSize", testNegotiatedHTTP2BasicPipelineCommunicatesWithTargetWindowSize),
("testNegotiatedHTTP1BasicPipelineCommunicates", testNegotiatedHTTP1BasicPipelineCommunicates),
]
}
@@ -86,6 +86,46 @@ class ConfiguringPipelineTests: XCTestCase {
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testBasicPipelineCommunicatesWithTargetWindowSize() throws {
let serverRecorder = FrameRecorderHandler()
let clientHandler = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, targetWindowSize: 65535).wait())
XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535) { channel, streamID in
return channel.pipeline.addHandler(serverRecorder)
}.wait())
XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel))
// Let's try sending a request.
let requestPromise = self.clientChannel.eventLoop.makePromise(of: Void.self)
let reqFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([(":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/")]), endStream: true)))
clientHandler.createStreamChannel(promise: nil) { channel, streamID in
XCTAssertEqual(streamID, HTTP2StreamID(1))
channel.writeAndFlush(reqFrame).whenComplete { _ in channel.close(promise: requestPromise) }
return channel.eventLoop.makeSucceededFuture(())
}
// In addition to interacting in memory, we need two loop spins. The first is to execute `createStreamChannel`.
// The second is to execute the close promise callback, after the interaction is complete.
(self.clientChannel.eventLoop as! EmbeddedEventLoop).run()
self.interactInMemory(self.clientChannel, self.serverChannel)
(self.clientChannel.eventLoop as! EmbeddedEventLoop).run()
XCTAssertThrowsError(try requestPromise.futureResult.wait()) { error in
XCTAssertTrue(error is NIOHTTP2Errors.StreamClosed)
}
// We should have received a HEADERS and a RST_STREAM frame.
// The RST_STREAM frame is from closing an incomplete stream on the client side.
let rstStreamFrame = HTTP2Frame(streamID: 1, payload: .rstStream(.cancel))
serverRecorder.receivedFrames.assertFramesMatch([reqFrame, rstStreamFrame])
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testPipelineRespectsPositionRequest() throws {
XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(FailOnWriteHandler()).wait())
@@ -104,6 +144,23 @@ class ConfiguringPipelineTests: XCTestCase {
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testPipelineRespectsPositionRequestWithTargetWindowSize() throws {
XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(FailOnWriteHandler()).wait())
XCTAssertNoThrow(try self.clientChannel.configureHTTP2Pipeline(mode: .client, position: .first, targetWindowSize: 65535).wait())
XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535).wait())
XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel))
// It's hard to see this, but if we got this far without a failure there is no failure. It means there were no writes
// passing through the FailOnWriteHandler, which is what we expect, as we asked for the handlers to be inserted in
// front of it. Now we just clean up.
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testPreambleGetsWrittenOnce() throws {
// This test checks that the preamble sent by NIOHTTP2Handler is only written once. There are two paths
// to sending the preamble, in handlerAdded(context:) (if the channel is active) and in channelActive(context:),
@@ -137,6 +194,39 @@ class ConfiguringPipelineTests: XCTestCase {
XCTAssertNil(try self.serverChannel.readOutbound(as: IOData.self))
}
func testPreambleGetsWrittenOnceWithTargetWindowSize() throws {
// This test checks that the preamble sent by NIOHTTP2Handler is only written once. There are two paths
// to sending the preamble, in handlerAdded(context:) (if the channel is active) and in channelActive(context:),
// we want to hit both of these.
let connectionPromise: EventLoopPromise<Void> = self.serverChannel.eventLoop.makePromise()
// Register the callback on the promise so we run it as it succeeds (i.e. before fireChannelActive is called).
let handlerAdded = connectionPromise.futureResult.flatMap {
// Use .server to avoid sending client magic.
self.serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535)
}
self.serverChannel.connect(to: try SocketAddress(unixDomainSocketPath: "/fake"), promise: connectionPromise)
XCTAssertNoThrow(try handlerAdded.wait())
let initialSettingsData: IOData? = try self.serverChannel.readOutbound()
XCTAssertNotNil(initialSettingsData)
guard case .some(.byteBuffer(let initialSettingsBuffer)) = initialSettingsData else {
XCTFail("Expected ByteBuffer containing the initial SETTINGS frame")
return
}
XCTAssertGreaterThanOrEqual(initialSettingsBuffer.readableBytes, 9)
// The 4-th byte contains the frame type (4 for SETTINGS).
XCTAssertEqual(initialSettingsBuffer.getInteger(at: initialSettingsBuffer.readerIndex + 3, as: UInt8.self), 4)
// Bytes 6-9 contain the stream ID; this should be the root stream, 0.
XCTAssertEqual(initialSettingsBuffer.getInteger(at: initialSettingsBuffer.readerIndex + 6, as: UInt32.self), 0)
// We don't expect anything else at this point.
XCTAssertNil(try self.serverChannel.readOutbound(as: IOData.self))
}
func testClosingParentChannelClosesStreamChannel() throws {
/// A channel handler that succeeds a promise when the channel becomes inactive.
final class InactiveHandler: ChannelInboundHandler {
@@ -179,6 +269,49 @@ class ConfiguringPipelineTests: XCTestCase {
}
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testClosingParentChannelClosesStreamChannelWithTargetWindowSize() throws {
/// A channel handler that succeeds a promise when the channel becomes inactive.
final class InactiveHandler: ChannelInboundHandler {
typealias InboundIn = Any
let inactivePromise: EventLoopPromise<Void>
init(inactivePromise: EventLoopPromise<Void>) {
self.inactivePromise = inactivePromise
}
func channelInactive(context: ChannelHandlerContext) {
inactivePromise.succeed(())
}
}
let clientMultiplexer = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, targetWindowSize: 65535).wait())
XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535).wait())
XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel))
let inactivePromise: EventLoopPromise<Void> = self.clientChannel.eventLoop.makePromise()
let streamChannelPromise: EventLoopPromise<Channel> = self.clientChannel.eventLoop.makePromise()
clientMultiplexer.createStreamChannel(promise: streamChannelPromise) { channel, _ in
return channel.pipeline.addHandler(InactiveHandler(inactivePromise: inactivePromise))
}
(self.clientChannel.eventLoop as! EmbeddedEventLoop).run()
let streamChannel = try assertNoThrowWithValue(try streamChannelPromise.futureResult.wait())
// Close the parent channel, not the stream channel.
XCTAssertNoThrow(try self.clientChannel.close().wait())
XCTAssertNoThrow(try inactivePromise.futureResult.wait())
XCTAssertFalse(streamChannel.isActive)
XCTAssertThrowsError(try self.clientChannel.finish()) { error in
XCTAssertEqual(error as? ChannelError, .alreadyClosed)
}
XCTAssertNoThrow(try self.serverChannel.finish())
}
/// A simple channel handler that records inbound frames.
class HTTP1ServerRequestRecorderHandler: ChannelInboundHandler {
@@ -252,6 +385,68 @@ class ConfiguringPipelineTests: XCTestCase {
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testNegotiatedHTTP2BasicPipelineCommunicatesWithTargetWindowSize() throws {
final class ErrorHandler: ChannelInboundHandler {
typealias InboundIn = Never
func errorCaught(context: ChannelHandlerContext, error: Error) {
context.close(promise: nil)
}
}
let serverRecorder = HTTP1ServerRequestRecorderHandler()
let clientHandler = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, targetWindowSize: 65535).wait())
XCTAssertNoThrow(try self.serverChannel.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: { $0.pipeline.addHandler(ErrorHandler()) }) { channel in
return channel.pipeline.addHandler(serverRecorder)
}.wait())
// Let's pretent the TLS handler did protocol negotiation for us
self.serverChannel.pipeline.fireUserInboundEventTriggered (TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2"))
XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel))
// Let's try sending an h2 request.
let requestPromise = self.clientChannel.eventLoop.makePromise(of: Void.self)
let reqFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([(":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/testH2toHTTP1")]), endStream: true)))
clientHandler.createStreamChannel(promise: nil) { channel, streamID in
XCTAssertEqual(streamID, HTTP2StreamID(1))
channel.writeAndFlush(reqFrame).whenComplete { _ in channel.close(promise: requestPromise) }
return channel.eventLoop.makeSucceededFuture(())
}
// In addition to interacting in memory, we need two loop spins. The first is to execute `createStreamChannel`.
// The second is to execute the close promise callback, after the interaction is complete.
(self.clientChannel.eventLoop as! EmbeddedEventLoop).run()
self.interactInMemory(self.clientChannel, self.serverChannel)
(self.clientChannel.eventLoop as! EmbeddedEventLoop).run()
XCTAssertThrowsError(try requestPromise.futureResult.wait()) { error in
XCTAssertTrue(error is NIOHTTP2Errors.StreamClosed)
}
// Assert that the user-provided handler received the
// HTTP1 parts corresponding to the H2 message sent
XCTAssertEqual(2, serverRecorder.receivedParts.count)
if case .some(.head(let head)) = serverRecorder.receivedParts.first {
XCTAssertEqual(1, head.headers["host"].count)
XCTAssertEqual("localhost", head.headers["host"].first)
XCTAssertEqual(.GET, head.method)
XCTAssertEqual("/testH2toHTTP1", head.uri)
} else {
XCTFail("Expected head")
}
if case .some(.end(_)) = serverRecorder.receivedParts.last {
} else {
XCTFail("Expected end")
}
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testNegotiatedHTTP1BasicPipelineCommunicates() throws {
final class ErrorHandler: ChannelInboundHandler {