diff --git a/Sources/NIO/Channel.swift b/Sources/NIO/Channel.swift index d7642efd8..fe79b66eb 100644 --- a/Sources/NIO/Channel.swift +++ b/Sources/NIO/Channel.swift @@ -91,33 +91,19 @@ public struct IOData { } } -final class PendingWrite { - var next: PendingWrite? - var buffer: ByteBuffer - var promise: Promise? +typealias PendingWrite = (buffer: ByteBuffer, promise: Promise?) - init(buffer: ByteBuffer, promise: Promise?) { - self.buffer = buffer - self.promise = promise - } -} - -func doPendingWriteVectorOperation(pending: PendingWrite?, - count: Int, - iovecs: UnsafeMutableBufferPointer, - storageRefs: UnsafeMutableBufferPointer>, - _ fn: (UnsafeBufferPointer) throws -> IOResult) throws -> IOResult { - var next = pending +private func doPendingWriteVectorOperation(pending: MarkedCircularBuffer, + count: Int, + iovecs: UnsafeMutableBufferPointer, + storageRefs: UnsafeMutableBufferPointer>, + _ fn: (UnsafeBufferPointer) throws -> IOResult) throws -> IOResult { + assert(count <= pending.count, "requested to write \(count) pending writes but only \(pending.count) available") for i in 0..: CustomStringConvertible { + private var buffer: CircularBuffer + private var markedIndex: Int = -1 /* negative: nothing marked */ + + public init(initialRingCapacity: UInt, expandSize: UInt = 8) { + self.buffer = CircularBuffer(initialRingCapacity: initialRingCapacity, expandSize: expandSize) + } + + // MARK: Forwarding + public mutating func append(_ value: E) { + self.buffer.append(value) + } + + public mutating func removeFirst() -> E { + self.markedIndex -= 1 + return self.buffer.removeFirst() + } + + public var first: E? { + return self.buffer.first + } + + public var isEmpty: Bool { + return self.buffer.isEmpty + } + + public var count: Int { + return self.buffer.count + } + + public subscript(index: Int) -> E { + get { + return self.buffer[index] + } + set { + self.buffer[index] = newValue + } + } + + public var indices: CountableRange { + return self.buffer.indices + } + + public var description: String { + return self.buffer.description + } + + // MARK: Marking + public mutating func mark() { + let count = self.buffer.count + if count > 0 { + self.markedIndex = count - 1 + } else { + assert(self.markedIndex == -1) + } + } + + public func isMarked(index: Int) -> Bool { + precondition(index >= 0 && index < self.buffer.count) + return self.markedIndex == index + } + + public func markedElementIndex() -> Int? { + let markedIndex = self.markedIndex + if markedIndex >= 0 { + return markedIndex + } else { + assert(markedIndex == -1, "marked index is \(markedIndex)") + return nil + } + } + + public func markedElement() -> E? { + return self.markedElementIndex().map { self.buffer[$0] } + } + + public func hasMark() -> Bool { + if self.markedIndex < 0 { + precondition(self.markedIndex == -1) + return false + } else { + return true + } + } +} + final fileprivate class PendingWrites { - private var head: PendingWrite? - private var tail: PendingWrite? + private var pendingWrites = MarkedCircularBuffer(initialRingCapacity: 16, expandSize: 3) + // Marks the last PendingWrite that should be written by consume(...) - private var flushCheckpoint: PendingWrite? private var iovecs: UnsafeMutableBufferPointer private var storageRefs: UnsafeMutableBufferPointer> fileprivate var waterMark: WriteBufferWaterMark = WriteBufferWaterMark(32 * 1024..<64 * 1024) private var writable: Atomic = Atomic(value: true) - fileprivate var writeSpinCount: UInt = 16 private(set) var outstanding: (chunks: Int, bytes: Int) = (0, 0) @@ -160,21 +230,12 @@ final fileprivate class PendingWrites { } var isEmpty: Bool { - return tail == nil + return self.pendingWrites.isEmpty } func add(buffer: ByteBuffer, promise: Promise?) -> Bool { assert(!closed) - let pending: PendingWrite = PendingWrite(buffer: buffer, promise: promise) - if let last = tail { - assert(head != nil) - last.next = pending - tail = pending - } else { - assert(tail == nil) - head = pending - tail = pending - } + self.pendingWrites.append((buffer: buffer, promise: promise)) outstanding = (chunks: outstanding.chunks + 1, bytes: outstanding.bytes + buffer.readableBytes) if outstanding.bytes > Int(waterMark.upperBound) && writable.compareAndExchange(expected: true, desired: false) { @@ -185,18 +246,17 @@ final fileprivate class PendingWrites { } private var hasMultiple: Bool { - return head?.next != nil + return self.pendingWrites.count > 1 } func markFlushCheckpoint(promise: Promise?) { - flushCheckpoint = tail - if let promise = promise { - if let checkpoint = flushCheckpoint { - if let p = checkpoint.promise { - p.futureResult.cascade(promise: promise) - } else { - checkpoint.promise = promise - } + self.pendingWrites.mark() + let checkpointIdx = self.pendingWrites.markedElementIndex() + if let promise = promise, let checkpoint = checkpointIdx { + if let p = self.pendingWrites[checkpoint].promise { + p.futureResult.cascade(promise: promise) + } else { + self.pendingWrites[checkpoint].promise = promise } } } @@ -215,23 +275,18 @@ final fileprivate class PendingWrites { return (result, false) } - private func updateNodes(pending: PendingWrite) { - head = pending.next - if head == nil { - tail = nil - flushCheckpoint = nil - } else if pending === flushCheckpoint { - // pending was the flush checkpoint so reset it - flushCheckpoint = nil - } + @discardableResult + private func popFirst() -> PendingWrite { + return self.pendingWrites.removeFirst() } var isFlushPending: Bool { - return flushCheckpoint != nil + return self.pendingWrites.hasMark() } private func consumeOne(_ body: (UnsafePointer, Int) throws -> IOResult) rethrows -> WriteResult { - if let pending = head, isFlushPending { + if self.isFlushPending && !self.pendingWrites.isEmpty { + let pending = self.pendingWrites[0] for _ in 0..) throws -> IOResult) throws -> WriteResult { - if var pending = head, isFlushPending { + if self.isFlushPending && !self.pendingWrites.isEmpty { writeLoop: for _ in 0..= p.buffer.readableBytes { w -= p.buffer.readableBytes outstanding = (outstanding.chunks-1, outstanding.bytes) // Directly update nodes as a promise may trigger a callback that will access the PendingWrites class. - updateNodes(pending: p) + popFirst() // buffer was completely written p.promise?.succeed(result: ()) @@ -310,10 +366,7 @@ final fileprivate class PendingWrites { } else { // Only partly written, so update the readerIndex. - p.buffer.moveReaderIndex(forwardBy: w) - - // update pending so we not need to process the old PendingWrites that we already processed and completed - pending = p + self.pendingWrites[0].buffer.moveReaderIndex(forwardBy: w) // may try again depending on the writeSpinCount continue writeLoop @@ -329,36 +382,19 @@ final fileprivate class PendingWrites { return .nothingToBeWritten } - - private func killAll(node: PendingWrite?, deconstructor: (PendingWrite) -> ()) { - var link = node - while link != nil { - let curr = link! - link = curr.next - curr.next = nil - deconstructor(curr) - } - } - func failAll(error: Error) { closed = true - /* - Workaround for https://bugs.swift.org/browse/SR-5145 which is that this linked list can cause a - stack overflow when released as the `deinit`s will get called with recursion. - */ - - killAll(node: head, deconstructor: { pending in + while !self.pendingWrites.isEmpty { + let pending = self.pendingWrites[0] outstanding = (outstanding.chunks-1, outstanding.bytes - pending.buffer.readableBytes) + popFirst() pending.promise?.fail(error: error) - }) - - // Remove references. - head = nil - tail = nil - flushCheckpoint = nil + } + assert(self.pendingWrites.isEmpty) + assert(self.pendingWrites.markedElement() == nil) assert(outstanding == (0, 0)) } @@ -889,7 +925,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { return; } // Even if writable() will be called later by the EVentLoop we still need to mark the flush checkpoint so we are sure all the flushed messages - // are actual written once writable() is called. + // are actually written once writable() is called. pendingWrites.markFlushCheckpoint(promise: promise) if !isWritePending() && !flushNow() && !closed { diff --git a/Sources/NIO/CircularBuffer.swift b/Sources/NIO/CircularBuffer.swift new file mode 100644 index 000000000..0227fd71a --- /dev/null +++ b/Sources/NIO/CircularBuffer.swift @@ -0,0 +1,147 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +public struct CircularBuffer: CustomStringConvertible { + private var buffer: ContiguousArray + + /* the capacity of the underlying buffer */ + /* private */ var bufferCapacity: Int + + /* how many slots of the underlying buffer are actually used */ + private var bufferLength = 0 + + /* the index into the buffer of the first item */ + private var startIdx = 0 + + /* the index into the buffer of the next free slot */ + private var endIdx = 0 + + /* the number of items in the ring part of this buffer */ + private var ringLength = 0 + + /* the capacity of the ring */ + private var ringCapacity: Int + + /* how many elements to add to the buffer by default if it's exhausted */ + private let expandSize: Int + + public init(initialRingCapacity: UInt, expandSize: UInt = 8) { + self.bufferCapacity = Int(initialRingCapacity) + self.ringCapacity = Int(initialRingCapacity) + self.buffer = ContiguousArray(repeating: nil, count: Int(initialRingCapacity)) + self.expandSize = Int(expandSize) + } + + public mutating func append(_ value: E) { + let expandBuf: Bool + let expandRing: Bool + if self.ringCapacity != self.bufferCapacity { + expandBuf = self.endIdx == 0 + expandRing = false + } else if self.ringCapacity == self.ringLength { + expandBuf = true + expandRing = self.endIdx == 0 + } else { + expandBuf = false + expandRing = false + } + + if expandBuf { + self.endIdx = self.bufferCapacity + let expansion: [E?] = Array(repeating: nil, count: self.expandSize) + self.buffer.append(contentsOf: expansion) + self.bufferCapacity += expansion.count + if expandRing { + self.ringCapacity = self.bufferCapacity + } + } + + self.buffer[self.endIdx] = value + self.bufferLength += 1 + if self.endIdx < self.ringCapacity { + self.ringLength += 1 + } + self.endIdx = (self.endIdx + 1) % self.bufferCapacity + } + + public mutating func removeFirst() -> E { + precondition(self.bufferLength != 0) + + let value = self.buffer[self.startIdx] + self.buffer[startIdx] = nil + self.bufferLength -= 1 + self.ringLength -= 1 + if self.ringLength == 0 && self.bufferLength != 0 { + self.startIdx = self.ringCapacity + self.ringLength = self.bufferLength + self.ringCapacity = self.bufferCapacity + } else { + self.startIdx = (self.startIdx + 1) % self.ringCapacity + } + + return value! + } + + public var first: E? { + if self.isEmpty { + return nil + } else { + return self.buffer[self.startIdx] + } + } + + public var isEmpty: Bool { + return self.bufferLength == 0 + } + + public var count: Int { + return self.bufferLength + } + + private func bufferIndex(ofIndex index: Int) -> Int { + if index < self.ringLength { + return (self.startIdx + index) % self.ringCapacity + } else { + return self.ringCapacity + index - ringLength + } + } + + public subscript(index: Int) -> E { + get { + return self.buffer[self.bufferIndex(ofIndex: index)]! + } + set { + self.buffer[self.bufferIndex(ofIndex: index)] = newValue + } + } + + public var indices: CountableRange { + return 0.. () throws -> Void)] { + return [ + ("testTrivial", testTrivial), + ("testAddRemoveInALoop", testAddRemoveInALoop), + ("testAddAllRemoveAll", testAddAllRemoveAll), + ("testHarderExpansion", testHarderExpansion), + ] + } +} + diff --git a/Tests/NIOTests/CircularBufferTests.swift b/Tests/NIOTests/CircularBufferTests.swift new file mode 100644 index 000000000..e97ebf189 --- /dev/null +++ b/Tests/NIOTests/CircularBufferTests.swift @@ -0,0 +1,89 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Foundation +import XCTest +import NIO + +class CircularBufferTests: XCTestCase { + func testTrivial() { + var ring = CircularBuffer(initialRingCapacity: 8) + ring.append(1) + XCTAssertEqual(1, ring.removeFirst()) + } + + func testAddRemoveInALoop() { + var ring = CircularBuffer(initialRingCapacity: 8) + for f in 0..<1000 { + ring.append(f) + XCTAssertEqual(f, ring.removeFirst()) + } + } + + func testAddAllRemoveAll() { + var ring = CircularBuffer(initialRingCapacity: 8) + for f in 0..<1000 { + ring.append(f) + } + for f in 0..<1000 { + XCTAssertEqual(f, ring.removeFirst()) + } + } + + func testHarderExpansion() { + var ring = CircularBuffer(initialRingCapacity: 3, expandSize: 3) + ring.append(1) + XCTAssertEqual(ring.count, 1) + XCTAssertEqual(ring[0], 1) + + ring.append(2) + XCTAssertEqual(ring.count, 2) + XCTAssertEqual(ring[0], 1) + XCTAssertEqual(ring[1], 2) + + ring.append(3) + XCTAssertEqual(ring.count, 3) + XCTAssertEqual(ring[0], 1) + XCTAssertEqual(ring[1], 2) + XCTAssertEqual(ring[2], 3) + + + XCTAssertEqual(1, ring.removeFirst()) + XCTAssertEqual(ring.count, 2) + XCTAssertEqual(ring[0], 2) + XCTAssertEqual(ring[1], 3) + + XCTAssertEqual(2, ring.removeFirst()) + XCTAssertEqual(ring.count, 1) + XCTAssertEqual(ring[0], 3) + + ring.append(5) + XCTAssertEqual(ring.count, 2) + XCTAssertEqual(ring[0], 3) + XCTAssertEqual(ring[1], 5) + + ring.append(6) + XCTAssertEqual(ring.count, 3) + XCTAssertEqual(ring[0], 3) + XCTAssertEqual(ring[1], 5) + XCTAssertEqual(ring[2], 6) + + ring.append(7) + XCTAssertEqual(ring.count, 4) + XCTAssertEqual(ring[0], 3) + XCTAssertEqual(ring[1], 5) + XCTAssertEqual(ring[2], 6) + XCTAssertEqual(ring[3], 7) + } +}