From 0ca970583136c62e33b05c9b2090e28cb770ab89 Mon Sep 17 00:00:00 2001 From: John Kassebaum <39099029+johnkassebaum@users.noreply.github.com> Date: Mon, 11 May 2020 04:34:43 -0700 Subject: [PATCH] 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 --- Sources/NIOHTTP2/HTTP2PipelineHelpers.swift | 52 ++++- Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift | 4 +- .../ConfiguringPipelineTests+XCTest.swift | 5 + .../ConfiguringPipelineTests.swift | 195 ++++++++++++++++++ 4 files changed, 253 insertions(+), 3 deletions(-) diff --git a/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift b/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift index bb0316c..e3d1d61 100644 --- a/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift +++ b/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift @@ -97,10 +97,33 @@ extension Channel { initialLocalSettings: [HTTP2Setting] = nioDefaultSettings, position: ChannelPipeline.Position = .last, inboundStreamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture)? = nil) -> EventLoopFuture { + 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)? = nil) -> EventLoopFuture { 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)? = nil, _ configurator: @escaping (Channel) -> EventLoopFuture) -> EventLoopFuture { + 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` that completes when the channel is ready. + public func configureCommonHTTPServerPipeline( + h2ConnectionChannelConfigurator: ((Channel) -> EventLoopFuture)? = nil, + targetWindowSize: Int, + _ configurator: @escaping (Channel) -> EventLoopFuture) -> EventLoopFuture { let h2ChannelConfigurator = { (channel: Channel) -> EventLoopFuture in - channel.configureHTTP2Pipeline(mode: .server) { (streamChannel, streamID) -> EventLoopFuture in + channel.configureHTTP2Pipeline(mode: .server, targetWindowSize: targetWindowSize) { (streamChannel, streamID) -> EventLoopFuture in streamChannel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID)).flatMap { () -> EventLoopFuture in configurator(streamChannel) } @@ -191,4 +238,5 @@ extension Channel { return self.configureHTTP2SecureUpgrade(h2ChannelConfigurator: h2ChannelConfigurator, http1ChannelConfigurator: http1ChannelConfigurator) } + } diff --git a/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift index 94a6f05..62799cb 100644 --- a/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift +++ b/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift @@ -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)? = 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 diff --git a/Tests/NIOHTTP2Tests/ConfiguringPipelineTests+XCTest.swift b/Tests/NIOHTTP2Tests/ConfiguringPipelineTests+XCTest.swift index 1612253..724adb1 100644 --- a/Tests/NIOHTTP2Tests/ConfiguringPipelineTests+XCTest.swift +++ b/Tests/NIOHTTP2Tests/ConfiguringPipelineTests+XCTest.swift @@ -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), ] } diff --git a/Tests/NIOHTTP2Tests/ConfiguringPipelineTests.swift b/Tests/NIOHTTP2Tests/ConfiguringPipelineTests.swift index fa53335..4353950 100644 --- a/Tests/NIOHTTP2Tests/ConfiguringPipelineTests.swift +++ b/Tests/NIOHTTP2Tests/ConfiguringPipelineTests.swift @@ -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 = 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 + + init(inactivePromise: EventLoopPromise) { + 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 = self.clientChannel.eventLoop.makePromise() + let streamChannelPromise: EventLoopPromise = 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 {