Support buffered writes

This commit is contained in:
Cory Benfield committed 2018-05-16 17:53:26 +01:00
1 parent 5c5987e6ad
commit bbcb593a6d
2 files changed
+168 -2

No files matched your search

+36 -2
View File
@@ -182,6 +182,12 @@ final class HTTP2StreamChannel: Channel, ChannelCore {
/// channel up.
private var pendingReads: CircularBuffer<HTTP2Frame> = CircularBuffer(initialRingCapacity: 8)
/// 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
/// stream is flushed, at which time we deliver them all. This buffer holds the pending ones.
private var pendingWrites: MarkedCircularBuffer<(HTTP2Frame, EventLoopPromise<Void>?)> = MarkedCircularBuffer(initialRingCapacity: 8)
public func register0(promise: EventLoopPromise<Void>?) {
fatalError("not implemented \(#function)")
}
@@ -195,11 +201,21 @@ final class HTTP2StreamChannel: Channel, ChannelCore {
}
public func write0(_ data: NIOAny, promise: EventLoopPromise<Void>?) {
guard self.state != .closed else {
promise?.fail(error: ChannelError.ioOnClosedChannel)
return
}
let frame = self.unwrapData(data, as: HTTP2Frame.self)
self.receiveOutboundFrame(frame, promise: promise)
self.pendingWrites.append((frame, promise))
}
public func flush0() {
guard self.state != .closed else {
return
}
self.pendingWrites.mark()
self.deliverPendingWrites()
self.parent?.flush()
}
@@ -262,6 +278,7 @@ final class HTTP2StreamChannel: Channel, ChannelCore {
}
self.state.completeClosing()
self.dropPendingReads()
self.failPendingWrites(error: ChannelError.eof)
if let promise = self.pendingClosePromise {
self.pendingClosePromise = nil
promise.succeed(result: ())
@@ -276,6 +293,7 @@ final class HTTP2StreamChannel: Channel, ChannelCore {
}
self.state.completeClosing()
self.dropPendingReads()
self.failPendingWrites(error: error)
if let promise = self.pendingClosePromise {
self.pendingClosePromise = nil
promise.fail(error: error)
@@ -286,7 +304,7 @@ final class HTTP2StreamChannel: Channel, ChannelCore {
}
}
// MARK:- Functions used to manage pending reads.
// MARK:- Functions used to manage pending reads and writes.
private extension HTTP2StreamChannel {
/// Drop all pending reads.
private func dropPendingReads() {
@@ -302,6 +320,22 @@ private extension HTTP2StreamChannel {
}
self.pipeline.fireChannelReadComplete()
}
/// Delivers all pending flushed writes to the parent channel.
private func deliverPendingWrites() {
while self.pendingWrites.hasMark() {
let write = self.pendingWrites.removeFirst()
self.receiveOutboundFrame(write.0, promise: write.1)
}
}
/// Fails all pending writes with the given error.
private func failPendingWrites(error: Error) {
assert(self.state == .closed)
while self.pendingWrites.count > 0 {
self.pendingWrites.removeFirst().1?.fail(error: error)
}
}
}
// MARK:- Functions used to communicate between the `HTTP2StreamMultiplexer` and the `HTTP2StreamChannel`.
@@ -560,4 +560,136 @@ final class HTTP2StreamMultiplexerTests: XCTestCase {
XCTAssertNoThrow(try self.channel.finish())
}
func testFlushingOneChannelDoesntFlushThemAll() throws {
let writeTracker = FrameWriteRecorder()
var channels: [Channel] = []
let multiplexer = HTTP2StreamMultiplexer { (channel, _) in
channels.append(channel)
return channel.eventLoop.newSucceededFuture(result: ())
}
XCTAssertNoThrow(try self.channel.pipeline.add(handler: writeTracker).wait())
XCTAssertNoThrow(try self.channel.pipeline.add(handler: multiplexer).wait())
// Let's open two streams.
let firstStreamID = HTTP2StreamID(knownID: 1)
let secondStreamID = HTTP2StreamID(knownID: 3)
for streamID in [firstStreamID, secondStreamID] {
var frame = HTTP2Frame(streamID: streamID, payload: .headers(HTTPHeaders()))
frame.endStream = true
XCTAssertNoThrow(try self.channel.writeInbound(frame))
}
XCTAssertEqual(channels.count, 2)
// We will now write a headers frame to each channel. Neither frame should be written to the connection. To verify this
// we will flush the parent channel.
for (idx, streamID) in [firstStreamID, secondStreamID].enumerated() {
let frame = HTTP2Frame(streamID: streamID, payload: .headers(HTTPHeaders()))
channels[idx].write(frame, promise: nil)
}
self.channel.flush()
XCTAssertEqual(writeTracker.flushedWrites.count, 0)
// Now we're going to flush only the first child channel. This should cause one flushed write.
channels[0].flush()
XCTAssertEqual(writeTracker.flushedWrites.count, 1)
// Now the other.
channels[1].flush()
XCTAssertEqual(writeTracker.flushedWrites.count, 2)
XCTAssertNoThrow(try self.channel.finish())
}
func testUnflushedWritesFailOnClose() throws {
var childChannel: Channel? = nil
let multiplexer = HTTP2StreamMultiplexer { (channel, _) in
childChannel = channel
return channel.eventLoop.newSucceededFuture(result: ())
}
XCTAssertNoThrow(try self.channel.pipeline.add(handler: multiplexer).wait())
// Let's open a stream.
let streamID = HTTP2StreamID(knownID: 1)
var frame = HTTP2Frame(streamID: streamID, payload: .headers(HTTPHeaders()))
frame.endStream = true
XCTAssertNoThrow(try self.channel.writeInbound(frame))
XCTAssertNotNil(channel)
// We will now write a headers frame to the channel, but don't flush it.
var writeError: Error? = nil
let responseFrame = HTTP2Frame(streamID: streamID, payload: .headers(HTTPHeaders()))
childChannel!.write(responseFrame).whenFailure {
writeError = $0
}
XCTAssertNil(writeError)
// Now we're going to deliver a normal close to the stream.
let userEvent = StreamClosedEvent(streamID: streamID, reason: nil)
self.channel.pipeline.fireUserInboundEventTriggered(userEvent)
XCTAssertEqual(writeError as? ChannelError, ChannelError.eof)
XCTAssertNoThrow(try self.channel.finish())
}
func testUnflushedWritesFailOnError() throws {
var childChannel: Channel? = nil
let multiplexer = HTTP2StreamMultiplexer { (channel, _) in
childChannel = channel
return channel.eventLoop.newSucceededFuture(result: ())
}
XCTAssertNoThrow(try self.channel.pipeline.add(handler: multiplexer).wait())
// Let's open a stream.
let streamID = HTTP2StreamID(knownID: 1)
var frame = HTTP2Frame(streamID: streamID, payload: .headers(HTTPHeaders()))
frame.endStream = true
XCTAssertNoThrow(try self.channel.writeInbound(frame))
XCTAssertNotNil(channel)
// We will now write a headers frame to the channel, but don't flush it.
var writeError: Error? = nil
let responseFrame = HTTP2Frame(streamID: streamID, payload: .headers(HTTPHeaders()))
childChannel!.write(responseFrame).whenFailure {
writeError = $0
}
XCTAssertNil(writeError)
// Now we're going to deliver a normal close to the stream.
let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel)
self.channel.pipeline.fireUserInboundEventTriggered(userEvent)
XCTAssertEqual(writeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .cancel))
XCTAssertNoThrow(try self.channel.finish())
}
func testWritesFailOnClosedStreamChannels() throws {
var childChannel: Channel? = nil
let multiplexer = HTTP2StreamMultiplexer { (channel, _) in
childChannel = channel
return channel.eventLoop.newSucceededFuture(result: ())
}
XCTAssertNoThrow(try self.channel.pipeline.add(handler: multiplexer).wait())
// Let's open a stream.
let streamID = HTTP2StreamID(knownID: 1)
var frame = HTTP2Frame(streamID: streamID, payload: .headers(HTTPHeaders()))
frame.endStream = true
XCTAssertNoThrow(try self.channel.writeInbound(frame))
XCTAssertNotNil(channel)
// Now let's close it.
let userEvent = StreamClosedEvent(streamID: streamID, reason: nil)
self.channel.pipeline.fireUserInboundEventTriggered(userEvent)
// We will now write a headers frame to the channel. This should fail immediately.
var writeError: Error? = nil
let responseFrame = HTTP2Frame(streamID: streamID, payload: .headers(HTTPHeaders()))
childChannel!.write(responseFrame).whenFailure {
writeError = $0
}
XCTAssertEqual(writeError as? ChannelError, ChannelError.ioOnClosedChannel)
XCTAssertNoThrow(try self.channel.finish())
}
}