Files
swift-async-algorithms/Sources/AsyncAlgorithms/Merge2StateMachine.swift
T
Franz Busch 314b10c634 Remove AsyncIterator: Sendable requirement from merge (#185)
* Remove `AsyncIterator: Sendable` requirement from merge

# Motivation
Currently a lot of the operator implementations in here that consume other `AsyncSequence`s require the `AsyncIterator` to be `Sendable`. This is mostly due to the fact that we are calling `makeAsyncIterator` on the upstream `AsyncSequence` and then pass that iterator around to various newly spawned `Task`s. This has two downsides:
1. It only allows users to use operators like `merge` if their `AsyncSequence.AsyncIterator` is `Sendable`
2. In merge we are creating new `Task`s for every new demand. Creating `Task`s is not cheap.

My main goal of this PR was to remove the `Sendable` constraint from `merge`.

# Modification
This PR overhauls the complete inner workings of the `AsyncMerge2Sequence`. It does a couple of things:
1. The main change is that instead of creating new `Task`s for every demand, we are creating one `Task` when the `AsyncIterator` is created. This task has as child task for every upstream sequence.
2. When calling `next` we are signalling the child tasks to demand from the upstream
3. A new state machine that is synchronizing the various concurrent operations that can happen
4. Handling cancellation since we are creating a bunch of continuations.

# Result
In the end, this PR swaps the implementation of `AsyncMerge2Sequence` and drops the `Sendable` constraint and passes all tests. Furthermore, on my local performance testing I saw up 50% speed increase in throughput.

# Open points
1. I need to make this sequence re-throwing but before going down that rabbit whole I wanna get buy-in on the implementation.
2. We should discuss and document if `merge` and other operators are hot or cold, i.e. if they only request if they got downstream demand
3. I need to switch `AsyncMerge3Sequence` over to the same iplementation

* Split logic into multiple files, adapt merge3 and incorporate PR feedback

* Add more tests and fix upstream throw behaviour

* Remove internal class from the sequence

* Setup task after first next

* Remove unnecessary tests
2022-10-10 08:34:50 -07:00

163 lines
5.1 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
struct Merge2StateMachine<Base1: AsyncSequence, Base2: AsyncSequence>: Sendable where Base1.AsyncIterator: Sendable, Base2.AsyncIterator: Sendable, Base1.Element: Sendable, Base2.Element: Sendable {
typealias Element1 = Base1.Element
typealias Element2 = Base2.Element
let iter1TerminatesOnNil : Bool
let iter2terminatesOnNil : Bool
enum Partial: @unchecked Sendable {
case first(Result<Element1?, Error>, Base1.AsyncIterator)
case second(Result<Element2?, Error>, Base2.AsyncIterator)
}
enum Either {
case first(Base1.Element)
case second(Base2.Element)
}
var state: (PartialIteration<Base1.AsyncIterator, Partial>, PartialIteration<Base2.AsyncIterator, Partial>)
init(_ iterator1: Base1.AsyncIterator, terminatesOnNil iter1TerminatesOnNil: Bool = false, _ iterator2: Base2.AsyncIterator, terminatesOnNil iter2terminatesOnNil: Bool = false) {
self.iter1TerminatesOnNil = iter1TerminatesOnNil
self.iter2terminatesOnNil = iter2terminatesOnNil
state = (.idle(iterator1), .idle(iterator2))
}
mutating func apply(_ task1: Task<Merge2StateMachine<Base1, Base2>.Partial, Never>?, _ task2: Task<Merge2StateMachine<Base1, Base2>.Partial, Never>?) async rethrows -> Either? {
switch await Task.select([task1, task2].compactMap ({ $0 })).value {
case .first(let result, let iterator):
do {
guard let value = try state.0.resolve(result, iterator) else {
if iter1TerminatesOnNil {
state.1.cancel()
return nil
}
return try await next()
}
return .first(value)
} catch {
state.1.cancel()
throw error
}
case .second(let result, let iterator):
do {
guard let value = try state.1.resolve(result, iterator) else {
if iter2terminatesOnNil {
state.0.cancel()
return nil
}
return try await next()
}
return .second(value)
} catch {
state.0.cancel()
throw error
}
}
}
func first(_ iterator1: Base1.AsyncIterator) -> Task<Partial, Never> {
Task {
var iter = iterator1
do {
let value = try await iter.next()
return .first(.success(value), iter)
} catch {
return .first(.failure(error), iter)
}
}
}
func second(_ iterator2: Base2.AsyncIterator) -> Task<Partial, Never> {
Task {
var iter = iterator2
do {
let value = try await iter.next()
return .second(.success(value), iter)
} catch {
return .second(.failure(error), iter)
}
}
}
/// Advances to the next element and returns it or `nil` if no next element exists.
mutating func next() async rethrows -> Either? {
if Task.isCancelled {
state.0.cancel()
state.1.cancel()
return nil
}
switch state {
case (.idle(let iterator1), .idle(let iterator2)):
let task1 = first(iterator1)
let task2 = second(iterator2)
state = (.pending(task1), .pending(task2))
return try await apply(task1, task2)
case (.idle(let iterator1), .pending(let task2)):
let task1 = first(iterator1)
state = (.pending(task1), .pending(task2))
return try await apply(task1, task2)
case (.pending(let task1), .idle(let iterator2)):
let task2 = second(iterator2)
state = (.pending(task1), .pending(task2))
return try await apply(task1, task2)
case (.idle(var iterator1), .terminal):
do {
if let value = try await iterator1.next() {
state = (.idle(iterator1), .terminal)
return .first(value)
} else {
state = (.terminal, .terminal)
return nil
}
} catch {
state = (.terminal, .terminal)
throw error
}
case (.terminal, .idle(var iterator2)):
do {
if let value = try await iterator2.next() {
state = (.terminal, .idle(iterator2))
return .second(value)
} else {
state = (.terminal, .terminal)
return nil
}
} catch {
state = (.terminal, .terminal)
throw error
}
case (.terminal, .pending(let task2)):
return try await apply(nil, task2)
case (.pending(let task1), .pending(let task2)):
return try await apply(task1, task2)
case (.pending(let task1), .terminal):
return try await apply(task1, nil)
case (.terminal, .terminal):
return nil
}
}
}
extension Merge2StateMachine.Either where Base1.Element == Base2.Element {
var value : Base1.Element {
switch self {
case .first(let val):
return val
case .second(let val):
return val
}
}
}