diff --git a/Sources/NIOHTTP2/HTTP2StreamChannel.swift b/Sources/NIOHTTP2/HTTP2StreamChannel.swift index dd0bf29..61b02ab 100644 --- a/Sources/NIOHTTP2/HTTP2StreamChannel.swift +++ b/Sources/NIOHTTP2/HTTP2StreamChannel.swift @@ -67,9 +67,9 @@ private enum StreamChannelState { mutating func completeClosing() { switch self { - case .closing, .closingFromIdle, .active: + case .idle, .closing, .closingFromIdle, .active: self = .closed - case .idle, .closed: + case .closed: preconditionFailure("Complete closing from \(self)") } } @@ -77,7 +77,7 @@ private enum StreamChannelState { final class HTTP2StreamChannel: Channel, ChannelCore { - public init(allocator: ByteBufferAllocator, parent: Channel, streamID: HTTP2StreamID, initializer: ((Channel, HTTP2StreamID) -> EventLoopFuture)?) { + internal init(allocator: ByteBufferAllocator, parent: Channel, streamID: HTTP2StreamID) { self.allocator = allocator self.closePromise = parent.eventLoop.newPromise() self.localAddress = parent.localAddress @@ -92,15 +92,17 @@ final class HTTP2StreamChannel: Channel, ChannelCore { // To begin with we initialize autoRead to false, but we are going to fetch it from our parent before we // go much further. self.autoRead = false - self._pipeline = ChannelPipeline(channel: self) + } - // Now we need to configure this channel. This involves doing four things: + @discardableResult + internal func configure(initializer: ((Channel, HTTP2StreamID) -> EventLoopFuture)?) -> EventLoopFuture { + // We need to configure this channel. This involves doing four things: // 1. Setting our autoRead state from the parent // 2. Calling the initializer, if provided. // 3. Activating when complete. // 4. Catching errors if they occur. - parent.getOption(option: ChannelOptions.autoRead).then { autoRead -> EventLoopFuture in + let f = self.parent!.getOption(option: ChannelOptions.autoRead).then { autoRead -> EventLoopFuture in self.autoRead = autoRead return initializer?(self, self.streamID) ?? self.eventLoop.newSucceededFuture(result: ()) }.map { @@ -109,9 +111,17 @@ final class HTTP2StreamChannel: Channel, ChannelCore { if self.autoRead { self.read0() } - }.whenFailure { (_: Error) in - self.closedWhileOpen() + self.deliverPendingWrites() } + + f.whenFailure { (error: Error) in + if self.streamID.networkStreamID != nil { + self.closedWhileOpen() + } else { + self.errorEncountered(error: error) + } + } + return f } private var _pipeline: ChannelPipeline! @@ -254,12 +264,11 @@ final class HTTP2StreamChannel: Channel, ChannelCore { } public func flush0() { - guard self.state != .closed else { - return - } self.pendingWrites.mark() - self.deliverPendingWrites() - self.parent?.flush() + + if self.isActive { + self.deliverPendingWrites() + } } public func read0() { @@ -412,10 +421,16 @@ private extension HTTP2StreamChannel { /// Delivers all pending flushed writes to the parent channel. private func deliverPendingWrites() { + // If there are no pending writes, don't bother with the processing. + guard self.pendingWrites.hasMark() else { + return + } + while self.pendingWrites.hasMark() { let write = self.pendingWrites.removeFirst() self.receiveOutboundFrame(write.0, promise: write.1) } + self.parent?.flush() } /// Fails all pending writes with the given error. diff --git a/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift index 7e1c036..5145b3b 100644 --- a/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift +++ b/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift @@ -29,7 +29,16 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun public typealias OutboundOut = HTTP2Frame private var streams: [HTTP2StreamID: HTTP2StreamChannel] = [:] - private let streamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture)? + private let inboundStreamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture)? + private var channel: Channel? + + public func handlerAdded(ctx: ChannelHandlerContext) { + self.channel = ctx.channel + } + + public func handlerRemoved(ctx: ChannelHandlerContext) { + self.channel = nil + } public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { let frame = self.unwrapInboundIn(data) @@ -44,11 +53,10 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun if let channel = streams[streamID] { channel.receiveInboundFrame(frame) } else if case .headers = frame.payload { - let channel = HTTP2StreamChannel(allocator: ctx.channel.allocator, - parent: ctx.channel, - streamID: streamID, - initializer: self.streamStateInitializer) - + let channel = HTTP2StreamChannel(allocator: self.channel!.allocator, + parent: self.channel!, + streamID: streamID) + channel.configure(initializer: self.inboundStreamStateInitializer) self.streams[streamID] = channel channel.closeFuture.whenComplete { self.childChannelClosed(streamID: streamID) @@ -83,7 +91,51 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun self.streams.removeValue(forKey: streamID) } - public init(streamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture)? = nil) { - self.streamStateInitializer = streamStateInitializer + /// Create a new `HTTP2StreamMultiplexer`. + /// + /// - parameters: + /// - 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(inboundStreamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture)? = nil) { + self.inboundStreamStateInitializer = inboundStreamStateInitializer + } +} + +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. + /// + /// - 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. + /// - returns: An `EventLoopFuture` that completes with the new channel. + public func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping (Channel, HTTP2StreamID) -> EventLoopFuture) { + guard let ourChannel = self.channel else { + promise?.fail(error: ChannelError.ioOnClosedChannel) + return + } + + ourChannel.eventLoop.execute { + let streamID = HTTP2StreamID() + let channel = HTTP2StreamChannel(allocator: ourChannel.allocator, + parent: ourChannel, + streamID: streamID) + let activationFuture = channel.configure(initializer: streamStateInitializer) + self.streams[streamID] = channel + channel.closeFuture.whenComplete { + self.childChannelClosed(streamID: streamID) + } + + if let promise = promise { + activationFuture.map { channel }.cascade(promise: promise) + } + } } } diff --git a/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests+XCTest.swift b/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests+XCTest.swift index cf235a2..35c5398 100644 --- a/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests+XCTest.swift +++ b/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests+XCTest.swift @@ -50,6 +50,10 @@ extension HTTP2StreamMultiplexerTests { ("testReadWithNoPendingDataCausesReadOnParentChannel", testReadWithNoPendingDataCausesReadOnParentChannel), ("testHandlersAreRemovedOnClosure", testHandlersAreRemovedOnClosure), ("testHandlersAreRemovedOnClosureWithError", testHandlersAreRemovedOnClosureWithError), + ("testCreatingOutboundChannel", testCreatingOutboundChannel), + ("testWritesOnCreatedChannelAreDelayed", testWritesOnCreatedChannelAreDelayed), + ("testWritesAreCancelledOnFailingInitializer", testWritesAreCancelledOnFailingInitializer), + ("testFailingInitializerDoesNotWrite", testFailingInitializerDoesNotWrite), ] } } diff --git a/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift b/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift index b0dbdb4..74c3a1c 100644 --- a/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift +++ b/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift @@ -997,4 +997,119 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.finish()) } + + func testCreatingOutboundChannel() throws { + let configurePromise: EventLoopPromise = self.channel.eventLoop.newPromise() + var createdChannelCount = 0 + var configuredChannelCount = 0 + let multiplexer = HTTP2StreamMultiplexer { (_, _) in + XCTFail("Must not be called") + return self.channel.eventLoop.newFailedFuture(error: MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.add(handler: multiplexer).wait()) + + for _ in 0..<3 { + let channelPromise: EventLoopPromise = self.channel.eventLoop.newPromise() + multiplexer.createStreamChannel(promise: channelPromise) { (channel, streamID) in + createdChannelCount += 1 + return configurePromise.futureResult + } + channelPromise.futureResult.whenSuccess { _ in + configuredChannelCount += 1 + } + } + + XCTAssertEqual(createdChannelCount, 0) + XCTAssertEqual(configuredChannelCount, 0) + + (self.channel.eventLoop as! EmbeddedEventLoop).run() + XCTAssertEqual(createdChannelCount, 3) + XCTAssertEqual(configuredChannelCount, 0) + + configurePromise.succeed(result: ()) + XCTAssertEqual(createdChannelCount, 3) + XCTAssertEqual(configuredChannelCount, 3) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testWritesOnCreatedChannelAreDelayed() throws { + let configurePromise: EventLoopPromise = self.channel.eventLoop.newPromise() + let writeRecorder = FrameWriteRecorder() + var childChannel: Channel? = nil + var childStreamID: HTTP2StreamID? = nil + + let multiplexer = HTTP2StreamMultiplexer { (_, _) in + XCTFail("Must not be called") + return self.channel.eventLoop.newFailedFuture(error: MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.add(handler: writeRecorder).wait()) + XCTAssertNoThrow(try self.channel.pipeline.add(handler: multiplexer).wait()) + multiplexer.createStreamChannel(promise: nil) { (channel, streamID) in + childChannel = channel + childStreamID = streamID + return configurePromise.futureResult + } + (self.channel.eventLoop as! EmbeddedEventLoop).run() + XCTAssertNotNil(childChannel) + XCTAssertNotNil(childStreamID) + + childChannel!.writeAndFlush(HTTP2Frame(streamID: childStreamID!, payload: .headers(HTTPHeaders())), promise: nil) + XCTAssertEqual(writeRecorder.flushedWrites.count, 0) + + configurePromise.succeed(result: ()) + (self.channel.eventLoop as! EmbeddedEventLoop).run() + XCTAssertEqual(writeRecorder.flushedWrites.count, 1) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testWritesAreCancelledOnFailingInitializer() throws { + let configurePromise: EventLoopPromise = self.channel.eventLoop.newPromise() + var childChannel: Channel? = nil + var childStreamID: HTTP2StreamID? = nil + + let multiplexer = HTTP2StreamMultiplexer { (_, _) in + XCTFail("Must not be called") + return self.channel.eventLoop.newFailedFuture(error: MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.add(handler: multiplexer).wait()) + multiplexer.createStreamChannel(promise: nil) { (channel, streamID) in + childChannel = channel + childStreamID = streamID + return configurePromise.futureResult + } + (self.channel.eventLoop as! EmbeddedEventLoop).run() + + var writeError: Error? = nil + childChannel!.writeAndFlush(HTTP2Frame(streamID: childStreamID!, payload: .headers(HTTPHeaders()))).whenFailure { writeError = $0 } + XCTAssertNil(writeError) + + configurePromise.fail(error: MyError()) + XCTAssertNotNil(writeError) + XCTAssertTrue(writeError is MyError) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testFailingInitializerDoesNotWrite() throws { + let configurePromise: EventLoopPromise = self.channel.eventLoop.newPromise() + let writeRecorder = FrameWriteRecorder() + + let multiplexer = HTTP2StreamMultiplexer { (_, _) in + XCTFail("Must not be called") + return self.channel.eventLoop.newFailedFuture(error: MyError()) + } + XCTAssertNoThrow(try self.channel.pipeline.add(handler: writeRecorder).wait()) + XCTAssertNoThrow(try self.channel.pipeline.add(handler: multiplexer).wait()) + multiplexer.createStreamChannel(promise: nil) { (channel, streamID) in + return configurePromise.futureResult + } + (self.channel.eventLoop as! EmbeddedEventLoop).run() + + configurePromise.fail(error: MyError()) + XCTAssertEqual(writeRecorder.flushedWrites.count, 0) + + XCTAssertNoThrow(try self.channel.finish()) + } }