From 419cd4eecec5710867025e94ebebc6dbc5ba1401 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Wed, 5 Jun 2019 12:15:52 -0700 Subject: [PATCH] Drop buffered outbound frames when closing. (#135) Motivation: While having outbound buffers is necessary, it's pretty important to clear then when the connection is closed, or the promise will get leaked. In this case, leaking the promise is usually pretty dang bad, and tends to cause awkward things like crashes. Modifications: - Added hooks to invalidate the CompoundOutboundBuffer. - Called those hooks in handlerRemoved, where there is no reentrancy risk. Result: Less risk of runtime crash. --- Sources/NIOHTTP2/ConcurrentStreamBuffer.swift | 8 ++++ Sources/NIOHTTP2/HTTP2ChannelHandler.swift | 5 +++ .../NIOHTTP2/OutboundFlowControlBuffer.swift | 12 ++++++ Sources/NIOHTTP2/OutboundFrameBuffer.swift | 5 +++ .../CompoundOutboundBufferTest+XCTest.swift | 1 + .../CompoundOutboundBufferTest.swift | 41 +++++++++++++++++++ .../SimpleClientServerTests+XCTest.swift | 1 + .../SimpleClientServerTests.swift | 34 +++++++++++++++ 8 files changed, 107 insertions(+) diff --git a/Sources/NIOHTTP2/ConcurrentStreamBuffer.swift b/Sources/NIOHTTP2/ConcurrentStreamBuffer.swift index 895804d..ffe5e19 100644 --- a/Sources/NIOHTTP2/ConcurrentStreamBuffer.swift +++ b/Sources/NIOHTTP2/ConcurrentStreamBuffer.swift @@ -81,6 +81,14 @@ struct ConcurrentStreamBuffer { return nil } + func invalidateBuffer(reason: ChannelError) { + for buffer in self.bufferedFrames { + for (_, promise) in buffer.frames { + promise?.fail(reason) + } + } + } + mutating func streamCreated(_ streamID: HTTP2StreamID) { // We only care about outbound streams. guard streamID.mayBeInitiatedBy(self.mode) else { diff --git a/Sources/NIOHTTP2/HTTP2ChannelHandler.swift b/Sources/NIOHTTP2/HTTP2ChannelHandler.swift index 87d4fda..607e1f2 100644 --- a/Sources/NIOHTTP2/HTTP2ChannelHandler.swift +++ b/Sources/NIOHTTP2/HTTP2ChannelHandler.swift @@ -112,6 +112,11 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { } } + public func handlerRemoved(context: ChannelHandlerContext) { + // Any frames we're buffering need to be dropped. + self.outboundBuffer.invalidateBuffer() + } + public func channelActive(context: ChannelHandlerContext) { self.writeAndFlushPreamble(context: context) context.fireChannelActive() diff --git a/Sources/NIOHTTP2/OutboundFlowControlBuffer.swift b/Sources/NIOHTTP2/OutboundFlowControlBuffer.swift index f6101fb..d83c279 100644 --- a/Sources/NIOHTTP2/OutboundFlowControlBuffer.swift +++ b/Sources/NIOHTTP2/OutboundFlowControlBuffer.swift @@ -110,6 +110,12 @@ internal struct OutboundFlowControlBuffer { } } + internal func invalidateBuffer(reason: ChannelError) { + for buffer in self.streamDataBuffers.values { + buffer.dataBuffer.failAllWrites(error: reason) + } + } + internal mutating func streamCreated(_ streamID: HTTP2StreamID, initialWindowSize: UInt32) { assert(streamID != .rootStream) @@ -304,6 +310,12 @@ private struct DataBuffer { swap(&buffer, &self.bufferedChunks) return buffer } + + func failAllWrites(error: ChannelError) { + for chunk in self.bufferedChunks { + chunk.1?.fail(error) + } + } } diff --git a/Sources/NIOHTTP2/OutboundFrameBuffer.swift b/Sources/NIOHTTP2/OutboundFrameBuffer.swift index ee27dbe..5237a0a 100644 --- a/Sources/NIOHTTP2/OutboundFrameBuffer.swift +++ b/Sources/NIOHTTP2/OutboundFrameBuffer.swift @@ -176,6 +176,11 @@ extension CompoundOutboundBuffer { return droppedPromises } + func invalidateBuffer() { + self.concurrentStreamsBuffer.invalidateBuffer(reason: ChannelError.ioOnClosedChannel) + self.flowControlBuffer.invalidateBuffer(reason: ChannelError.ioOnClosedChannel) + } + mutating func updateStreamWindow(_ streamID: HTTP2StreamID, newSize: Int32) { self.flowControlBuffer.updateWindowOfStream(streamID, newSize: newSize) } diff --git a/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest+XCTest.swift b/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest+XCTest.swift index 0835238..4377255 100644 --- a/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest+XCTest.swift +++ b/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest+XCTest.swift @@ -35,6 +35,7 @@ extension CompoundOutboundBufferTest { ("testBufferedFrameDrops", testBufferedFrameDrops), ("testRejectsPrioritySelfDependency", testRejectsPrioritySelfDependency), ("testBufferedFlushedFrameBufferingBehindFlowControl", testBufferedFlushedFrameBufferingBehindFlowControl), + ("testFailingAllPromisesOnClose", testFailingAllPromisesOnClose), ] } } diff --git a/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift b/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift index 5bbd782..d0c9559 100644 --- a/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift +++ b/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift @@ -281,6 +281,47 @@ final class CompoundOutboundBufferTest: XCTestCase { } thirdUnbufferedFrame.assertFrameMatches(this: secondData) } + + func testFailingAllPromisesOnClose() { + var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1) + + var results: [Bool?] = Array(repeating: nil as Bool?, count: 4) + var futures: [EventLoopFuture] = [] + + // Write in a bunch of frames, which will get buffered. + for streamID in [HTTP2StreamID(1), HTTP2StreamID(3)] { + let startFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders([])))) + let dataFrame = self.createDataFrame(streamID, byteBufferSize: 50) + + let startPromise = self.loop.makePromise(of: Void.self) + let dataPromise = self.loop.makePromise(of: Void.self) + if streamID == 1 { + XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: startPromise).assertForward()) + startPromise.succeed(()) + buffer.streamCreated(streamID, initialWindowSize: 65535) + } else { + XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: startPromise).assertNothing()) + } + + XCTAssertNoThrow(try buffer.processOutboundFrame(dataFrame, promise: dataPromise).assertNothing()) + futures.append(contentsOf: [startPromise.futureResult, dataPromise.futureResult]) + } + + for (idx, future) in futures.enumerated() { + future.map { + results[idx] = false + }.whenFailure { error in + XCTAssertEqual(error as? ChannelError, ChannelError.ioOnClosedChannel) + results[idx] = true + } + } + + XCTAssertEqual(results, [false, nil, nil, nil]) + + // Now, invalidate the buffer. + buffer.invalidateBuffer() + XCTAssertEqual(results, [false, true, true, true]) + } } diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift b/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift index 917de42..7f72691 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift @@ -58,6 +58,7 @@ extension SimpleClientServerTests { ("testInvalidRequestHeaderBlockAllowsRstStream", testInvalidRequestHeaderBlockAllowsRstStream), ("testClientConnectionErrorCorrectlyReported", testClientConnectionErrorCorrectlyReported), ("testChangingMaxConcurrentStreams", testChangingMaxConcurrentStreams), + ("testFailsPromisesForBufferedWrites", testFailsPromisesForBufferedWrites), ] } } diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift index 15986b2..0565844 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift @@ -1360,4 +1360,38 @@ class SimpleClientServerTests: XCTestCase { XCTAssertNoThrow(try self.clientChannel.finish()) XCTAssertNoThrow(try self.serverChannel.finish()) } + + func testFailsPromisesForBufferedWrites() throws { + // Begin by getting the connection up. + try self.basicHTTP2Connection() + + // We're going to queue some frames in the client, but not flush them. The HEADERS frame will pass + // right through, but the DATA ones won't. + let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let clientStreamID = HTTP2StreamID(1) + let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers, endStream: false))) + + var promiseResults: [Bool?] = Array(repeatElement(nil as Bool?, count: 5)) + self.clientChannel.write(reqFrame, promise: nil) + + let bodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) + for index in promiseResults.indices { + self.clientChannel.write(bodyFrame).map { + promiseResults[index] = true + }.whenFailure { + XCTAssertEqual($0 as? ChannelError, ChannelError.ioOnClosedChannel) + promiseResults[index] = false + } + } + + XCTAssertEqual(promiseResults, [nil, nil, nil, nil, nil]) + + // Close the channel. + self.clientChannel.close(promise: nil) + self.clientChannel.embeddedEventLoop.run() + + // The promises should be succeeded. + XCTAssertEqual(promiseResults, [false, false, false, false, false]) + XCTAssertNoThrow(try self.serverChannel.finish()) + } }