simplify channel writes

Motivation:

Channel writes are a complex matter and it was even more
complex when `FileRegion` and `ByteBuffer` were completely
different kinds of objects. Now that they're more in line we can
simplify a lot of things.

Modifications:

Rewrote the inner layers of channel writes to make them more readable
and hopefully more correct.

Result:

hopefully fewer bugs.
This commit is contained in:
Johannes Weiss committed 2018-02-15 14:07:57 +00:00
1 parent 68f20f84fd
commit be1de1c433
7 files changed
+196 -233

No files matched your search

+3 -2
View File
@@ -97,8 +97,9 @@ public enum AutoReadOption: ChannelOption {
case const(())
}
/// `WriteSpinOption` allows to configure the number of write calls to do before consider the `Channel` as non-writable and give up until it
/// becomes writable again.
/// `WriteSpinOption` allows users to configure the number of repetitions of a only partially successful write call before considering the `Channel` not writable.
/// Setting this option to `0` means that we only issue one write call and if that call does not write all the bytes,
/// we consider the `Channel` not writable.
public enum WriteSpinOption: ChannelOption {
public typealias AssociatedValueType = ()
public typealias OptionType = UInt
@@ -13,6 +13,8 @@
//===----------------------------------------------------------------------===//
import NIOConcurrencyHelpers
internal typealias WriteResult = SingleWriteOperationResult
private struct PendingDatagramWrite {
var data: ByteBuffer
var promise: EventLoopPromise<Void>?
@@ -562,7 +564,7 @@ final class PendingDatagramWritesManager {
/// - singleWriteOperation: An operation that writes a single, contiguous array of bytes (usually `sendto`).
private func triggerSingleWrite(singleWriteOperation: (UnsafeRawBufferPointer, UnsafePointer<sockaddr>, socklen_t) throws -> IOResult<Int>) rethrows -> WriteResult {
guard self.state.isFlushPending && !self.state.isEmpty else {
return .nothingToBeWritten
return .writtenCompletely
}
for _ in 0..<writeSpinCount {
@@ -601,7 +603,7 @@ final class PendingDatagramWritesManager {
"vector write called in state flush pending: \(self.state.isFlushPending), empty: \(self.state.isEmpty)")
for _ in 0..<writeSpinCount {
if closed {
return .closed
return .writtenCompletely
}
switch self.didWrite(try doPendingDatagramWriteVectorOperation(pending: self.state,
iovecs: self.iovecs,
+57 -76
View File
@@ -37,12 +37,6 @@ private func doPendingWriteVectorOperation(pending: PendingStreamWritesState,
// the numbers of storage refs that we need to decrease later.
var numberOfUsedStorageSlots = 0
// we need to track if we stopped collecting more buffer because of a writev limit or not.
// if we hit a limit we should indicate that we intended to write at least one more buffer so that `didWrite`
// returns `.writtenPartially`.
var hitLimit = pending.flushedChunks > Socket.writevLimitIOVectors
var toWrite: Int = 0
loop: for i in 0..<count {
@@ -51,7 +45,6 @@ private func doPendingWriteVectorOperation(pending: PendingStreamWritesState,
case .byteBuffer(let buffer):
// Must not write more than Int32.max in one go.
guard (numberOfUsedStorageSlots == 0) || (Socket.writevLimitBytes - toWrite >= buffer.readableBytes) else {
hitLimit = true
break loop
}
let toWriteForThisBuffer = min(Socket.writevLimitBytes, buffer.readableBytes)
@@ -64,7 +57,6 @@ private func doPendingWriteVectorOperation(pending: PendingStreamWritesState,
numberOfUsedStorageSlots += 1
case .fileRegion(_):
// We found a FileRegion so stop collecting
hitLimit = false
break loop
}
}
@@ -75,25 +67,29 @@ private func doPendingWriteVectorOperation(pending: PendingStreamWritesState,
}
let result = try fn(UnsafeBufferPointer(start: iovecs.baseAddress!, count: numberOfUsedStorageSlots))
/* if we hit a limit, we really wanted to write more than we have so the caller should retry us */
return (numberOfUsedStorageSlots + (hitLimit ? 1 : 0), result)
return (numberOfUsedStorageSlots, result)
}
/// The high-level result of a write operation.
/* private but tests */ enum WriteResult {
/// The result of a single write operation, usually `write`, `sendfile` or `writev`.
internal enum SingleWriteOperationResult {
/// Wrote everything asked.
case writtenCompletely
/// Wrote some portion of what was asked.
case writtenPartially
/// There was nothing to be written.
case nothingToBeWritten
/// Could not write as doing that would have blocked.
case wouldBlock
}
/// Could not write as the underlying descriptor is closed.
case closed
/// The result of trying to write all the outstanding flushed data. That naturally includes all `ByteBuffer`s and
/// `FileRegions` and the individual writes have potentially been retried (see `WriteSpinOption`).
internal enum OverallWriteResult {
/// Wrote all the data that was flushed. When receiving this result, we can unsubscribe from 'writable' notification.
case writtenCompletely
/// Could not write everything. Before attempting further writes the eventing system should send a 'writable' notification.
case couldNotWriteEverything
}
/// This holds the states of the currently pending stream writes. The core is a `MarkedCircularBuffer` which holds all the
@@ -214,8 +210,8 @@ private struct PendingStreamWritesState {
///
/// - parameters:
/// - writeResult: The result of the write operation.
/// - returns: A closure that the caller _needs_ to run which will fulfill the promises of the writes and a `WriteResult` which indicates if we could write everything or not.
public mutating func didWrite(itemCount: Int, result writeResult: IOResult<Int>) -> (() -> Void, WriteResult) {
/// - returns: A closure that the caller _needs_ to run which will fulfill the promises of the writes and a `SingleWriteOperationResult` which indicates if we could write everything or not.
public mutating func didWrite(itemCount: Int, result writeResult: IOResult<Int>) -> (() -> Void, SingleWriteOperationResult) {
var promises: [EventLoopPromise<()>] = []
let fulfillPromises = { promises.forEach { $0.succeed(result: ()) } }
@@ -330,16 +326,29 @@ final class PendingStreamWritesManager {
/// - singleWriteOperation: An operation that writes a single, contiguous array of bytes (usually `write`).
/// - vectorWriteOperation: An operation that writes multiple contiguous arrays of bytes (usually `writev`).
/// - fileWriteOperation: An operation that writes a region of a file descriptor.
/// - returns: The `WriteResult` and whether the `Channel` is now writable.
/// - returns: The `SingleWriteOperationResult` and whether the `Channel` is now writable.
func triggerAppropriateWriteOperation(singleWriteOperation: (UnsafeRawBufferPointer) throws -> IOResult<Int>,
vectorWriteOperation: (UnsafeBufferPointer<IOVector>) throws -> IOResult<Int>,
fileWriteOperation: (CInt, Int, Int) throws -> IOResult<Int>) throws -> (writeResult: WriteResult, writable: Bool) {
fileWriteOperation: (CInt, Int, Int) throws -> IOResult<Int>) throws -> (writeResult: OverallWriteResult, writable: Bool) {
let wasWritable = writable.load()
let result: WriteResult
if self.state.hasMultipleFlushedByteBuffers {
result = try triggerVectorWrite(vectorWriteOperation: vectorWriteOperation)
} else {
result = try triggerSingleWrite(singleWriteOperation: singleWriteOperation, fileWriteOperation: fileWriteOperation)
var result: OverallWriteResult = .couldNotWriteEverything
writeSpinLoop: for _ in 0...writeSpinCount {
var oneResult: SingleWriteOperationResult
repeat {
guard !self.closed && self.isFlushPending else {
result = .writtenCompletely
break
}
if self.state.hasMultipleFlushedByteBuffers {
oneResult = try triggerVectorWrite(vectorWriteOperation: vectorWriteOperation)
} else {
oneResult = try triggerSingleWrite(singleWriteOperation: singleWriteOperation, fileWriteOperation: fileWriteOperation)
}
if oneResult == .wouldBlock {
break writeSpinLoop
}
} while oneResult == .writtenCompletely
}
if !wasWritable {
@@ -355,7 +364,7 @@ final class PendingStreamWritesManager {
/// - parameters:
/// - itemCount: The number of items we tried to write.
/// - result: The result of the write operation.
private func didWrite(itemCount: Int, result: IOResult<Int>) -> WriteResult {
private func didWrite(itemCount: Int, result: IOResult<Int>) -> SingleWriteOperationResult {
let (fulfillPromises, result) = self.state.didWrite(itemCount: itemCount, result: result)
if self.state.bytes < waterMark.lowerBound {
@@ -372,65 +381,37 @@ final class PendingStreamWritesManager {
/// - singleWriteOperation: An operation that writes a single, contiguous array of bytes (usually `write`).
/// - fileWriteOperation: An operation that writes a region of a file descriptor.
private func triggerSingleWrite(singleWriteOperation: (UnsafeRawBufferPointer) throws -> IOResult<Int>,
fileWriteOperation: (CInt, Int, Int) throws -> IOResult<Int>) throws -> WriteResult {
if self.state.isFlushPending && !self.state.isEmpty {
for _ in 0..<writeSpinCount {
assert(!closed,
"Channel got closed during the spinning of a single write operation which should be impossible as we don't call out")
let pending = self.state[0]
switch pending.data {
case .byteBuffer(let buffer):
switch self.didWrite(itemCount: 1, result: try buffer.withUnsafeReadableBytes(singleWriteOperation)) {
case .writtenPartially:
continue
case let other:
return other
}
case .fileRegion(let file):
func with(_ fileWriteOperation: (CInt, Int, Int) throws -> IOResult<Int>) throws -> IOResult<Int> {
let readerIndex = file.readerIndex
let endIndex = file.endIndex
return try file.fileHandle.withDescriptor { fd in
return try fileWriteOperation(fd, readerIndex, endIndex)
}
}
switch self.didWrite(itemCount: 1, result: try with(fileWriteOperation)) {
case .writtenPartially:
continue
case let other:
return other
}
fileWriteOperation: (CInt, Int, Int) throws -> IOResult<Int>) throws -> SingleWriteOperationResult {
assert(self.state.isFlushPending && !self.state.isEmpty && !self.closed,
"single write called in illegal state: flush pending: \(self.state.isFlushPending), empty: \(self.state.isEmpty), closed: \(self.closed)")
switch self.state[0].data {
case .byteBuffer(let buffer):
return self.didWrite(itemCount: 1, result: try buffer.withUnsafeReadableBytes(singleWriteOperation))
case .fileRegion(let file):
func with(_ fileWriteOperation: (CInt, Int, Int) throws -> IOResult<Int>) throws -> IOResult<Int> {
let readerIndex = file.readerIndex
let endIndex = file.endIndex
return try file.fileHandle.withDescriptor { fd in
return try fileWriteOperation(fd, readerIndex, endIndex)
}
}
return .writtenPartially
return self.didWrite(itemCount: 1, result: try with(fileWriteOperation))
}
return .nothingToBeWritten
}
/// Trigger a vector write operation. In other words: Write multiple contiguous arrays of bytes.
///
/// - parameters:
/// - vectorWriteOperation: The vector write operation to use. Usually `writev`.
private func triggerVectorWrite(vectorWriteOperation: (UnsafeBufferPointer<IOVector>) throws -> IOResult<Int>) throws -> WriteResult {
assert(self.state.isFlushPending && !self.state.isEmpty,
"vector write called in state flush pending: \(self.state.isFlushPending), empty: \(self.state.isEmpty)")
for _ in 0..<writeSpinCount {
if closed {
return .closed
}
let (itemCount, result) = try doPendingWriteVectorOperation(pending: self.state,
iovecs: self.iovecs,
storageRefs: self.storageRefs,
vectorWriteOperation)
switch self.didWrite(itemCount: itemCount, result: result) {
case .writtenPartially:
continue
case let other:
return other
}
}
return .writtenPartially
private func triggerVectorWrite(vectorWriteOperation: (UnsafeBufferPointer<IOVector>) throws -> IOResult<Int>) throws -> SingleWriteOperationResult {
assert(self.state.isFlushPending && !self.state.isEmpty && !self.closed,
"vector write called in illegal state: flush pending: \(self.state.isFlushPending), empty: \(self.state.isEmpty), closed: \(self.closed)")
let (itemCount, result) = try doPendingWriteVectorOperation(pending: self.state,
iovecs: self.iovecs,
storageRefs: self.storageRefs,
vectorWriteOperation)
return self.didWrite(itemCount: itemCount, result: result)
}
/// Fail all the outstanding writes. This is useful if for example the `Channel` is closed.
+32 -45
View File
@@ -15,10 +15,10 @@ import NIOConcurrencyHelpers
private extension ByteBuffer {
mutating func withMutableWritePointer(body: (UnsafeMutablePointer<UInt8>, Int) throws -> IOResult<Int>) rethrows -> IOResult<Int> {
var writeResult: IOResult<Int>!
var singleResult: IOResult<Int>!
_ = try self.writeWithUnsafeMutableBytes { ptr in
let localWriteResult = try body(ptr.baseAddress!.assumingMemoryBound(to: UInt8.self), ptr.count)
writeResult = localWriteResult
singleResult = localWriteResult
switch localWriteResult {
case .processed(let written):
return written
@@ -26,7 +26,7 @@ private extension ByteBuffer {
return written
}
}
return writeResult
return singleResult
}
}
@@ -743,44 +743,38 @@ final class SocketChannel: BaseSocketChannel<Socket> {
return result
}
private func writeToSocket(pendingWrites: PendingStreamWritesManager) throws -> WriteResult {
repeat {
let result = try pendingWrites.triggerAppropriateWriteOperation(singleWriteOperation: { ptr in
guard ptr.count > 0 else {
private func writeToSocket(pendingWrites: PendingStreamWritesManager) throws -> OverallWriteResult {
let result = try pendingWrites.triggerAppropriateWriteOperation(singleWriteOperation: { ptr in
guard ptr.count > 0 else {
// No need to call write if the buffer is empty.
return .processed(0)
}
// normal write
return try self.socket.write(pointer: ptr.baseAddress!.assumingMemoryBound(to: UInt8.self), size: ptr.count)
}, vectorWriteOperation: { ptrs in
switch ptrs.count {
case 0:
// No need to call write if the buffer is empty.
return .processed(0)
case 1:
let p = ptrs[0]
guard p.iov_len > 0 else {
// No need to call write if the buffer is empty.
return .processed(0)
}
// normal write
return try self.socket.write(pointer: ptr.baseAddress!.assumingMemoryBound(to: UInt8.self), size: ptr.count)
}, vectorWriteOperation: { ptrs in
switch ptrs.count {
case 0:
// No need to call write if the buffer is empty.
return .processed(0)
case 1:
let p = ptrs[0]
guard p.iov_len > 0 else {
// No need to call write if the buffer is empty.
return .processed(0)
}
return try self.socket.write(pointer: p.iov_base.assumingMemoryBound(to: UInt8.self), size: p.iov_len)
default:
// Gathering write
return try self.socket.writev(iovecs: ptrs)
}
}, fileWriteOperation: { descriptor, index, endIndex in
return try self.socket.sendFile(fd: descriptor, offset: index, count: endIndex - index)
})
if result.writable {
// writable again
self.pipeline.fireChannelWritabilityChanged0()
return try self.socket.write(pointer: p.iov_base.assumingMemoryBound(to: UInt8.self), size: p.iov_len)
default:
// Gathering write
return try self.socket.writev(iovecs: ptrs)
}
if result.writeResult == .writtenCompletely && pendingWrites.isFlushPending {
// there are more buffers to process, so continue
continue
}
return result.writeResult
} while true
}, fileWriteOperation: { descriptor, index, endIndex in
return try self.socket.sendFile(fd: descriptor, offset: index, count: endIndex - index)
})
if result.writable {
// writable again
self.pipeline.fireChannelWritabilityChanged0()
}
return result.writeResult
}
override fileprivate func connectSocket(to address: SocketAddress) throws -> Bool {
@@ -913,17 +907,10 @@ final class SocketChannel: BaseSocketChannel<Socket> {
while !closed {
do {
switch try self.writeToSocket(pendingWrites: pendingWrites) {
case .writtenPartially:
// Could not write the next buffer(s) completely
return false
case .wouldBlock:
case .couldNotWriteEverything:
return false
case .writtenCompletely:
return true
case .closed:
return true
case .nothingToBeWritten:
return true
}
} catch let err {
// If there is a write error we should try drain the inbound before closing the socket as there may be some data pending.
+1
View File
@@ -35,6 +35,7 @@ extension ChannelTests {
("testPendingWritesWorkWithPartialWrites", testPendingWritesWorkWithPartialWrites),
("testPendingWritesSpinCountWorksForSingleWrites", testPendingWritesSpinCountWorksForSingleWrites),
("testPendingWritesSpinCountWorksForVectorWrites", testPendingWritesSpinCountWorksForVectorWrites),
("testPendingWritesCompleteWritesDontConsumeWriteSpinCount", testPendingWritesCompleteWritesDontConsumeWriteSpinCount),
("testPendingWritesCancellationWorksCorrectly", testPendingWritesCancellationWorksCorrectly),
("testPendingWritesNoMoreThanWritevLimitIsWritten", testPendingWritesNoMoreThanWritevLimitIsWritten),
("testPendingWritesNoMoreThanWritevLimitIsWrittenInOneMassiveChunk", testPendingWritesNoMoreThanWritevLimitIsWrittenInOneMassiveChunk),
+97 -106
View File
@@ -250,7 +250,7 @@ public class ChannelTests: XCTestCase {
returns: [IOResult<Int>],
promiseStates: [[Bool]],
file: StaticString = #file,
line: UInt = #line) throws -> WriteResult {
line: UInt = #line) throws -> OverallWriteResult {
var everythingState = 0
var singleState = 0
var multiState = 0
@@ -380,12 +380,12 @@ public class ChannelTests: XCTestCase {
_ = pwm.add(data: .byteBuffer(buffer), promise: ps[1])
var result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
expectedSingleWritabilities: [0],
expectedVectorWritabilities: nil,
expectedFileWritabilities: nil,
returns: [.processed(0)],
promiseStates: [[true, false]])
promises: ps,
expectedSingleWritabilities: [0],
expectedVectorWritabilities: nil,
expectedFileWritabilities: nil,
returns: [.processed(0)],
promiseStates: [[true, false]])
XCTAssertFalse(pwm.isEmpty)
XCTAssertFalse(pwm.isFlushPending)
@@ -398,7 +398,7 @@ public class ChannelTests: XCTestCase {
expectedFileWritabilities: nil,
returns: [],
promiseStates: [[true, false]])
XCTAssertEqual(WriteResult.nothingToBeWritten, result)
XCTAssertEqual(OverallWriteResult.writtenCompletely, result)
pwm.markFlushCheckpoint(promise: nil)
@@ -409,7 +409,7 @@ public class ChannelTests: XCTestCase {
expectedFileWritabilities: nil,
returns: [.processed(0)],
promiseStates: [[true, true]])
XCTAssertEqual(WriteResult.writtenCompletely, result)
XCTAssertEqual(OverallWriteResult.writtenCompletely, result)
}
}
@@ -435,7 +435,7 @@ public class ChannelTests: XCTestCase {
expectedFileWritabilities: nil,
returns: [.processed(8)],
promiseStates: [[true, true, false]])
XCTAssertEqual(WriteResult.writtenCompletely, result)
XCTAssertEqual(.writtenCompletely, result)
pwm.markFlushCheckpoint(promise: nil)
@@ -446,7 +446,7 @@ public class ChannelTests: XCTestCase {
expectedFileWritabilities: nil,
returns: [.processed(0)],
promiseStates: [[true, true, true]])
XCTAssertEqual(WriteResult.writtenCompletely, result)
XCTAssertEqual(.writtenCompletely, result)
}
}
@@ -473,7 +473,7 @@ public class ChannelTests: XCTestCase {
returns: [.processed(1), .wouldBlock(0)],
promiseStates: [[false, false, false, false], [false, false, false, false]])
XCTAssertEqual(WriteResult.wouldBlock, result)
XCTAssertEqual(.couldNotWriteEverything, result)
result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
expectedSingleWritabilities: nil,
@@ -483,7 +483,7 @@ public class ChannelTests: XCTestCase {
promiseStates: [[true, true, false, false], [true, true, false, false]]
)
XCTAssertEqual(WriteResult.wouldBlock, result)
XCTAssertEqual(.couldNotWriteEverything, result)
result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
@@ -492,7 +492,7 @@ public class ChannelTests: XCTestCase {
expectedFileWritabilities: nil,
returns: [.processed(8)],
promiseStates: [[true, true, true, true], [true, true, true, true]])
XCTAssertEqual(WriteResult.writtenCompletely, result)
XCTAssertEqual(.writtenCompletely, result)
}
}
@@ -503,7 +503,7 @@ public class ChannelTests: XCTestCase {
var buffer = alloc.buffer(capacity: 12)
try withPendingStreamWritesManager { pwm in
let numberOfBytes = Int(pwm.writeSpinCount + 1 /* so one byte remains at the end */)
let numberOfBytes = Int(1 /* first write */ + pwm.writeSpinCount /* the spins */ + 1 /* so one byte remains at the end */)
buffer.clear()
buffer.write(bytes: Array<UInt8>(repeating: 0xff, count: numberOfBytes))
let ps: [EventLoopPromise<()>] = (0..<1).map { _ in el.newPromise() }
@@ -520,7 +520,7 @@ public class ChannelTests: XCTestCase {
expectedFileWritabilities: nil,
returns: Array(repeating: .processed(1), count: numberOfBytes),
promiseStates: Array(repeating: [false], count: numberOfBytes))
XCTAssertEqual(.writtenPartially, result)
XCTAssertEqual(.couldNotWriteEverything, result)
/* we'll now write the one last byte and assert that all the writes are complete */
result = try assertExpectedWritability(pendingWritesManager: pwm,
@@ -541,7 +541,7 @@ public class ChannelTests: XCTestCase {
var buffer = alloc.buffer(capacity: 12)
try withPendingStreamWritesManager { pwm in
let numberOfBytes = Int(pwm.writeSpinCount + 1 /* so one byte remains at the end */)
let numberOfBytes = Int(1 /* first write */ + pwm.writeSpinCount /* the spins */ + 1 /* so one byte remains at the end */)
buffer.clear()
buffer.write(bytes: [0xff] as [UInt8])
let ps: [EventLoopPromise<()>] = (0..<numberOfBytes).map { _ in
@@ -575,7 +575,7 @@ public class ChannelTests: XCTestCase {
expectedFileWritabilities: nil,
returns: Array(repeating: .processed(1), count: numberOfBytes),
promiseStates: expectedPromiseStates)
XCTAssertEqual(.writtenPartially, result)
XCTAssertEqual(.couldNotWriteEverything, result)
/* we'll now write the one last byte and assert that all the writes are complete */
result = try assertExpectedWritability(pendingWritesManager: pwm,
@@ -589,6 +589,45 @@ public class ChannelTests: XCTestCase {
}
}
/// Tests that the spin count works for one long buffer if small bits are written one by one.
func testPendingWritesCompleteWritesDontConsumeWriteSpinCount() throws {
let el = EmbeddedEventLoop()
let alloc = ByteBufferAllocator()
var buffer = alloc.buffer(capacity: 12)
try withPendingStreamWritesManager { pwm in
let numberOfWrites = Int(1 /* first write */ + pwm.writeSpinCount /* the spins */ + 1 /* so one byte remains at the end */)
buffer.clear()
buffer.write(bytes: Array<UInt8>(repeating: 0xff, count: 1))
let handle = FileHandle(descriptor: -1)
defer {
/* fake file handle, so don't actually close */
XCTAssertNoThrow(try handle.takeDescriptorOwnership())
}
let fileRegion = FileRegion(fileHandle: handle, readerIndex: 0, endIndex: 1)
let ps: [EventLoopPromise<()>] = (0...numberOfWrites).map { _ in el.newPromise() }
(0..<numberOfWrites).forEach { i in
_ = pwm.add(data: i % 2 == 0 ? .byteBuffer(buffer) : .fileRegion(fileRegion), promise: ps[i])
}
pwm.markFlushCheckpoint(promise: ps[numberOfWrites])
let expectedPromiseStates = Array((1...numberOfWrites).reversed()).map { n in
Array(repeating: true, count: numberOfWrites - n + 1) + Array(repeating: false, count: n - 1) + [n - 1 == 0 ? true : false]
}
/* below, we'll write 1 byte at a time. So the number of bytes offered should decrease by one.
The write operation should be repeated until we did it 1 + spin count times and then return `.writtenPartially`.
After that, one byte will remain */
let result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
expectedSingleWritabilities: Array(repeating: 1, count: numberOfWrites / 2),
expectedVectorWritabilities: nil,
expectedFileWritabilities: Array(repeating: (0, 1), count: numberOfWrites / 2),
returns: Array(repeating: .processed(1), count: numberOfWrites),
promiseStates: expectedPromiseStates)
XCTAssertEqual(.writtenCompletely, result)
}
}
/// Test that cancellation of the Channel writes works correctly.
func testPendingWritesCancellationWorksCorrectly() throws {
let el = EmbeddedEventLoop()
@@ -605,13 +644,13 @@ public class ChannelTests: XCTestCase {
_ = pwm.add(data: .byteBuffer(emptyBuffer), promise: ps[2])
let result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
expectedSingleWritabilities: nil,
expectedVectorWritabilities: [[4, 4], [2, 4]],
expectedFileWritabilities: nil,
returns: [.processed(2), .wouldBlock(0)],
promiseStates: [[false, false, false], [false, false, false]])
XCTAssertEqual(WriteResult.wouldBlock, result)
promises: ps,
expectedSingleWritabilities: nil,
expectedVectorWritabilities: [[4, 4], [2, 4]],
expectedFileWritabilities: nil,
returns: [.processed(2), .wouldBlock(0)],
promiseStates: [[false, false, false], [false, false, false]])
XCTAssertEqual(.couldNotWriteEverything, result)
pwm.failAll(error: ChannelError.operationUnsupported, close: true)
@@ -642,12 +681,12 @@ public class ChannelTests: XCTestCase {
let result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
expectedSingleWritabilities: nil,
expectedVectorWritabilities: [[halfTheWriteVLimit, halfTheWriteVLimit], [halfTheWriteVLimit]],
expectedSingleWritabilities: [halfTheWriteVLimit],
expectedVectorWritabilities: [[halfTheWriteVLimit, halfTheWriteVLimit]],
expectedFileWritabilities: nil,
returns: [.processed(2 * halfTheWriteVLimit), .processed(halfTheWriteVLimit)],
promiseStates: [[true, true, false], [true, true, true]])
XCTAssertEqual(WriteResult.writtenCompletely, result)
XCTAssertEqual(.writtenCompletely, result)
}
}
@@ -691,7 +730,7 @@ public class ChannelTests: XCTestCase {
/* Xcode */ [true, false, false],
/* needs */ [true, false, false],
/* help */ [true, true, true]])
XCTAssertEqual(WriteResult.writtenCompletely, result)
XCTAssertEqual(.writtenCompletely, result)
XCTAssertTrue(flushPromise1.futureResult.fulfilled)
let emptyFlushPromise: EventLoopPromise<()> = el.newPromise()
@@ -733,7 +772,7 @@ public class ChannelTests: XCTestCase {
expectedFileWritabilities: nil,
returns: [],
promiseStates: [[true, false]])
XCTAssertEqual(WriteResult.nothingToBeWritten, result)
XCTAssertEqual(.writtenCompletely, result)
pwm.markFlushCheckpoint(promise: nil)
@@ -744,7 +783,7 @@ public class ChannelTests: XCTestCase {
expectedFileWritabilities: [(0, 2), (1, 2)],
returns: [.processed(1), .processed(1)],
promiseStates: [[true, false], [true, true]])
XCTAssertEqual(WriteResult.writtenCompletely, result)
XCTAssertEqual(.writtenCompletely, result)
}
}
@@ -802,44 +841,20 @@ public class ChannelTests: XCTestCase {
var result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
expectedSingleWritabilities: nil,
expectedSingleWritabilities: [4, 3, 2, 1],
expectedVectorWritabilities: [[4, 4]],
expectedFileWritabilities: nil,
returns: [.processed(8)],
promiseStates: [[true, true, false, false, false]])
XCTAssertEqual(.writtenCompletely, result)
result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
expectedSingleWritabilities: nil,
expectedVectorWritabilities: nil,
expectedFileWritabilities: [(99, 99)],
returns: [.processed(0)],
promiseStates: [[true, true, true, false, false]])
XCTAssertEqual(.writtenCompletely, result)
result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
expectedSingleWritabilities: [4, 3, 2, 1],
expectedVectorWritabilities: nil,
expectedFileWritabilities: nil,
returns: [.processed(1), .processed(1), .processed(1), .processed(1)],
promiseStates: [[true, true, true, false, false],
[true, true, true, false, false],
[true, true, true, false, false],
[true, true, true, true, false]])
XCTAssertEqual(.writtenCompletely, result)
result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
expectedSingleWritabilities: nil,
expectedVectorWritabilities: nil,
expectedFileWritabilities: [(0, 10), (3, 10), (6, 10)],
returns: [.wouldBlock(3), .processed(3), .wouldBlock(0)],
promiseStates: [[true, true, true, true, false],
[true, true, true, true, false],
[true, true, true, true, false]])
XCTAssertEqual(.wouldBlock, result)
expectedFileWritabilities: [(99, 99), (0, 10), (3, 10), (6, 10)],
returns: [.processed(8), .processed(0), .processed(1), .processed(1), .processed(1), .processed(1), .wouldBlock(3), .processed(3), .wouldBlock(0)],
promiseStates: [[true, true, false, false, false],
[true, true, true, false, false],
[true, true, true, false, false],
[true, true, true, false, false],
[true, true, true, false, false],
[true, true, true, true, false],
[true, true, true, true, false],
[true, true, true, true, false],
[true, true, true, true, false]])
XCTAssertEqual(.couldNotWriteEverything, result)
result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
@@ -891,38 +906,14 @@ public class ChannelTests: XCTestCase {
pwm.markFlushCheckpoint(promise: ps[1])
result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
expectedSingleWritabilities: nil,
expectedVectorWritabilities: [[4, 4]],
expectedFileWritabilities: nil,
returns: [.processed(8)],
promiseStates: [[true, false]])
XCTAssertEqual(WriteResult.writtenCompletely, result)
result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
expectedSingleWritabilities: nil,
expectedVectorWritabilities: nil,
expectedFileWritabilities: [(99, 99)],
returns: [.processed(0)],
promiseStates: [[true, false]])
XCTAssertEqual(WriteResult.writtenCompletely, result)
result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
expectedSingleWritabilities: [4],
expectedVectorWritabilities: nil,
expectedFileWritabilities: nil,
returns: [.processed(4)],
promiseStates: [[true, false]])
XCTAssertEqual(WriteResult.writtenCompletely, result)
result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
expectedSingleWritabilities: nil,
expectedVectorWritabilities: nil,
expectedFileWritabilities: [(0, 10)],
returns: [.processed(10)],
promiseStates: [[true, true]])
XCTAssertEqual(WriteResult.writtenCompletely, result)
expectedVectorWritabilities: [[4, 4]],
expectedFileWritabilities: [(99, 99), (0, 10)],
returns: [.processed(8), .processed(0), .processed(4), .processed(10)],
promiseStates: [[true, false], [true, false], [true, false], [true, true]])
XCTAssertEqual(.writtenCompletely, result)
}
}
@@ -963,7 +954,7 @@ public class ChannelTests: XCTestCase {
expectedFileWritabilities: nil,
returns: [.processed(8)],
promiseStates: [[true, true, true, true, false, false]])
XCTAssertEqual(WriteResult.writtenCompletely, result)
XCTAssertEqual(.writtenCompletely, result)
pwm.markFlushCheckpoint(promise: ps[5])
@@ -974,7 +965,7 @@ public class ChannelTests: XCTestCase {
expectedFileWritabilities: nil,
returns: [.processed(0)],
promiseStates: [[true, true, true, true, true, true]])
XCTAssertEqual(WriteResult.writtenCompletely, result)
XCTAssertEqual(.writtenCompletely, result)
}
}
@@ -998,7 +989,7 @@ public class ChannelTests: XCTestCase {
expectedFileWritabilities: nil,
returns: [.processed(0)],
promiseStates: [[true, true, false]])
XCTAssertEqual(WriteResult.writtenCompletely, result)
XCTAssertEqual(.writtenCompletely, result)
pwm.markFlushCheckpoint(promise: nil)
@@ -1009,7 +1000,7 @@ public class ChannelTests: XCTestCase {
expectedFileWritabilities: nil,
returns: [.processed(0)],
promiseStates: [[true, true, true]])
XCTAssertEqual(WriteResult.writtenCompletely, result)
XCTAssertEqual(.writtenCompletely, result)
}
}
@@ -1037,7 +1028,7 @@ public class ChannelTests: XCTestCase {
expectedFileWritabilities: nil,
returns: [.processed(4)],
promiseStates: [[true, true, true]])
XCTAssertEqual(WriteResult.closed, result)
XCTAssertEqual(.writtenCompletely, result)
XCTAssertNoThrow(try ps[0].futureResult.wait())
XCTAssertThrowsError(try ps[1].futureResult.wait())
XCTAssertThrowsError(try ps[2].futureResult.wait())
@@ -1060,13 +1051,13 @@ public class ChannelTests: XCTestCase {
var result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
expectedSingleWritabilities: nil,
expectedVectorWritabilities: [Array(repeating: 4, count: Socket.writevLimitIOVectors), [4]],
expectedSingleWritabilities: [4],
expectedVectorWritabilities: [Array(repeating: 4, count: Socket.writevLimitIOVectors)],
expectedFileWritabilities: nil,
returns: [.processed(4 * Socket.writevLimitIOVectors), .wouldBlock(0)],
promiseStates: [Array(repeating: true, count: Socket.writevLimitIOVectors) + [false],
Array(repeating: true, count: Socket.writevLimitIOVectors) + [false]])
XCTAssertEqual(WriteResult.wouldBlock, result)
XCTAssertEqual(.couldNotWriteEverything, result)
XCTAssertFalse(flushPromise.futureResult.fulfilled)
result = try assertExpectedWritability(pendingWritesManager: pwm,
promises: ps,
@@ -1075,7 +1066,7 @@ public class ChannelTests: XCTestCase {
expectedFileWritabilities: nil,
returns: [.processed(4)],
promiseStates: [Array(repeating: true, count: Socket.writevLimitIOVectors + 1)])
XCTAssertEqual(WriteResult.writtenCompletely, result)
XCTAssertEqual(.writtenCompletely, result)
XCTAssertTrue(flushPromise.futureResult.fulfilled)
}
}
@@ -261,7 +261,7 @@ class PendingDatagramWritesManagerTests: XCTestCase {
expectedVectorWritabilities: nil,
returns: [],
promiseStates: [[true, false]])
XCTAssertEqual(WriteResult.nothingToBeWritten, result)
XCTAssertEqual(WriteResult.writtenCompletely, result)
pwm.markFlushCheckpoint(promise: nil)
@@ -622,7 +622,7 @@ class PendingDatagramWritesManagerTests: XCTestCase {
expectedVectorWritabilities: [[(4, address), (4, address)]],
returns: [.ok(.processed(1))],
promiseStates: [[true, true, true]])
XCTAssertEqual(WriteResult.closed, result)
XCTAssertEqual(WriteResult.writtenCompletely, result)
XCTAssertNoThrow(try ps[0].futureResult.wait())
XCTAssertThrowsError(try ps[1].futureResult.wait())
XCTAssertThrowsError(try ps[2].futureResult.wait())