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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
|
//
// AsyncOperation.swift
// Operations
//
// Created by pronebird on 01/06/2020.
// Copyright © 2020 Mullvad VPN AB. All rights reserved.
//
import Foundation
@objc private enum State: Int, Comparable, CustomStringConvertible {
case initialized
case pending
case evaluatingConditions
case ready
case executing
case finished
static func < (lhs: State, rhs: State) -> Bool {
lhs.rawValue < rhs.rawValue
}
var description: String {
switch self {
case .initialized:
return "initialized"
case .pending:
return "pending"
case .evaluatingConditions:
return "evaluatingConditions"
case .ready:
return "ready"
case .executing:
return "executing"
case .finished:
return "finished"
}
}
}
/// A base implementation of an asynchronous operation
open class AsyncOperation: Operation, @unchecked Sendable {
/// Mutex lock used for guarding critical sections of operation lifecycle.
private let operationLock = NSRecursiveLock()
/// Mutex lock used to guard `state` and `isCancelled` properties.
///
/// This lock must not encompass KVO hooks such as `willChangeValue` and `didChangeValue` to
/// prevent deadlocks, since KVO observers may synchronously query the operation state on a
/// different thread.
///
/// `operationLock` should be used along with `stateLock` to ensure internal state consistency
/// when multiple access to `state` or `isCancelled` is necessary, such as when testing
/// the value before modifying it.
private let stateLock = NSRecursiveLock()
/// Backing variable for `state`.
/// Access must be guarded with `stateLock`.
private var _state: State = .initialized
/// Backing variable for `_isCancelled`.
/// Access must be guarded with `stateLock`.
private var __isCancelled = false
/// Backing variable for `error`.
/// Access must be guarded with `stateLock`.
private var __error: Error?
/// Operation state.
@objc private var state: State {
get {
stateLock.lock()
defer { stateLock.unlock() }
return _state
}
set(newState) {
willChangeValue(for: \.state)
stateLock.lock()
assert(_state < newState)
_state = newState
stateLock.unlock()
didChangeValue(for: \.state)
}
}
private var _isCancelled: Bool {
get {
stateLock.lock()
defer { stateLock.unlock() }
return __isCancelled
}
set {
willChangeValue(for: \.isCancelled)
stateLock.lock()
__isCancelled = newValue
stateLock.unlock()
didChangeValue(for: \.isCancelled)
}
}
private var _error: Error? {
get {
stateLock.lock()
defer { stateLock.unlock() }
return __error
}
set {
stateLock.lock()
defer { stateLock.unlock() }
__error = newValue
}
}
public var error: Error? {
_error
}
dynamic override public final var isReady: Bool {
stateLock.lock()
defer { stateLock.unlock() }
// super.isReady should turn true when all dependencies are satisfied.
guard super.isReady else {
return false
}
// Mark operation ready when cancelled, so that operation queue could flush it faster.
guard !__isCancelled else {
return true
}
switch _state {
case .initialized, .pending, .evaluatingConditions:
return false
case .ready, .executing, .finished:
return true
}
}
override public final var isExecuting: Bool {
state == .executing
}
override public final var isFinished: Bool {
state == .finished
}
override public final var isCancelled: Bool {
_isCancelled
}
override public final var isAsynchronous: Bool {
true
}
// MARK: - Observers
private var _observers: [OperationObserver] = []
public final var observers: [OperationObserver] {
operationLock.lock()
defer { operationLock.unlock() }
return _observers
}
public final func addObserver(_ observer: OperationObserver) {
operationLock.lock()
assert(state < .executing)
_observers.append(observer)
operationLock.unlock()
observer.didAttach(to: self)
}
// MARK: - Conditions
private var _conditions: [OperationCondition] = []
public final var conditions: [OperationCondition] {
operationLock.lock()
defer { operationLock.unlock() }
return _conditions
}
public func addCondition(_ condition: OperationCondition) {
operationLock.lock()
defer { operationLock.unlock() }
assert(state < .evaluatingConditions)
_conditions.append(condition)
}
private func evaluateConditions() {
guard !_conditions.isEmpty else {
state = .ready
return
}
state = .evaluatingConditions
nonisolated(unsafe) var results = [Bool](repeating: false, count: _conditions.count)
let group = DispatchGroup()
for (index, condition) in _conditions.enumerated() {
group.enter()
condition.evaluate(for: self) { [weak self] isSatisfied in
self?.dispatchQueue.async {
results[index] = isSatisfied
group.leave()
}
}
}
group.notify(queue: dispatchQueue) { [weak self] in
self?.didEvaluateConditions(results)
}
}
private func didEvaluateConditions(_ results: [Bool]) {
operationLock.lock()
defer { operationLock.unlock() }
guard state < .ready else { return }
let conditionsSatisfied = results.allSatisfy { $0 }
if !conditionsSatisfied {
cancel()
}
state = .ready
}
// MARK: -
public let dispatchQueue: DispatchQueue
private var isReadyObserver: NSKeyValueObservation?
public init(dispatchQueue: DispatchQueue? = nil) {
self.dispatchQueue = dispatchQueue ?? DispatchQueue(label: "AsyncOperation.dispatchQueue")
super.init()
isReadyObserver = observe(\.isReady, options: []) { operation, _ in
operation.checkReadiness()
}
}
deinit {
// Clear the observer when the operation is deallocated to avoid leaking memory.
isReadyObserver = nil
}
// MARK: - KVO
@objc class func keyPathsForValuesAffectingIsReady() -> Set<String> {
[#keyPath(state)]
}
@objc class func keyPathsForValuesAffectingIsExecuting() -> Set<String> {
[#keyPath(state)]
}
@objc class func keyPathsForValuesAffectingIsFinished() -> Set<String> {
[#keyPath(state)]
}
// MARK: - Lifecycle
override public final func start() {
let currentQueue = OperationQueue.current
let underlyingQueue = currentQueue?.underlyingQueue
if underlyingQueue == dispatchQueue {
_start()
} else {
dispatchQueue.async {
self._start()
}
}
}
private func _start() {
operationLock.lock()
if _isCancelled {
notifyCancellation()
operationLock.unlock()
finish(error: OperationError.cancelled)
} else {
state = .executing
for observer in _observers {
observer.operationDidStart(self)
}
operationLock.unlock()
main()
}
}
override open func main() {
// Override in subclasses
}
override public final func cancel() {
operationLock.lock()
if !_isCancelled {
_isCancelled = true
// Notify observers only when executing, otherwise `_start()` will take care of doing this as soon
// as operation is ready to execute.
if state == .executing {
dispatchQueue.async {
self.notifyCancellation()
}
}
}
operationLock.unlock()
super.cancel()
}
public func finish() {
finish(error: nil)
}
public func finish(error: Error?) {
guard tryFinish(error: error) else { return }
dispatchQueue.async {
self.operationDidFinish()
let anError = self.error
for observer in self.observers {
observer.operationDidFinish(self, error: anError)
}
}
}
// MARK: - Private
internal func didEnqueue() {
operationLock.lock()
defer { operationLock.unlock() }
guard state == .initialized else {
return
}
state = .pending
}
private func checkReadiness() {
operationLock.lock()
defer { operationLock.unlock() }
if state == .pending, !_isCancelled, super.isReady {
evaluateConditions()
}
}
private func tryFinish(error: Error?) -> Bool {
operationLock.lock()
defer { operationLock.unlock() }
guard state < .finished else { return false }
_error = error
state = .finished
return true
}
private func notifyCancellation() {
operationDidCancel()
for observer in _observers {
observer.operationDidCancel(self)
}
}
// MARK: - Subclass overrides
open func operationDidCancel() {
// Override in subclasses.
}
open func operationDidFinish() {
// Override in subclasses.
}
}
extension AsyncOperation: OperationBlockObserverSupport {}
extension Operation {
public func addDependencies(_ dependencies: [Operation]) {
for dependency in dependencies {
addDependency(dependency)
}
}
}
|