From e2ea2b88b9af8cfd0e6fb5e6f84c3398e7e05e15 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Thu, 17 May 2018 11:58:25 +0100 Subject: [PATCH] Support read() --- Sources/NIOHTTP2/HTTP2StreamChannel.swift | 102 +++++++- .../HTTP2StreamMultiplexerTests.swift | 219 ++++++++++++++++++ 2 files changed, 309 insertions(+), 12 deletions(-) diff --git a/Sources/NIOHTTP2/HTTP2StreamChannel.swift b/Sources/NIOHTTP2/HTTP2StreamChannel.swift index 20970d3..60515ac 100644 --- a/Sources/NIOHTTP2/HTTP2StreamChannel.swift +++ b/Sources/NIOHTTP2/HTTP2StreamChannel.swift @@ -88,13 +88,27 @@ final class HTTP2StreamChannel: Channel, ChannelCore { // FIXME: that's just wrong self.isWritable = true self.state = .idle + + // 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) - let initializingFuture: EventLoopFuture = initializer?(self, self.streamID) ?? self.eventLoop.newSucceededFuture(result: ()) - initializingFuture.map { + // Now 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 + self.autoRead = autoRead + return initializer?(self, self.streamID) ?? self.eventLoop.newSucceededFuture(result: ()) + }.map { self.state.activate() self.pipeline.fireChannelActive() - self.deliverPendingReads() + if self.autoRead { + self.read0() + } }.whenFailure { (_: Error) in self.closedWhileOpen() } @@ -128,8 +142,16 @@ final class HTTP2StreamChannel: Channel, ChannelCore { fatalError() } - func setOption(option: T, value: T.OptionType) -> EventLoopFuture where T : ChannelOption { - fatalError() + func setOption(option: T, value: T.OptionType) -> EventLoopFuture where T: ChannelOption { + if eventLoop.inEventLoop { + do { + return eventLoop.newSucceededFuture(result: try setOption0(option: option, value: value)) + } catch { + return eventLoop.newFailedFuture(error: error) + } + } else { + return eventLoop.submit { try self.setOption0(option: option, value: value) } + } } public func getOption(option: T) -> EventLoopFuture where T: ChannelOption { @@ -144,14 +166,27 @@ final class HTTP2StreamChannel: Channel, ChannelCore { } } - func getOption0(option: T) throws -> T.OptionType { + private func setOption0(option: T, value: T.OptionType) throws where T: ChannelOption { + assert(eventLoop.inEventLoop) + + switch option { + case _ as AutoReadOption: + self.autoRead = value as! Bool + default: + fatalError("setting option \(option) on HTTP2StreamChannel not supported") + } + } + + private func getOption0(option: T) throws -> T.OptionType where T: ChannelOption { assert(eventLoop.inEventLoop) switch option { case _ as StreamIDOption: return self.streamID as! T.OptionType + case _ as AutoReadOption: + return self.autoRead as! T.OptionType default: - fatalError("option \(option) not supported") + fatalError("option \(option) not supported on HTTP2StreamChannel") } } @@ -182,6 +217,14 @@ final class HTTP2StreamChannel: Channel, ChannelCore { /// channel up. private var pendingReads: CircularBuffer = CircularBuffer(initialRingCapacity: 8) + /// Whether `autoRead` is enabled. By default, all `HTTP2StreamChannel` objects inherit their `autoRead` + /// state from their parent. + private var autoRead: Bool + + /// Whether a call to `read` has happened without any frames available to read (that is, whether newly + /// received frames should be immediately delivered to the pipeline). + private var unsatisfiedRead: Bool = false + /// A buffer of pending outbound writes to deliver to the parent channel. /// /// To correctly respect flushes, we deliberately withold frames from the parent channel until this @@ -220,7 +263,20 @@ final class HTTP2StreamChannel: Channel, ChannelCore { } public func read0() { - fatalError("not implemented \(#function)") + if self.unsatisfiedRead { + // We already have an unsatisfied read, let's do nothing. + return + } + + // At this stage, we have an unsatisfied read. If there is no pending data to read, + // we're going to call read() on the parent channel. Otherwise, we're going to + // succeed the read out of our pending data. + self.unsatisfiedRead = true + if self.pendingReads.count > 0 { + self.tryToRead() + } else { + self.parent?.read() + } } public func close0(error: Error, mode: CloseMode, promise: EventLoopPromise?) { @@ -302,6 +358,31 @@ final class HTTP2StreamChannel: Channel, ChannelCore { self.pipeline.fireChannelInactive() self.closePromise.fail(error: error) } + + private func tryToRead() { + // If there's no read to satisfy, no worries about it. + guard self.unsatisfiedRead else { + return + } + + assert(self.pendingReads.count > 0, "tryToRead called without reads!") + + // If we're not active, we will hold on to these reads. + guard self.isActive else { + return + } + + // Ok, we're satisfying a read here. + self.unsatisfiedRead = false + self.deliverPendingReads() + + // If auto-read is turned on, recurse into read0. + // This cannot recurse indefinitely unless frames are being delivered + // by the read stacks, which is generally fairly unlikely to continue unbounded. + if self.autoRead { + self.read0() + } + } } // MARK:- Functions used to manage pending reads and writes. @@ -351,10 +432,7 @@ internal extension HTTP2StreamChannel { } self.pendingReads.append(frame) - if self.isActive { - // TODO(cory): Replace this when we add support for read(). - self.deliverPendingReads() - } + self.tryToRead() } diff --git a/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift b/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift index 0872cd7..29b7266 100644 --- a/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift +++ b/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift @@ -96,6 +96,19 @@ final class InboundFrameRecorder: ChannelInboundHandler { } +/// A handler that tracks the number of times read() was called on the channel. +final class ReadCounter: ChannelOutboundHandler { + typealias OutboundIn = Any + typealias OutboundOut = Any + + var readCount = 0 + + func read(ctx: ChannelHandlerContext) { + readCount += 1 + } +} + + final class HTTP2StreamMultiplexerTests: XCTestCase { var channel: EmbeddedChannel! @@ -692,4 +705,210 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.finish()) } + + func testReadPullsInAllFrames() throws { + var childChannel: Channel? = nil + let frameRecorder = InboundFrameRecorder() + let multiplexer = HTTP2StreamMultiplexer { (channel, _) -> EventLoopFuture in + childChannel = channel + + // We're going to disable autoRead on this channel. + return channel.getOption(option: ChannelOptions.autoRead).map { + XCTAssertTrue($0) + }.then { + channel.setOption(option: ChannelOptions.autoRead, value: false) + }.then { + channel.getOption(option: ChannelOptions.autoRead) + }.map { + XCTAssertFalse($0) + }.then { + channel.pipeline.add(handler: frameRecorder) + } + } + XCTAssertNoThrow(try self.channel.pipeline.add(handler: multiplexer).wait()) + + // Let's open a stream. + let streamID = HTTP2StreamID(knownID: 1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(HTTPHeaders())) + XCTAssertNoThrow(try self.channel.writeInbound(frame)) + XCTAssertNotNil(channel) + + // Now we're going to deliver 5 data frames for this stream. + var buffer = self.channel.allocator.buffer(capacity: 12) + buffer.write(staticString: "Hello, world!") + for _ in 0..<5 { + let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.byteBuffer(buffer))) + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + } + + // These frames should not have been delivered. + XCTAssertEqual(frameRecorder.receivedFrames.count, 0) + + // We'll call read() on the child channel. + childChannel!.read() + + // All frames should now have been delivered. + XCTAssertEqual(frameRecorder.receivedFrames.count, 6) + frameRecorder.receivedFrames[0].assertFrameMatches(this: frame) + for idx in 1...5 { + frameRecorder.receivedFrames[idx].assertDataFrame(endStream: false, streamID: 1, payload: buffer) + } + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testReadIsPerChannel() throws { + let firstStreamID = HTTP2StreamID(knownID: 1) + let secondStreamID = HTTP2StreamID(knownID: 3) + var frameRecorders: [HTTP2StreamID: InboundFrameRecorder] = [:] + + let multiplexer = HTTP2StreamMultiplexer { (channel, streamID) -> EventLoopFuture in + let recorder = InboundFrameRecorder() + frameRecorders[streamID] = recorder + + // Disable autoRead on the first channel. + return channel.setOption(option: ChannelOptions.autoRead, value: streamID != firstStreamID).then { + return channel.pipeline.add(handler: recorder) + } + } + XCTAssertNoThrow(try self.channel.pipeline.add(handler: multiplexer).wait()) + + // Let's open two streams. + for streamID in [firstStreamID, secondStreamID] { + let frame = HTTP2Frame(streamID: streamID, payload: .headers(HTTPHeaders())) + XCTAssertNoThrow(try self.channel.writeInbound(frame)) + } + XCTAssertEqual(frameRecorders.count, 2) + + // Stream 1 should not have received a frame, stream 3 should. + XCTAssertEqual(frameRecorders[firstStreamID]!.receivedFrames.count, 0) + XCTAssertEqual(frameRecorders[secondStreamID]!.receivedFrames.count, 1) + + // Deliver a DATA frame to each stream, which should also have gone into stream 3 but not stream 1. + var buffer = self.channel.allocator.buffer(capacity: 12) + buffer.write(staticString: "Hello, world!") + for streamID in [firstStreamID, secondStreamID] { + let frame = HTTP2Frame(streamID: streamID, payload: .data(.byteBuffer(buffer))) + XCTAssertNoThrow(try self.channel.writeInbound(frame)) + } + + // Stream 1 should not have received a frame, stream 3 should. + XCTAssertEqual(frameRecorders[firstStreamID]!.receivedFrames.count, 0) + XCTAssertEqual(frameRecorders[secondStreamID]!.receivedFrames.count, 2) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testReadWillCauseAutomaticFrameDelivery() throws { + var childChannel: Channel? = nil + let frameRecorder = InboundFrameRecorder() + let multiplexer = HTTP2StreamMultiplexer { (channel, _) -> EventLoopFuture in + childChannel = channel + + // We're going to disable autoRead on this channel. + return channel.setOption(option: ChannelOptions.autoRead, value: false).then { + channel.pipeline.add(handler: frameRecorder) + } + } + XCTAssertNoThrow(try self.channel.pipeline.add(handler: multiplexer).wait()) + + // Let's open a stream. + let streamID = HTTP2StreamID(knownID: 1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(HTTPHeaders())) + XCTAssertNoThrow(try self.channel.writeInbound(frame)) + XCTAssertNotNil(channel) + + // This stream should have seen no frames. + XCTAssertEqual(frameRecorder.receivedFrames.count, 0) + + // Call read, the header frame will come through. + childChannel!.read() + XCTAssertEqual(frameRecorder.receivedFrames.count, 1) + + // Call read again, nothing happens. + childChannel!.read() + XCTAssertEqual(frameRecorder.receivedFrames.count, 1) + + // Now deliver a data frame. + var buffer = self.channel.allocator.buffer(capacity: 12) + buffer.write(staticString: "Hello, world!") + let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.byteBuffer(buffer))) + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + + // This frame should have been immediately delivered. + XCTAssertEqual(frameRecorder.receivedFrames.count, 2) + + // Delivering another data frame does nothing. + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + XCTAssertEqual(frameRecorder.receivedFrames.count, 2) + + XCTAssertNoThrow(try self.channel.finish()) + } + + func testReadWithNoPendingDataCausesReadOnParentChannel() throws { + var childChannel: Channel? = nil + let readCounter = ReadCounter() + let frameRecorder = InboundFrameRecorder() + let multiplexer = HTTP2StreamMultiplexer { (channel, _) -> EventLoopFuture in + childChannel = channel + + // We're going to disable autoRead on this channel. + return channel.setOption(option: ChannelOptions.autoRead, value: false).then { + channel.pipeline.add(handler: frameRecorder) + } + } + XCTAssertNoThrow(try self.channel.pipeline.add(handler: readCounter).wait()) + XCTAssertNoThrow(try self.channel.pipeline.add(handler: multiplexer).wait()) + + // Let's open a stream. + let streamID = HTTP2StreamID(knownID: 1) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(HTTPHeaders())) + XCTAssertNoThrow(try self.channel.writeInbound(frame)) + XCTAssertNotNil(channel) + + // This stream should have seen no frames. + XCTAssertEqual(frameRecorder.receivedFrames.count, 0) + + // There should be no calls to read. + XCTAssertEqual(readCounter.readCount, 0) + + // Call read, the header frame will come through. No calls to read on the parent stream. + childChannel!.read() + XCTAssertEqual(frameRecorder.receivedFrames.count, 1) + XCTAssertEqual(readCounter.readCount, 0) + + // Call read again, read is called on the parent stream. No frames delivered. + childChannel!.read() + XCTAssertEqual(frameRecorder.receivedFrames.count, 1) + XCTAssertEqual(readCounter.readCount, 1) + + // Now deliver a data frame. + var buffer = self.channel.allocator.buffer(capacity: 12) + buffer.write(staticString: "Hello, world!") + let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.byteBuffer(buffer))) + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + + // This frame should have been immediately delivered. No extra call to read. + XCTAssertEqual(frameRecorder.receivedFrames.count, 2) + XCTAssertEqual(readCounter.readCount, 1) + + // Another call to read issues a read to the parent stream. + childChannel!.read() + XCTAssertEqual(frameRecorder.receivedFrames.count, 2) + XCTAssertEqual(readCounter.readCount, 2) + + // Another call to read, this time does not issue a read to the parent stream. + childChannel!.read() + XCTAssertEqual(frameRecorder.receivedFrames.count, 2) + XCTAssertEqual(readCounter.readCount, 2) + + // Delivering two more frames does not cause another call to read, and only one frame + // is delivered. + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) + XCTAssertEqual(frameRecorder.receivedFrames.count, 3) + XCTAssertEqual(readCounter.readCount, 2) + + XCTAssertNoThrow(try self.channel.finish()) + } }