1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
final class MergeStorage<
Base1: AsyncSequence,
Base2: AsyncSequence,
Base3: AsyncSequence
>: @unchecked Sendable where
Base1.Element == Base2.Element,
Base1.Element == Base3.Element,
Base1: Sendable, Base2: Sendable, Base3: Sendable,
Base1.Element: Sendable
{
typealias Element = Base1.Element
/// The lock that protects our state.
private let lock = Lock.allocate()
/// The state machine.
private var stateMachine: MergeStateMachine<Base1, Base2, Base3>
init(
base1: Base1,
base2: Base2,
base3: Base3?
) {
stateMachine = .init(base1: base1, base2: base2, base3: base3)
}
deinit {
self.lock.deinitialize()
}
func iteratorDeinitialized() {
let action = lock.withLock { self.stateMachine.iteratorDeinitialized() }
switch action {
case let .cancelTaskAndUpstreamContinuations(
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
case .none:
break
}
}
func next() async rethrows -> Element? {
// We need to handle cancellation here because we are creating a continuation
// and because we need to cancel the `Task` we created to consume the upstream
try await withTaskCancellationHandler {
self.lock.lock()
let action = self.stateMachine.next()
switch action {
case .startTaskAndSuspendDownstreamTask(let base1, let base2, let base3):
self.startTask(
stateMachine: &self.stateMachine,
base1: base1,
base2: base2,
base3: base3
)
// It is safe to hold the lock across this method
// since the closure is guaranteed to be run straight away
return try await withUnsafeThrowingContinuation { continuation in
let action = self.stateMachine.next(for: continuation)
self.lock.unlock()
switch action {
case let .resumeUpstreamContinuations(upstreamContinuations):
// This is signalling the child tasks that are consuming the upstream
// sequences to signal demand.
upstreamContinuations.forEach { $0.resume(returning: ()) }
}
}
case let .returnElement(element):
self.lock.unlock()
return try element._rethrowGet()
case .returnNil:
self.lock.unlock()
return nil
case let .throwError(error):
self.lock.unlock()
throw error
case .suspendDownstreamTask:
// It is safe to hold the lock across this method
// since the closure is guaranteed to be run straight away
return try await withUnsafeThrowingContinuation { continuation in
let action = self.stateMachine.next(for: continuation)
self.lock.unlock()
switch action {
case let .resumeUpstreamContinuations(upstreamContinuations):
// This is signalling the child tasks that are consuming the upstream
// sequences to signal demand.
upstreamContinuations.forEach { $0.resume(returning: ()) }
}
}
}
} onCancel: {
let action = self.lock.withLock { self.stateMachine.cancelled() }
switch action {
case let .resumeDownstreamContinuationWithNilAndCancelTaskAndUpstreamContinuations(
downstreamContinuation,
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(returning: nil)
case let .cancelTaskAndUpstreamContinuations(
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
case .none:
break
}
}
}
private func startTask(stateMachine: inout MergeStateMachine<Base1, Base2, Base3>, base1: Base1, base2: Base2, base3: Base3?) {
// This creates a new `Task` that is iterating the upstream
// sequences. We must store it to cancel it at the right times.
let task = Task {
await withThrowingTaskGroup(of: Void.self) { group in
self.iterateAsyncSequence(base1, in: &group)
self.iterateAsyncSequence(base2, in: &group)
// Copy from the above just using the base3 sequence
if let base3 = base3 {
self.iterateAsyncSequence(base3, in: &group)
}
while !group.isEmpty {
do {
try await group.next()
} catch {
// One of the upstream sequences threw an error
let action = self.lock.withLock {
self.stateMachine.upstreamThrew(error)
}
switch action {
case let .resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations(
downstreamContinuation,
error,
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(throwing: error)
case let .cancelTaskAndUpstreamContinuations(
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
case .none:
break
}
group.cancelAll()
}
}
}
}
// We need to inform our state machine that we started the Task
stateMachine.taskStarted(task)
}
private func iterateAsyncSequence<AsyncSequence: _Concurrency.AsyncSequence>(
_ base: AsyncSequence,
in taskGroup: inout ThrowingTaskGroup<Void, Error>
) where AsyncSequence.Element == Base1.Element, AsyncSequence: Sendable {
// For each upstream sequence we are adding a child task that
// is consuming the upstream sequence
taskGroup.addTask {
var iterator = base.makeAsyncIterator()
// This is our upstream consumption loop
loop: while true {
// We are creating a continuation before requesting the next
// element from upstream. This continuation is only resumed
// if the downstream consumer called `next` to signal his demand.
try await withUnsafeThrowingContinuation { continuation in
let action = self.lock.withLock {
self.stateMachine.childTaskSuspended(continuation)
}
switch action {
case let .resumeContinuation(continuation):
// This happens if there is outstanding demand
// and we need to demand from upstream right away
continuation.resume(returning: ())
case let .resumeContinuationWithError(continuation, error):
// This happens if another upstream already failed or if
// the task got cancelled.
continuation.resume(throwing: error)
case .none:
break
}
}
// We got signalled from the downstream that we have demand so let's
// request a new element from the upstream
if let element1 = try await iterator.next() {
let action = self.lock.withLock {
self.stateMachine.elementProduced(element1)
}
switch action {
case let .resumeContinuation(continuation, element):
// We had an outstanding demand and where the first
// upstream to produce an element so we can forward it to
// the downstream
continuation.resume(returning: element)
case .none:
break
}
} else {
// The upstream returned `nil` which indicates that it finished
let action = self.lock.withLock {
self.stateMachine.upstreamFinished()
}
// All of this is mostly cleanup around the Task and the outstanding
// continuations used for signalling.
switch action {
case let .resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations(
downstreamContinuation,
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(returning: nil)
break loop
case let .cancelTaskAndUpstreamContinuations(
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
break loop
case .none:
break loop
}
}
}
}
}
}
|