diff --git a/Sources/NIO/Channel.swift b/Sources/NIO/Channel.swift index 3e332120e..8615b5b9b 100644 --- a/Sources/NIO/Channel.swift +++ b/Sources/NIO/Channel.swift @@ -39,6 +39,10 @@ private func doPendingWriteVectorOperation(pending: MarkedCircularBuffer>, _ fn: (UnsafeBufferPointer) throws -> IOResult) throws -> IOResult { assert(count <= pending.count, "requested to write \(count) pending writes but only \(pending.count) available") + assert(iovecs.count >= Socket.writevLimit, "Insufficiently sized buffer for a maximal writev") + + // Clamp the number of writes we're willing to issue to the limit for writev. + let count = min(count, Socket.writevLimit) // the numbers of storage refs that we need to decrease later. var c = 0 diff --git a/Tests/NIOTests/ChannelTests+XCTest.swift b/Tests/NIOTests/ChannelTests+XCTest.swift index 67a8b4919..48e4a9906 100644 --- a/Tests/NIOTests/ChannelTests+XCTest.swift +++ b/Tests/NIOTests/ChannelTests+XCTest.swift @@ -27,6 +27,7 @@ extension ChannelTests { static var allTests : [(String, (ChannelTests) -> () throws -> Void)] { return [ ("testBasicLifecycle", testBasicLifecycle), + ("testManyManyWrites", testManyManyWrites), ] } } diff --git a/Tests/NIOTests/ChannelTests.swift b/Tests/NIOTests/ChannelTests.swift index 7d5cb8f71..62005bdf8 100644 --- a/Tests/NIOTests/ChannelTests.swift +++ b/Tests/NIOTests/ChannelTests.swift @@ -13,7 +13,7 @@ //===----------------------------------------------------------------------===// import XCTest -import NIO +@testable import NIO class ChannelLifecycleHandler: ChannelInboundHandler { @@ -102,4 +102,30 @@ public class ChannelTests: XCTestCase { XCTAssertEqual(serverLifecycleHandler.stateHistory, [.unregistered, .inactive, .active, .inactive, .unregistered]) }.wait() } + + func testManyManyWrites() throws { + let group = try MultiThreadedEventLoopGroup(numThreads: 1) + defer { + try! group.syncShutdownGracefully() + } + + let serverChannel = try ServerBootstrap(group: group) + .option(option: ChannelOptions.Socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) + .bind(to: "127.0.0.1", on: 0).wait() + + let clientChannel = try ClientBootstrap(group: group) + .connect(to: serverChannel.localAddress!).wait() + + // We're going to try to write loads, and loads, and loads of data. In this case, one more + // write than the iovecs max. + for _ in 0...Socket.writevLimit { + var buffer = clientChannel.allocator.buffer(capacity: 1) + buffer.write(string: "a") + clientChannel.write(data: NIOAny(buffer), promise: nil) + } + try clientChannel.flush().wait() + + // Start shutting stuff down. + try clientChannel.close().wait() + } }