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 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
final class DebounceStorage<Base: AsyncSequence & Sendable, C: Clock>: Sendable where Base.Element: Sendable {
typealias Element = Base.Element
/// The state machine protected with a lock.
private let stateMachine: ManagedCriticalState<DebounceStateMachine<Base, C>>
/// The interval to debounce.
private let interval: C.Instant.Duration
/// The tolerance for the clock.
private let tolerance: C.Instant.Duration?
/// The clock.
private let clock: C
init(base: Base, interval: C.Instant.Duration, tolerance: C.Instant.Duration?, clock: C) {
self.stateMachine = .init(.init(base: base, clock: clock, interval: interval))
self.interval = interval
self.tolerance = tolerance
self.clock = clock
}
func iteratorDeinitialized() {
let action = self.stateMachine.withCriticalRegion { $0.iteratorDeinitialized() }
switch action {
case .cancelTaskAndUpstreamAndClockContinuations(
let task,
let upstreamContinuation,
let clockContinuation
):
upstreamContinuation?.resume(throwing: CancellationError())
clockContinuation?.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
return try await withTaskCancellationHandler {
// We always suspend since we can never return an element right away
let result: Result<Element?, Error> = await withUnsafeContinuation { continuation in
let action: DebounceStateMachine<Base, C>.NextAction? = self.stateMachine.withCriticalRegion {
let action = $0.next(for: continuation)
switch action {
case .startTask(let base):
self.startTask(
stateMachine: &$0,
base: base,
downstreamContinuation: continuation
)
return nil
case .resumeUpstreamContinuation:
return action
case .resumeUpstreamAndClockContinuation:
return action
case .resumeDownstreamContinuationWithNil:
return action
case .resumeDownstreamContinuationWithError:
return action
}
}
switch action {
case .startTask:
// We are handling the startTask in the lock already because we want to avoid
// other inputs interleaving while starting the task
fatalError("Internal inconsistency")
case .resumeUpstreamContinuation(let upstreamContinuation):
// This is signalling the upstream task that is consuming the upstream
// sequence to signal demand.
upstreamContinuation?.resume(returning: ())
case .resumeUpstreamAndClockContinuation(let upstreamContinuation, let clockContinuation, let deadline):
// This is signalling the upstream task that is consuming the upstream
// sequence to signal demand and start the clock task.
upstreamContinuation?.resume(returning: ())
clockContinuation?.resume(returning: deadline)
case .resumeDownstreamContinuationWithNil(let continuation):
continuation.resume(returning: .success(nil))
case .resumeDownstreamContinuationWithError(let continuation, let error):
continuation.resume(returning: .failure(error))
case .none:
break
}
}
return try result._rethrowGet()
} onCancel: {
let action = self.stateMachine.withCriticalRegion { $0.cancelled() }
switch action {
case .resumeDownstreamContinuationWithNilAndCancelTaskAndUpstreamAndClockContinuation(
let downstreamContinuation,
let task,
let upstreamContinuation,
let clockContinuation
):
upstreamContinuation?.resume(throwing: CancellationError())
clockContinuation?.resume(throwing: CancellationError())
task.cancel()
downstreamContinuation.resume(returning: .success(nil))
case .none:
break
}
}
}
private func startTask(
stateMachine: inout DebounceStateMachine<Base, C>,
base: Base,
downstreamContinuation: UnsafeContinuation<Result<Base.Element?, Error>, Never>
) {
let task = Task {
await withThrowingTaskGroup(of: Void.self) { group in
// The task that consumes the upstream sequence
group.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
// and until the Clock sleep finished.
try await withUnsafeThrowingContinuation { continuation in
let action = self.stateMachine.withCriticalRegion { $0.upstreamTaskSuspended(continuation) }
switch action {
case .resumeContinuation(let continuation):
// This happens if there is outstanding demand
// and we need to demand from upstream right away
continuation.resume(returning: ())
case .resumeContinuationWithError(let continuation, let error):
// This happens 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 element = try await iterator.next() {
let action = self.stateMachine.withCriticalRegion {
let deadline = self.clock.now.advanced(by: self.interval)
return $0.elementProduced(element, deadline: deadline)
}
switch action {
case .resumeClockContinuation(let clockContinuation, let deadline):
clockContinuation?.resume(returning: deadline)
case .none:
break
}
} else {
// The upstream returned `nil` which indicates that it finished
let action = self.stateMachine.withCriticalRegion { $0.upstreamFinished() }
// All of this is mostly cleanup around the Task and the outstanding
// continuations used for signalling.
switch action {
case .cancelTaskAndClockContinuation(let task, let clockContinuation):
task.cancel()
clockContinuation?.resume(throwing: CancellationError())
break loop
case .resumeContinuationWithNilAndCancelTaskAndUpstreamAndClockContinuation(
let downstreamContinuation,
let task,
let upstreamContinuation,
let clockContinuation
):
upstreamContinuation?.resume(throwing: CancellationError())
clockContinuation?.resume(throwing: CancellationError())
task.cancel()
downstreamContinuation.resume(returning: .success(nil))
break loop
case .resumeContinuationWithElementAndCancelTaskAndUpstreamAndClockContinuation(
let downstreamContinuation,
let element,
let task,
let upstreamContinuation,
let clockContinuation
):
upstreamContinuation?.resume(throwing: CancellationError())
clockContinuation?.resume(throwing: CancellationError())
task.cancel()
downstreamContinuation.resume(returning: .success(element))
break loop
case .none:
break loop
}
}
}
}
group.addTask {
// This is our clock scheduling loop
loop: while true {
do {
// We are creating a continuation sleeping on the Clock.
// This continuation is only resumed if the downstream consumer called `next`.
let deadline: C.Instant = try await withUnsafeThrowingContinuation { continuation in
let action = self.stateMachine.withCriticalRegion { $0.clockTaskSuspended(continuation) }
switch action {
case .resumeContinuation(let continuation, let deadline):
// This happens if there is outstanding demand
// and we need to demand from upstream right away
continuation.resume(returning: deadline)
case .resumeContinuationWithError(let continuation, let error):
// This happens if the task got cancelled.
continuation.resume(throwing: error)
case .none:
break
}
}
try await self.clock.sleep(until: deadline, tolerance: self.tolerance)
let action = self.stateMachine.withCriticalRegion { $0.clockSleepFinished() }
switch action {
case .resumeDownstreamContinuation(let downstreamContinuation, let element):
downstreamContinuation.resume(returning: .success(element))
case .none:
break
}
} catch {
// The only error that we expect is the `CancellationError`
// thrown from the Clock.sleep or from the withUnsafeContinuation.
// This happens if we are cleaning everything up. We can just drop that error and break our loop
precondition(error is CancellationError, "Received unexpected error \(error) in the Clock loop")
break loop
}
}
}
while !group.isEmpty {
do {
try await group.next()
} catch {
// One of the upstream sequences threw an error
let action = self.stateMachine.withCriticalRegion { stateMachine in
stateMachine.upstreamThrew(error)
}
switch action {
case .resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuation(
let downstreamContinuation,
let error,
let task,
let upstreamContinuation,
let clockContinuation
):
upstreamContinuation?.resume(throwing: CancellationError())
clockContinuation?.resume(throwing: CancellationError())
task.cancel()
downstreamContinuation.resume(returning: .failure(error))
case .cancelTaskAndClockContinuation(
let task,
let clockContinuation
):
clockContinuation?.resume(throwing: CancellationError())
task.cancel()
case .none:
break
}
}
group.cancelAll()
}
}
}
stateMachine.taskStarted(task, downstreamContinuation: downstreamContinuation)
}
}
|