mirror of
https://github.com/apple/swift-nio
synced 2026-11-29 05:24:21 +00:00
Implement a back-pressure aware AsyncSequence source (#2230)
* Implement a back-pressure aware `AsyncSequence` source # Motivation We ran into multiple use-cases (https://github.com/apple/swift-nio/pull/2067, https://github.com/grpc/grpc-swift/blob/main/Sources/GRPC/AsyncAwaitSupport/PassthroughMessageSource.swift) already where we want to vend an `AsyncSequence` where elements are produced from the sync world while the consumer is in the async world. Furthermore, we need the `AsyncSequence` to properly support back-pressure. Since we already identified that this is something fundamental for our ecosystem and that current `AsyncSequence` sources are not providing the proper semantics or performance, it would be great to find a single solution that we can use everywhere. Before diving into the code, I think it is good to understand the goals of this `AsyncSequence`: - The `AsyncSequence` should support a single unicast `Subscriber` - The `AsyncSequence` should allow a pluggable back-pressure strategy - The `AsyncSequence` should allow to yield a sequence of elements to avoid aquiring the lock for every element. - We should make sure to do as few thread hops as possible to signal the producer to demand more elements. # Modification This PR introduces a new `AsyncSequence` called `NIOBackPressuredAsyncSequence`. The goal of that sequence to enable sync to async element streaming with back-pressure support. # Result We can now power our sync to async use-cases with this new `AsyncSequence`. # Future work There are couple of things left that I wanna land in a follow up PR: 1. An adaptive back-pressure strategy that grows and shrinks depending on the speed of consumption 2. A throwing version of this sequence 3. Potentially an async version that suspends on `yield()` and resumes when more elements should be demanded. * Fix cancellation handling * Review * Add init helper * Add return types to help the type checker * Fix 5.7 CI * Rename delegate method and update docs * Review * Switch to Deque, rename the type and change the behaviour of yielding an empty sequence * Review comments from George * Review comments by Konrad * Review and add tests for the high low strategy * Fix 5.4 tests * Code review Co-authored-by: Cory Benfield <lukasa@apple.com>
This commit is contained in:
1 parent
b4e0a274f7
commit
dd40215fd4
5 files changed
+1740
-1
No files matched your search
+3
-1
@@ -16,10 +16,11 @@
|
||||
import PackageDescription
|
||||
|
||||
let swiftAtomics: PackageDescription.Target.Dependency = .product(name: "Atomics", package: "swift-atomics")
|
||||
let swiftCollections: PackageDescription.Target.Dependency = .product(name: "DequeModule", package: "swift-collections")
|
||||
|
||||
var targets: [PackageDescription.Target] = [
|
||||
.target(name: "NIOCore",
|
||||
dependencies: ["NIOConcurrencyHelpers", "CNIOLinux", "CNIOWindows"]),
|
||||
dependencies: ["NIOConcurrencyHelpers", "CNIOLinux", "CNIOWindows", swiftCollections]),
|
||||
.target(name: "_NIODataStructures"),
|
||||
.target(name: "NIOEmbedded",
|
||||
dependencies: ["NIOCore",
|
||||
@@ -140,6 +141,7 @@ let package = Package(
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-atomics.git", from: "1.0.2"),
|
||||
.package(url: "https://github.com/apple/swift-collections.git", from: "1.0.2"),
|
||||
],
|
||||
targets: targets
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,49 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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)
|
||||
public enum NIOAsyncSequenceProducerBackPressureStrategies {
|
||||
/// A high-low watermarked back-pressure strategy for a ``NIOAsyncSequenceProducer``.
|
||||
///
|
||||
/// This strategy does the following:
|
||||
/// - On yield it keeps on demanding more elements from the producer as long as the number of buffered elements hasn't reached the `highWatermark`.
|
||||
/// - On consume it starts to demand again from the producer once the number of buffered elements reach the `lowWatermark`.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public struct HighLowWatermark: NIOAsyncSequenceProducerBackPressureStrategy {
|
||||
private let lowWatermark: Int
|
||||
private let highWatermark: Int
|
||||
|
||||
/// Initializes a new ``NIOAsyncSequenceProducerBackPressureStrategies/HighLowWatermark``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - lowWatermark: The low watermark where demand should start.
|
||||
/// - highWatermark: The high watermark where demand should be stopped.
|
||||
public init(lowWatermark: Int, highWatermark: Int) {
|
||||
precondition(lowWatermark <= highWatermark)
|
||||
self.lowWatermark = lowWatermark
|
||||
self.highWatermark = highWatermark
|
||||
}
|
||||
|
||||
public mutating func didYield(bufferDepth: Int) -> Bool {
|
||||
// We are demanding more until we reach the high watermark
|
||||
bufferDepth < self.highWatermark
|
||||
}
|
||||
|
||||
public mutating func didConsume(bufferDepth: Int) -> Bool {
|
||||
// We start demanding again once we are below the low watermark
|
||||
bufferDepth < self.lowWatermark
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOCore
|
||||
import XCTest
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
final class NIOAsyncSequenceProducerBackPressureStrategiesHighLowWatermarkTests: XCTestCase {
|
||||
private var strategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark!
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
|
||||
self.strategy = .init(
|
||||
lowWatermark: 5,
|
||||
highWatermark: 10
|
||||
)
|
||||
}
|
||||
|
||||
override func tearDown() {
|
||||
self.strategy = nil
|
||||
|
||||
super.tearDown()
|
||||
}
|
||||
|
||||
func testDidYield_whenBelowHighWatermark() {
|
||||
XCTAssertTrue(self.strategy.didYield(bufferDepth: 5))
|
||||
}
|
||||
|
||||
func testDidYield_whenAboveHighWatermark() {
|
||||
XCTAssertFalse(self.strategy.didYield(bufferDepth: 15))
|
||||
}
|
||||
|
||||
func testDidYield_whenAtHighWatermark() {
|
||||
XCTAssertFalse(self.strategy.didYield(bufferDepth: 10))
|
||||
}
|
||||
|
||||
func testDidConsume_whenBelowLowWatermark() {
|
||||
XCTAssertTrue(self.strategy.didConsume(bufferDepth: 4))
|
||||
}
|
||||
|
||||
func testDidConsume_whenAboveLowWatermark() {
|
||||
XCTAssertFalse(self.strategy.didConsume(bufferDepth: 6))
|
||||
}
|
||||
|
||||
func testDidConsume_whenAtLowWatermark() {
|
||||
XCTAssertFalse(self.strategy.didConsume(bufferDepth: 5))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,554 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOCore
|
||||
import XCTest
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
private final class MockNIOElementStreamBackPressureStrategy: NIOAsyncSequenceProducerBackPressureStrategy, @unchecked Sendable {
|
||||
var didYieldCallCount = 0
|
||||
var didYieldHandler: ((Int) -> Bool)?
|
||||
func didYield(bufferDepth: Int) -> Bool {
|
||||
self.didYieldCallCount += 1
|
||||
if let didYieldHandler = self.didYieldHandler {
|
||||
return didYieldHandler(bufferDepth)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var didNextCallCount = 0
|
||||
var didNextHandler: ((Int) -> Bool)?
|
||||
func didConsume(bufferDepth: Int) -> Bool {
|
||||
self.didNextCallCount += 1
|
||||
if let didNextHandler = self.didNextHandler {
|
||||
return didNextHandler(bufferDepth)
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private final class MockNIOBackPressuredStreamSourceDelegate: NIOAsyncSequenceProducerDelegate, @unchecked Sendable {
|
||||
var demandCallCount = 0
|
||||
var demandHandler: (() -> Void)?
|
||||
func produceMore() {
|
||||
self.demandCallCount += 1
|
||||
if let demandHandler = self.demandHandler {
|
||||
return demandHandler()
|
||||
}
|
||||
}
|
||||
|
||||
var didTerminateCallCount = 0
|
||||
var didTerminateHandler: (() -> Void)?
|
||||
func didTerminate() {
|
||||
self.didTerminateCallCount += 1
|
||||
if let didTerminateHandler = self.didTerminateHandler {
|
||||
return didTerminateHandler()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class NIOAsyncSequenceProducerTests: XCTestCase {
|
||||
private var backPressureStrategy: MockNIOElementStreamBackPressureStrategy!
|
||||
private var delegate: MockNIOBackPressuredStreamSourceDelegate!
|
||||
private var sequence: NIOAsyncSequenceProducer<
|
||||
Int,
|
||||
MockNIOElementStreamBackPressureStrategy,
|
||||
MockNIOBackPressuredStreamSourceDelegate
|
||||
>!
|
||||
private var source: NIOAsyncSequenceProducer<
|
||||
Int,
|
||||
MockNIOElementStreamBackPressureStrategy,
|
||||
MockNIOBackPressuredStreamSourceDelegate
|
||||
>.Source!
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
|
||||
self.backPressureStrategy = .init()
|
||||
self.delegate = .init()
|
||||
let result = NIOAsyncSequenceProducer.makeSequence(
|
||||
of: Int.self,
|
||||
backPressureStrategy: self.backPressureStrategy,
|
||||
delegate: self.delegate
|
||||
)
|
||||
self.source = result.source
|
||||
self.sequence = result.sequence
|
||||
}
|
||||
|
||||
override func tearDown() {
|
||||
self.backPressureStrategy = nil
|
||||
self.delegate = nil
|
||||
self.sequence = nil
|
||||
|
||||
super.tearDown()
|
||||
}
|
||||
|
||||
// MARK: - End to end tests
|
||||
|
||||
func testBackPressure() async {
|
||||
let lowWatermark = 2
|
||||
let higherWatermark = 5
|
||||
self.backPressureStrategy.didYieldHandler = { bufferDepth in
|
||||
bufferDepth < higherWatermark
|
||||
}
|
||||
self.backPressureStrategy.didNextHandler = { bufferDepth in
|
||||
bufferDepth < lowWatermark
|
||||
}
|
||||
let iterator = self.sequence.makeAsyncIterator()
|
||||
|
||||
XCTAssertEqual(self.source.yield(contentsOf: [1, 2, 3]), .produceMore)
|
||||
XCTAssertEqual(self.source.yield(contentsOf: [4, 5, 6]), .stopProducing)
|
||||
XCTAssertEqual(self.delegate.demandCallCount, 0)
|
||||
XCTAssertEqualWithoutAutoclosure(await iterator.next(), 1)
|
||||
XCTAssertEqualWithoutAutoclosure(await iterator.next(), 2)
|
||||
XCTAssertEqualWithoutAutoclosure(await iterator.next(), 3)
|
||||
XCTAssertEqualWithoutAutoclosure(await iterator.next(), 4)
|
||||
XCTAssertEqual(self.delegate.demandCallCount, 0)
|
||||
XCTAssertEqualWithoutAutoclosure(await iterator.next(), 5)
|
||||
XCTAssertEqual(self.delegate.demandCallCount, 1)
|
||||
XCTAssertEqual(self.source.yield(contentsOf: [7, 8, 9, 10, 11]), .stopProducing)
|
||||
}
|
||||
|
||||
// MARK: - Yield
|
||||
|
||||
func testYield_whenInitial_andStopDemanding() async {
|
||||
self.backPressureStrategy.didYieldHandler = { _ in false }
|
||||
let result = self.source.yield(contentsOf: [1])
|
||||
|
||||
XCTAssertEqual(self.backPressureStrategy.didYieldCallCount, 1)
|
||||
XCTAssertEqual(result, .stopProducing)
|
||||
}
|
||||
|
||||
func testYield_whenInitial_andDemandMore() async {
|
||||
self.backPressureStrategy.didYieldHandler = { _ in true }
|
||||
let result = self.source.yield(contentsOf: [1])
|
||||
|
||||
XCTAssertEqual(self.backPressureStrategy.didYieldCallCount, 1)
|
||||
XCTAssertEqual(result, .produceMore)
|
||||
}
|
||||
|
||||
func testYield_whenStreaming_andSuspended_andStopDemanding() async throws {
|
||||
self.backPressureStrategy.didYieldHandler = { _ in false }
|
||||
|
||||
// We are registering our demand and sleeping a bit to make
|
||||
// sure the other child task runs when the demand is registered
|
||||
let sequence = try XCTUnwrap(self.sequence)
|
||||
async let element = sequence.first { _ in true }
|
||||
try await Task.sleep(nanoseconds: 1_000_000)
|
||||
XCTAssertEqual(self.backPressureStrategy.didNextCallCount, 1)
|
||||
|
||||
let result = self.source.yield(contentsOf: [1])
|
||||
|
||||
XCTAssertEqual(result, .stopProducing)
|
||||
XCTAssertEqualWithoutAutoclosure(await element, 1)
|
||||
XCTAssertEqual(self.backPressureStrategy.didYieldCallCount, 1)
|
||||
}
|
||||
|
||||
func testYield_whenStreaming_andSuspended_andDemandMore() async throws {
|
||||
self.backPressureStrategy.didYieldHandler = { _ in true }
|
||||
|
||||
// We are registering our demand and sleeping a bit to make
|
||||
// sure the other child task runs when the demand is registered
|
||||
let sequence = try XCTUnwrap(self.sequence)
|
||||
async let element = sequence.first { _ in true }
|
||||
try await Task.sleep(nanoseconds: 1_000_000)
|
||||
XCTAssertEqual(self.backPressureStrategy.didNextCallCount, 1)
|
||||
|
||||
let result = self.source.yield(contentsOf: [1])
|
||||
|
||||
XCTAssertEqual(result, .produceMore)
|
||||
XCTAssertEqualWithoutAutoclosure(await element, 1)
|
||||
XCTAssertEqual(self.backPressureStrategy.didYieldCallCount, 1)
|
||||
}
|
||||
|
||||
func testYieldEmptySequence_whenStreaming_andSuspended_andStopDemanding() async throws {
|
||||
self.backPressureStrategy.didYieldHandler = { _ in false }
|
||||
|
||||
// We are registering our demand and sleeping a bit to make
|
||||
// sure the other child task runs when the demand is registered
|
||||
let sequence = try XCTUnwrap(self.sequence)
|
||||
Task {
|
||||
// Would prefer to use async let _ here but that is not allowed yet
|
||||
_ = await sequence.first { _ in true }
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 1_000_000)
|
||||
XCTAssertEqual(self.backPressureStrategy.didNextCallCount, 1)
|
||||
|
||||
let result = self.source.yield(contentsOf: [])
|
||||
|
||||
XCTAssertEqual(result, .stopProducing)
|
||||
XCTAssertEqual(self.backPressureStrategy.didYieldCallCount, 0)
|
||||
}
|
||||
|
||||
func testYieldEmptySequence_whenStreaming_andSuspended_andDemandMore() async throws {
|
||||
self.backPressureStrategy.didYieldHandler = { _ in true }
|
||||
|
||||
// We are registering our demand and sleeping a bit to make
|
||||
// sure the other child task runs when the demand is registered
|
||||
let sequence = try XCTUnwrap(self.sequence)
|
||||
Task {
|
||||
// Would prefer to use async let _ here but that is not allowed yet
|
||||
_ = await sequence.first { _ in true }
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 1_000_000)
|
||||
XCTAssertEqual(self.backPressureStrategy.didNextCallCount, 1)
|
||||
|
||||
let result = self.source.yield(contentsOf: [])
|
||||
|
||||
XCTAssertEqual(result, .stopProducing)
|
||||
XCTAssertEqual(self.backPressureStrategy.didYieldCallCount, 0)
|
||||
}
|
||||
|
||||
func testYield_whenStreaming_andNotSuspended_andStopDemanding() async throws {
|
||||
self.backPressureStrategy.didYieldHandler = { _ in false }
|
||||
// This transitions the sequence into streaming
|
||||
_ = self.source.yield(contentsOf: [])
|
||||
|
||||
let result = self.source.yield(contentsOf: [1])
|
||||
|
||||
XCTAssertEqual(result, .stopProducing)
|
||||
XCTAssertEqual(self.backPressureStrategy.didYieldCallCount, 2)
|
||||
}
|
||||
|
||||
func testYield_whenStreaming_andNotSuspended_andDemandMore() async throws {
|
||||
self.backPressureStrategy.didYieldHandler = { _ in true }
|
||||
// This transitions the sequence into streaming
|
||||
_ = self.source.yield(contentsOf: [])
|
||||
|
||||
let result = self.source.yield(contentsOf: [1])
|
||||
|
||||
XCTAssertEqual(result, .produceMore)
|
||||
XCTAssertEqual(self.backPressureStrategy.didYieldCallCount, 2)
|
||||
}
|
||||
|
||||
func testYield_whenSourceFinished() async throws {
|
||||
self.source.finish()
|
||||
|
||||
let result = self.source.yield(contentsOf: [1])
|
||||
|
||||
XCTAssertEqual(result, .dropped)
|
||||
XCTAssertEqual(self.backPressureStrategy.didYieldCallCount, 0)
|
||||
}
|
||||
|
||||
// MARK: - Finish
|
||||
|
||||
func testFinish_whenInitial() async {
|
||||
self.source.finish()
|
||||
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
}
|
||||
|
||||
func testFinish_whenStreaming_andSuspended() async throws {
|
||||
// We are registering our demand and sleeping a bit to make
|
||||
// sure the other child task runs when the demand is registered
|
||||
let sequence = try XCTUnwrap(self.sequence)
|
||||
async let element = sequence.first { _ in true }
|
||||
try await Task.sleep(nanoseconds: 1_000_000)
|
||||
|
||||
self.source.finish()
|
||||
|
||||
XCTAssertEqualWithoutAutoclosure(await element, nil)
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
}
|
||||
|
||||
func testFinish_whenStreaming_andNotSuspended_andBufferEmpty() async throws {
|
||||
_ = self.source.yield(contentsOf: [])
|
||||
|
||||
self.source.finish()
|
||||
|
||||
let element = await self.sequence.first { _ in true }
|
||||
XCTAssertNil(element)
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
}
|
||||
|
||||
func testFinish_whenStreaming_andNotSuspended_andBufferNotEmpty() async throws {
|
||||
_ = self.source.yield(contentsOf: [1])
|
||||
|
||||
self.source.finish()
|
||||
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
|
||||
|
||||
let element = await self.sequence.first { _ in true }
|
||||
XCTAssertEqual(element, 1)
|
||||
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
}
|
||||
|
||||
func testFinish_whenFinished() async throws {
|
||||
self.source.finish()
|
||||
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
|
||||
self.source.finish()
|
||||
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
}
|
||||
|
||||
// MARK: - Task cancel
|
||||
|
||||
func testTaskCancel_whenStreaming_andSuspended() async throws {
|
||||
// We are registering our demand and sleeping a bit to make
|
||||
// sure our task runs when the demand is registered
|
||||
let sequence = try XCTUnwrap(self.sequence)
|
||||
let task: Task<Int?, Never> = Task {
|
||||
let iterator = sequence.makeAsyncIterator()
|
||||
return await iterator.next()
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 1_000_000)
|
||||
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
|
||||
task.cancel()
|
||||
let value = await task.value
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
XCTAssertNil(value)
|
||||
}
|
||||
|
||||
func testTaskCancel_whenStreaming_andNotSuspended() async throws {
|
||||
// We are registering our demand and sleeping a bit to make
|
||||
// sure our task runs when the demand is registered
|
||||
let sequence = try XCTUnwrap(self.sequence)
|
||||
let task: Task<Int?, Never> = Task {
|
||||
let iterator = sequence.makeAsyncIterator()
|
||||
return await iterator.next()
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 1_000_000)
|
||||
|
||||
_ = self.source.yield(contentsOf: [1])
|
||||
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
|
||||
task.cancel()
|
||||
let value = await task.value
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
XCTAssertEqual(value, 1)
|
||||
}
|
||||
|
||||
func testTaskCancel_whenSourceFinished() async throws {
|
||||
// We are registering our demand and sleeping a bit to make
|
||||
// sure our task runs when the demand is registered
|
||||
let sequence = try XCTUnwrap(self.sequence)
|
||||
let task: Task<Int?, Never> = Task {
|
||||
let iterator = sequence.makeAsyncIterator()
|
||||
return await iterator.next()
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 1_000_000)
|
||||
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
|
||||
self.source.finish()
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
task.cancel()
|
||||
let value = await task.value
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
XCTAssertNil(value)
|
||||
}
|
||||
|
||||
func testTaskCancel_whenStreaming_andTaskIsAlreadyCancelled() async throws {
|
||||
let sequence = try XCTUnwrap(self.sequence)
|
||||
let task: Task<Int?, Never> = Task {
|
||||
// We are sleeping here to allow some time for us to cancel the task.
|
||||
// Once the Task is cancelled we will call `next()`
|
||||
try? await Task.sleep(nanoseconds: 1_000_000)
|
||||
let iterator = sequence.makeAsyncIterator()
|
||||
return await iterator.next()
|
||||
}
|
||||
|
||||
task.cancel()
|
||||
|
||||
let value = await task.value
|
||||
|
||||
XCTAssertNil(value)
|
||||
}
|
||||
|
||||
// MARK: - Next
|
||||
|
||||
func testNext_whenInitial_whenDemand() async throws {
|
||||
self.backPressureStrategy.didNextHandler = { _ in true }
|
||||
// We are registering our demand and sleeping a bit to make
|
||||
// sure the other child task runs when the demand is registered
|
||||
let sequence = try XCTUnwrap(self.sequence)
|
||||
Task {
|
||||
// Would prefer to use async let _ here but that is not allowed yet
|
||||
_ = await sequence.first { _ in true }
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 1_000_000)
|
||||
|
||||
XCTAssertEqual(self.backPressureStrategy.didNextCallCount, 1)
|
||||
XCTAssertEqual(self.delegate.demandCallCount, 1)
|
||||
}
|
||||
|
||||
func testNext_whenInitial_whenNoDemand() async throws {
|
||||
self.backPressureStrategy.didNextHandler = { _ in false }
|
||||
// We are registering our demand and sleeping a bit to make
|
||||
// sure the other child task runs when the demand is registered
|
||||
let sequence = try XCTUnwrap(self.sequence)
|
||||
Task {
|
||||
// Would prefer to use async let _ here but that is not allowed yet
|
||||
_ = await sequence.first { _ in true }
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 1_000_000)
|
||||
|
||||
XCTAssertEqual(self.backPressureStrategy.didNextCallCount, 1)
|
||||
XCTAssertEqual(self.delegate.demandCallCount, 0)
|
||||
}
|
||||
|
||||
func testNext_whenStreaming_whenEmptyBuffer_whenDemand() async throws {
|
||||
self.backPressureStrategy.didNextHandler = { _ in true }
|
||||
_ = self.source.yield(contentsOf: [])
|
||||
|
||||
// We are registering our demand and sleeping a bit to make
|
||||
// sure the other child task runs when the demand is registered
|
||||
let sequence = try XCTUnwrap(self.sequence)
|
||||
Task {
|
||||
// Would prefer to use async let _ here but that is not allowed yet
|
||||
_ = await sequence.first { _ in true }
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 1_000_000)
|
||||
|
||||
XCTAssertEqual(self.backPressureStrategy.didNextCallCount, 1)
|
||||
XCTAssertEqual(self.delegate.demandCallCount, 1)
|
||||
}
|
||||
|
||||
func testNext_whenStreaming_whenEmptyBuffer_whenNoDemand() async throws {
|
||||
self.backPressureStrategy.didNextHandler = { _ in false }
|
||||
_ = self.source.yield(contentsOf: [])
|
||||
|
||||
// We are registering our demand and sleeping a bit to make
|
||||
// sure the other child task runs when the demand is registered
|
||||
let sequence = try XCTUnwrap(self.sequence)
|
||||
Task {
|
||||
// Would prefer to use async let _ here but that is not allowed yet
|
||||
_ = await sequence.first { _ in true }
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 1_000_000)
|
||||
|
||||
XCTAssertEqual(self.backPressureStrategy.didNextCallCount, 1)
|
||||
XCTAssertEqual(self.delegate.demandCallCount, 0)
|
||||
}
|
||||
|
||||
func testNext_whenStreaming_whenNotEmptyBuffer_whenNoDemand() async throws {
|
||||
self.backPressureStrategy.didNextHandler = { _ in false }
|
||||
_ = self.source.yield(contentsOf: [1])
|
||||
|
||||
let element = await self.sequence.first { _ in true }
|
||||
|
||||
XCTAssertEqual(element, 1)
|
||||
XCTAssertEqual(self.backPressureStrategy.didNextCallCount, 1)
|
||||
XCTAssertEqual(self.delegate.demandCallCount, 0)
|
||||
}
|
||||
|
||||
func testNext_whenStreaming_whenNotEmptyBuffer_whenNewDemand() async throws {
|
||||
self.backPressureStrategy.didNextHandler = { _ in true }
|
||||
_ = self.source.yield(contentsOf: [1])
|
||||
|
||||
let element = await self.sequence.first { _ in true }
|
||||
|
||||
XCTAssertEqual(element, 1)
|
||||
XCTAssertEqual(self.backPressureStrategy.didNextCallCount, 1)
|
||||
XCTAssertEqual(self.delegate.demandCallCount, 1)
|
||||
}
|
||||
|
||||
func testNext_whenStreaming_whenNotEmptyBuffer_whenNewAndOutstandingDemand() async throws {
|
||||
self.backPressureStrategy.didNextHandler = { _ in true }
|
||||
self.backPressureStrategy.didYieldHandler = { _ in true }
|
||||
|
||||
_ = self.source.yield(contentsOf: [1])
|
||||
XCTAssertEqual(self.delegate.demandCallCount, 0)
|
||||
|
||||
let element = await self.sequence.first { _ in true }
|
||||
|
||||
XCTAssertEqual(element, 1)
|
||||
XCTAssertEqual(self.backPressureStrategy.didNextCallCount, 1)
|
||||
XCTAssertEqual(self.delegate.demandCallCount, 0)
|
||||
}
|
||||
|
||||
func testNext_whenSourceFinished() async throws {
|
||||
_ = self.source.yield(contentsOf: [1, 2])
|
||||
self.source.finish()
|
||||
|
||||
var elements = [Int]()
|
||||
|
||||
for await element in self.sequence {
|
||||
elements.append(element)
|
||||
}
|
||||
|
||||
XCTAssertEqual(elements, [1, 2])
|
||||
}
|
||||
|
||||
// MARK: - SequenceDeinitialized
|
||||
|
||||
func testSequenceDeinitialized() async {
|
||||
self.sequence = nil
|
||||
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
}
|
||||
|
||||
func testSequenceDeinitialized_whenIteratorReferenced() async {
|
||||
var iterator = self.sequence?.makeAsyncIterator()
|
||||
|
||||
self.sequence = nil
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
|
||||
|
||||
XCTAssertNotNil(iterator)
|
||||
iterator = nil
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
}
|
||||
|
||||
// MARK: - IteratorDeinitialized
|
||||
|
||||
func testIteratorDeinitialized_whenSequenceReferenced() async {
|
||||
var iterator = self.sequence?.makeAsyncIterator()
|
||||
|
||||
XCTAssertNotNil(iterator)
|
||||
iterator = nil
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
|
||||
self.sequence = nil
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
}
|
||||
|
||||
func testIteratorDeinitialized_whenSequenceFinished() {
|
||||
self.source.finish()
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
|
||||
var iterator = self.sequence?.makeAsyncIterator()
|
||||
|
||||
XCTAssertNotNil(iterator)
|
||||
iterator = nil
|
||||
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
}
|
||||
|
||||
func testIteratorDeinitialized_whenStreaming() {
|
||||
_ = self.source.yield(contentsOf: [1])
|
||||
var iterator = self.sequence?.makeAsyncIterator()
|
||||
|
||||
XCTAssertNotNil(iterator)
|
||||
iterator = nil
|
||||
|
||||
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
|
||||
}
|
||||
}
|
||||
|
||||
// This is needed until async let is supported to be used in autoclosures
|
||||
fileprivate func XCTAssertEqualWithoutAutoclosure<T>(
|
||||
_ expression1: T,
|
||||
_ expression2: T,
|
||||
_ message: @autoclosure () -> String = "",
|
||||
file: StaticString = #filePath,
|
||||
line: UInt = #line
|
||||
) where T: Equatable {
|
||||
let result = expression1 == expression2
|
||||
XCTAssertTrue(result, message(), file: file, line: line)
|
||||
}
|
||||
|
||||
#endif
|
||||
Reference in new issue
Block a user