Implement a NIOAsyncWriter (#2251)

* Implement a `NIOAsyncWriter`

# Motivation
We previously added the `NIOAsyncProducer` to bridge between the NIO channel pipeline and the asynchronous world. However, we still need something to bridge writes from the asynchronous world back to the NIO channel pipeline.

# Modification
This PR adds a new `NIOAsyncWriter` type that allows us to asynchronously `yield` elements to it. On the other side, we can register a `NIOAsyncWriterDelegate` which will get informed about any written elements. Furthermore, the synchronous side can toggle the writability of the `AsyncWriter` which allows it to implement flow control.
A main goal of this type is to be as performant as possible. To achieve this I did the following things:
- Make everything generic and inlinable
- Use a class with a lock instead of an actor
- Provide methods to yield a sequence of things which allows users to reduce the amount of times the lock gets acquired.

# Result
We now have the means to bridge writes from the asynchronous world to the synchronous

* Remove the completion struct and incorporate code review comments

* Fixup some refactoring leftovers

* More code review comments

* Move to holding the lock around the delegate and moved the delegate into the state machine

* Comment fixups

* More doc fixes

* Call finish when the sink deinits

* Refactor the writer to only yield Deques and rename the delegate to NIOAsyncWriterSinkDelegate

* Review

* Fix some warnings

* Fix benchmark sendability

* Remove Failure generic parameter and allow sending of an error through the Sink
This commit is contained in:
Franz Busch authored and GitHub committed 2022-09-21 02:53:53 -07:00
1 parent 26afcecdc2
commit f144292e5d
9 files changed
+1738 -3

No files matched your search

+1 -1
View File
@@ -20,7 +20,7 @@ let swiftCollections: PackageDescription.Target.Dependency = .product(name: "Deq
var targets: [PackageDescription.Target] = [
.target(name: "NIOCore",
dependencies: ["NIOConcurrencyHelpers", "CNIOLinux", "CNIOWindows", swiftCollections]),
dependencies: ["NIOConcurrencyHelpers", "CNIOLinux", "CNIOWindows", swiftCollections, swiftAtomics]),
.target(name: "_NIODataStructures"),
.target(name: "NIOEmbedded",
dependencies: ["NIOCore",
+1 -1
View File
@@ -20,7 +20,7 @@ let swiftCollections: PackageDescription.Target.Dependency = .product(name: "Deq
var targets: [PackageDescription.Target] = [
.target(name: "NIOCore",
dependencies: ["NIOConcurrencyHelpers", "CNIOLinux", "CNIOWindows", swiftCollections]),
dependencies: ["NIOConcurrencyHelpers", "CNIOLinux", "CNIOWindows", swiftCollections, swiftAtomics]),
.target(name: "_NIODataStructures"),
.target(name: "NIOEmbedded",
dependencies: ["NIOCore",
+1 -1
View File
@@ -20,7 +20,7 @@ let swiftCollections: PackageDescription.Target.Dependency = .product(name: "Deq
var targets: [PackageDescription.Target] = [
.target(name: "NIOCore",
dependencies: ["NIOConcurrencyHelpers", "CNIOLinux", "CNIOWindows", swiftCollections]),
dependencies: ["NIOConcurrencyHelpers", "CNIOLinux", "CNIOWindows", swiftCollections, swiftAtomics]),
.target(name: "_NIODataStructures"),
.target(name: "NIOEmbedded",
dependencies: ["NIOCore",
File diff suppressed because it is too large. Load diff
@@ -12,6 +12,8 @@
//
//===----------------------------------------------------------------------===//
import Dispatch
protocol Benchmark: AnyObject {
func setUp() throws
func tearDown()
@@ -27,3 +29,32 @@ func measureAndPrint<B: Benchmark>(desc: String, benchmark bench: B) throws {
return try bench.run()
}
}
#if compiler(>=5.5.2) && canImport(_Concurrency)
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
protocol AsyncBenchmark: AnyObject, Sendable {
func setUp() async throws
func tearDown()
func run() async throws -> Int
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
func measureAndPrint<B: AsyncBenchmark>(desc: String, benchmark bench: B) throws {
let group = DispatchGroup()
group.enter()
Task {
do {
try await bench.setUp()
defer {
bench.tearDown()
}
try await measureAndPrint(desc: desc) {
return try await bench.run()
}
}
group.leave()
}
group.wait()
}
#endif
@@ -0,0 +1,57 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2022 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
//
//===----------------------------------------------------------------------===//
#if compiler(>=5.5.2) && canImport(_Concurrency)
import NIOCore
import DequeModule
import Atomics
struct NoOpDelegate: NIOAsyncWriterSinkDelegate, @unchecked Sendable {
typealias Element = Int
let counter = ManagedAtomic(0)
func didYield(contentsOf sequence: Deque<Int>) {
counter.wrappingIncrement(by: sequence.count, ordering: .relaxed)
}
func didTerminate(error: Error?) {}
}
// This is unchecked Sendable because the Sink is not Sendable but the Sink is thread safe
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
final class NIOAsyncWriterSingleWritesBenchmark: AsyncBenchmark, @unchecked Sendable {
private let iterations: Int
private let delegate: NoOpDelegate
private let writer: NIOAsyncWriter<Int, NoOpDelegate>
private let sink: NIOAsyncWriter<Int, NoOpDelegate>.Sink
init(iterations: Int) {
self.iterations = iterations
self.delegate = .init()
let newWriter = NIOAsyncWriter<Int, NoOpDelegate>.makeWriter(isWritable: true, delegate: self.delegate)
self.writer = newWriter.writer
self.sink = newWriter.sink
}
func setUp() async throws {}
func tearDown() {}
func run() async throws -> Int {
for i in 0..<self.iterations {
try await self.writer.yield(i)
}
return self.delegate.counter.load(ordering: .sequentiallyConsistent)
}
}
#endif
+42
View File
@@ -62,6 +62,37 @@ public func measureAndPrint(desc: String, fn: () throws -> Int) rethrows -> Void
}
}
#if compiler(>=5.5.2) && canImport(_Concurrency)
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func measure(_ fn: () async throws -> Int) async rethrows -> [Double] {
func measureOne(_ fn: () async throws -> Int) async rethrows -> Double {
let start = DispatchTime.now().uptimeNanoseconds
_ = try await fn()
let end = DispatchTime.now().uptimeNanoseconds
return Double(end - start) / Double(TimeAmount.seconds(1).nanoseconds)
}
_ = try await measureOne(fn) /* pre-heat and throw away */
var measurements = Array(repeating: 0.0, count: 10)
for i in 0..<10 {
measurements[i] = try await measureOne(fn)
}
return measurements
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func measureAndPrint(desc: String, fn: () async throws -> Int) async rethrows -> Void {
if limitSet.isEmpty || limitSet.contains(desc) {
print("measuring\(warning): \(desc): ", terminator: "")
let measurements = try await measure(fn)
print(measurements.reduce(into: "") { $0.append("\($1), ") })
} else {
print("skipping '\(desc)', limit set = \(limitSet)")
}
}
#endif
// MARK: Utilities
private final class SimpleHTTPServer: ChannelInboundHandler {
@@ -1053,3 +1084,14 @@ try measureAndPrint(
iterations: 1_000_000
)
)
#if compiler(>=5.5.2) && canImport(_Concurrency)
if #available(macOS 10.15, *) {
try measureAndPrint(
desc: "asyncwriter_single_writes_1M_times",
benchmark: NIOAsyncWriterSingleWritesBenchmark(
iterations: 1_000_000
)
)
}
#endif
@@ -0,0 +1,532 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2022 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
//
//===----------------------------------------------------------------------===//
#if compiler(>=5.5.2) && canImport(_Concurrency)
import DequeModule
import NIOCore
import XCTest
private struct SomeError: Error, Hashable {}
private final class MockAsyncWriterDelegate: NIOAsyncWriterSinkDelegate, @unchecked Sendable {
typealias Element = String
var didYieldCallCount = 0
var didYieldHandler: ((Deque<String>) -> Void)?
func didYield(contentsOf sequence: Deque<String>) {
self.didYieldCallCount += 1
if let didYieldHandler = self.didYieldHandler {
didYieldHandler(sequence)
}
}
var didTerminateCallCount = 0
var didTerminateHandler: ((Error?) -> Void)?
func didTerminate(error: Error?) {
self.didTerminateCallCount += 1
if let didTerminateHandler = self.didTerminateHandler {
didTerminateHandler(error)
}
}
}
final class NIOAsyncWriterTests: XCTestCase {
private var writer: NIOAsyncWriter<String, MockAsyncWriterDelegate>!
private var sink: NIOAsyncWriter<String, MockAsyncWriterDelegate>.Sink!
private var delegate: MockAsyncWriterDelegate!
override func setUp() {
super.setUp()
self.delegate = .init()
let newWriter = NIOAsyncWriter.makeWriter(
elementType: String.self,
isWritable: true,
delegate: self.delegate
)
self.writer = newWriter.writer
self.sink = newWriter.sink
}
override func tearDown() {
self.delegate = nil
self.writer = nil
self.sink = nil
super.tearDown()
}
func testMultipleConcurrentWrites() async throws {
let task1 = Task { [writer] in
for i in 0...9 {
try await writer!.yield("message\(i)")
}
}
let task2 = Task { [writer] in
for i in 10...19 {
try await writer!.yield("message\(i)")
}
}
let task3 = Task { [writer] in
for i in 20...29 {
try await writer!.yield("message\(i)")
}
}
try await task1.value
try await task2.value
try await task3.value
XCTAssertEqual(self.delegate.didYieldCallCount, 30)
}
func testWriterCoalescesWrites() async throws {
var writes = [Deque<String>]()
self.delegate.didYieldHandler = {
writes.append($0)
}
self.sink.setWritability(to: false)
let task1 = Task { [writer] in
try await writer!.yield("message1")
}
task1.cancel()
try await task1.value
let task2 = Task { [writer] in
try await writer!.yield("message2")
}
task2.cancel()
try await task2.value
let task3 = Task { [writer] in
try await writer!.yield("message3")
}
task3.cancel()
try await task3.value
self.sink.setWritability(to: true)
XCTAssertEqual(writes, [Deque(["message1", "message2", "message3"])])
}
// MARK: - WriterDeinitialized
func testWriterDeinitialized_whenInitial() async throws {
self.writer = nil
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
func testWriterDeinitialized_whenStreaming() async throws {
Task { [writer] in
try await writer!.yield("message1")
}
try await Task.sleep(nanoseconds: 1_000_000)
self.writer = nil
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
func testWriterDeinitialized_whenWriterFinished() async throws {
self.sink.setWritability(to: false)
Task { [writer] in
try await writer!.yield("message1")
}
try await Task.sleep(nanoseconds: 1_000_000)
self.writer.finish()
self.writer = nil
XCTAssertEqual(self.delegate.didYieldCallCount, 0)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
func testWriterDeinitialized_whenFinished() async throws {
self.sink.finish()
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
self.writer = nil
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
// MARK: - ToggleWritability
func testSetWritability_whenInitial() async throws {
self.sink.setWritability(to: false)
Task { [writer] in
try await writer!.yield("message1")
}
// Sleep a bit so that the other Task suspends on the yield
try await Task.sleep(nanoseconds: 1_000_000)
XCTAssertEqual(self.delegate.didYieldCallCount, 0)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
func testSetWritability_whenStreaming_andBecomingUnwritable() async throws {
try await self.writer.yield("message1")
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
self.sink.setWritability(to: false)
Task { [writer] in
try await writer!.yield("message2")
}
// Sleep a bit so that the other Task suspends on the yield
try await Task.sleep(nanoseconds: 1_000_000)
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
func testSetWritability_whenStreaming_andBecomingWritable() async throws {
self.sink.setWritability(to: false)
Task { [writer] in
try await writer!.yield("message2")
}
// Sleep a bit so that the other Task suspends on the yield
try await Task.sleep(nanoseconds: 1_000_000)
self.sink.setWritability(to: true)
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
func testSetWritability_whenStreaming_andSettingSameWritability() async throws {
self.sink.setWritability(to: false)
Task { [writer] in
try await writer!.yield("message1")
}
// Sleep a bit so that the other Task suspends on the yield
try await Task.sleep(nanoseconds: 1_000_000)
// Setting the writability to the same state again shouldn't change anything
self.sink.setWritability(to: false)
XCTAssertEqual(self.delegate.didYieldCallCount, 0)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
func testSetWritability_whenWriterFinished() async throws {
self.sink.setWritability(to: false)
Task { [writer] in
try await writer!.yield("message1")
}
// Sleep a bit so that the other Task suspends on the yield
try await Task.sleep(nanoseconds: 1_000_000)
self.writer.finish()
XCTAssertEqual(self.delegate.didYieldCallCount, 0)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
self.sink.setWritability(to: true)
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
func testSetWritability_whenFinished() async throws {
self.sink.finish()
self.sink.setWritability(to: false)
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
// MARK: - Yield
func testYield_whenInitial_andWritable() async throws {
try await self.writer.yield("message1")
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
}
func testYield_whenInitial_andNotWritable() async throws {
self.sink.setWritability(to: false)
Task { [writer] in
try await writer!.yield("message2")
}
// Sleep a bit so that the other Task suspends on the yield
try await Task.sleep(nanoseconds: 1_000_000)
XCTAssertEqual(self.delegate.didYieldCallCount, 0)
}
func testYield_whenStreaming_andWritable() async throws {
try await self.writer.yield("message1")
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
try await self.writer.yield("message2")
XCTAssertEqual(self.delegate.didYieldCallCount, 2)
}
func testYield_whenStreaming_andNotWritable() async throws {
try await self.writer.yield("message1")
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
self.sink.setWritability(to: false)
Task { [writer] in
try await writer!.yield("message2")
}
// Sleep a bit so that the other Task suspends on the yield
try await Task.sleep(nanoseconds: 1_000_000)
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
}
func testYield_whenStreaming_andYieldCancelled() async throws {
try await self.writer.yield("message1")
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
let task = Task { [writer] in
// Sleeping here a bit to delay the call to yield
// The idea is that we call yield once the Task is
// already cancelled
try? await Task.sleep(nanoseconds: 1_000_000)
try await writer!.yield("message2")
}
task.cancel()
await XCTAssertNoThrow(try await task.value)
XCTAssertEqual(self.delegate.didYieldCallCount, 2)
}
func testYield_whenWriterFinished() async throws {
self.sink.setWritability(to: false)
Task { [writer] in
try await writer!.yield("message1")
}
// Sleep a bit so that the other Task suspends on the yield
try await Task.sleep(nanoseconds: 1_000_000)
self.writer.finish()
await XCTAssertThrowsError(try await self.writer.yield("message1")) { error in
XCTAssertEqual(error as? NIOAsyncWriterError, .alreadyFinished())
}
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
func testYield_whenFinished() async throws {
self.sink.finish()
await XCTAssertThrowsError(try await self.writer.yield("message1")) { error in
XCTAssertEqual(error as? NIOAsyncWriterError, .alreadyFinished())
}
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
func testYield_whenFinishedError() async throws {
self.sink.finish(error: SomeError())
await XCTAssertThrowsError(try await self.writer.yield("message1")) { error in
XCTAssertTrue(error is SomeError)
}
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
// MARK: - Cancel
func testCancel_whenInitial() async throws {
let task = Task { [writer] in
// Sleeping here a bit to delay the call to yield
// The idea is that we call yield once the Task is
// already cancelled
try? await Task.sleep(nanoseconds: 1_000_000)
try await writer!.yield("message1")
}
task.cancel()
await XCTAssertNoThrow(try await task.value)
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
func testCancel_whenStreaming_andCancelBeforeYield() async throws {
try await self.writer.yield("message1")
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
let task = Task { [writer] in
// Sleeping here a bit to delay the call to yield
// The idea is that we call yield once the Task is
// already cancelled
try? await Task.sleep(nanoseconds: 1_000_000)
try await writer!.yield("message2")
}
task.cancel()
await XCTAssertNoThrow(try await task.value)
XCTAssertEqual(self.delegate.didYieldCallCount, 2)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
func testCancel_whenStreaming_andCancelAfterSuspendedYield() async throws {
try await self.writer.yield("message1")
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
self.sink.setWritability(to: false)
let task = Task { [writer] in
try await writer!.yield("message2")
}
// Sleeping here to give the task enough time to suspend on the yield
try await Task.sleep(nanoseconds: 1_000_000)
task.cancel()
await XCTAssertNoThrow(try await task.value)
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
self.sink.setWritability(to: true)
XCTAssertEqual(self.delegate.didYieldCallCount, 2)
}
func testCancel_whenFinished() async throws {
self.writer.finish()
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
let task = Task { [writer] in
// Sleeping here a bit to delay the call to yield
// The idea is that we call yield once the Task is
// already cancelled
try? await Task.sleep(nanoseconds: 1_000_000)
try await writer!.yield("message1")
}
// Sleeping here to give the task enough time to suspend on the yield
try await Task.sleep(nanoseconds: 1_000_000)
task.cancel()
XCTAssertEqual(self.delegate.didYieldCallCount, 0)
await XCTAssertThrowsError(try await task.value) { error in
XCTAssertEqual(error as? NIOAsyncWriterError, .alreadyFinished())
}
}
// MARK: - Writer Finish
func testWriterFinish_whenInitial() async throws {
self.writer.finish()
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
func testWriterFinish_whenInitial_andFailure() async throws {
self.writer.finish(error: SomeError())
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
func testWriterFinish_whenStreaming() async throws {
try await self.writer!.yield("message1")
self.writer.finish()
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
func testWriterFinish_whenStreaming_AndBufferedElements() async throws {
// We are setting up a suspended yield here to check that it gets resumed
self.sink.setWritability(to: false)
let task = Task { [writer] in
try await writer!.yield("message1")
}
// Sleeping here to give the task enough time to suspend on the yield
try await Task.sleep(nanoseconds: 1_000_000)
self.writer.finish()
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
await XCTAssertNoThrow(try await task.value)
}
func testWriterFinish_whenFinished() {
// This tests just checks that finishing again is a no-op
self.writer.finish()
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
self.writer.finish()
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
// MARK: - Sink Finish
func testSinkFinish_whenInitial() async throws {
self.sink = nil
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
func testSinkFinish_whenStreaming() async throws {
Task { [writer] in
try await writer!.yield("message1")
}
try await Task.sleep(nanoseconds: 1_000_000)
self.sink = nil
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
func testSinkFinish_whenFinished() async throws {
self.writer.finish()
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
self.sink = nil
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
}
#endif
@@ -89,6 +89,19 @@ internal func XCTAssertThrowsError<T>(
}
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal func XCTAssertNoThrow<T>(
_ expression: @autoclosure () async throws -> T,
file: StaticString = #file,
line: UInt = #line
) async {
do {
_ = try await expression()
} catch {
XCTFail("Expression did throw error", file: file, line: line)
}
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal func XCTAssertNoThrowWithResult<Result>(
_ expression: @autoclosure () async throws -> Result,