-
Notifications
You must be signed in to change notification settings - Fork 109
/
PromisedReply.swift
277 lines (255 loc) · 8.04 KB
/
PromisedReply.swift
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
//
// PromisedReply.swift
// ios
//
// Copyright © 2019 Tinode. All rights reserved.
//
import Foundation
enum PromisedReplyError: Error {
case illegalStateError(String)
}
// Inspired by https://github.com/uber/swift-concurrency/blob/master/Sources/Concurrency/CountDownLatch.swift
private class CountDownLatch {
private let condition = NSCondition()
private var conditionCount: Int
public init(count: Int) {
assert(count >= 0, "CountDownLatch must have an initial count that is not negative.")
conditionCount = count
}
public func countDown() {
guard conditionCount > 0 else {
return
}
condition.lock()
conditionCount -= 1
condition.broadcast()
condition.unlock()
}
public func await() {
guard conditionCount > 0 else {
return
}
condition.lock()
defer {
condition.unlock()
}
while conditionCount > 0 {
// We may be woken up by a broadcast in countDown.
condition.wait()
}
}
}
public class PromisedReply<Value> {
public typealias SuccessHandler = ((Value?) throws -> PromisedReply<Value>?)?
public typealias FailureHandler = ((Error) throws -> PromisedReply<Value>?)?
public typealias FinallyHandler = (() throws -> Void)
enum State {
case waiting
case resolved(Value?)
case rejected(Error)
var isDone: Bool {
switch self {
case .resolved, .rejected:
return true
default:
return false
}
}
}
private var state: State = .waiting
private var successHandler: SuccessHandler = nil
private var failureHandler: FailureHandler = nil
private var nextPromise: PromisedReply<Value>?
private var countDownLatch: CountDownLatch?
private var queue = DispatchQueue(label: "co.tinode.promise")
private(set) var creationTimestamp: Date = Date()
var isResolved: Bool {
if case .resolved = state { return true }
return false
}
var isRejected: Bool {
if case .rejected = state { return true }
return false
}
var isDone: Bool {
return state.isDone
}
public init() {
countDownLatch = CountDownLatch(count: 1)
}
public init(value: Value?) {
state = .resolved(value)
countDownLatch = CountDownLatch(count: 0)
}
public init(error: Error) {
state = .rejected(error)
countDownLatch = CountDownLatch(count: 0)
}
public class func allOf(promises waitFor: [PromisedReply]) -> PromisedReply<Void> {
let done = PromisedReply<Void>()
// Create a separate thread and wait for all promises to resolve.
DispatchQueue(label: "co.tinode.promise.allOf").async {
for p in waitFor {
p.countDownLatch?.await()
}
// We can't do anything if it throws.
try? done.resolve(result: nil)
}
return done
}
public func resolve(result: Value?) throws {
defer {
// down the semaphore
countDownLatch?.countDown()
}
try queue.sync {
// critical section
guard case .waiting = state else {
throw PromisedReplyError.illegalStateError("Resolve: Promise already completed.")
}
state = .resolved(result)
try callOnSuccess(result: result)
}
}
public func reject(error: Error) throws {
defer {
// down the semaphore
countDownLatch?.countDown()
}
try queue.sync {
// critical section
guard case .waiting = state else {
// down the semaphore
throw PromisedReplyError.illegalStateError("Reject: promise already completed")
}
state = .rejected(error)
try callOnFailure(err: error)
}
}
@discardableResult
public func then(onSuccess successHandler: SuccessHandler, onFailure failureHandler: FailureHandler = nil) -> PromisedReply<Value> {
return queue.sync {
// start critical section
guard nextPromise == nil else {
fatalError("Multiple calls to then are not supported")
}
self.successHandler = successHandler
self.failureHandler = failureHandler
self.nextPromise = PromisedReply<Value>()
do {
switch state {
case .resolved(let result):
try callOnSuccess(result: result)
case .rejected(let error):
try callOnFailure(err: error)
case .waiting: break
}
} catch {
self.nextPromise = PromisedReply<Value>(error: error)
}
return self.nextPromise!
}
}
@discardableResult
public func thenApply(_ successHandler: SuccessHandler) -> PromisedReply<Value> {
return then(onSuccess: successHandler, onFailure: nil)
}
@discardableResult
public func thenCatch(_ failureHandler: FailureHandler) -> PromisedReply<Value> {
return then(onSuccess: nil, onFailure: failureHandler)
}
public func thenFinally(_ finally: @escaping FinallyHandler) {
then(
onSuccess: {
_ in try finally()
return nil
},
onFailure: {
_ in try finally()
return nil
})
}
private func callOnSuccess(result: Value?) throws {
var ret: PromisedReply<Value>?
do {
if let sh = successHandler {
ret = try sh(result)
}
} catch {
// failure handler
try handleFailure(e: error)
return
}
try handleSuccess(ret: ret)
}
private func callOnFailure(err: Error) throws {
if let fh = failureHandler {
// Try to recover.
do {
try handleSuccess(ret: fh(err))
} catch {
try handleFailure(e: error)
}
} else {
// Pass to the next handler.
try handleFailure(e: err)
}
}
private func handleSuccess(ret: PromisedReply<Value>?) throws {
guard let np = nextPromise else {
if let r = ret, case .rejected(let retError) = r.state {
throw retError
}
return
}
guard let r = ret else {
// 'ret' is nil when an attempt is made at recovering from a failure. If the current
// promise is rejected we should resolve the next in chain with the 'nil' value.
let value: Value?
switch state {
case .resolved(let v): value = v
default: value = nil
}
try np.resolve(result: value)
return
}
switch r.state {
case .resolved(let value):
try np.resolve(result: value)
case .rejected(let error):
try np.reject(error: error)
case .waiting:
r.insertNextPromise(next: np)
}
}
private func handleFailure(e: Error) throws {
if let np = nextPromise {
try np.reject(error: e)
} else {
throw e
}
}
private func insertNextPromise(next: PromisedReply<Value>) {
// critical section
if let np = nextPromise {
next.insertNextPromise(next: np)
}
nextPromise = next
}
public func getResult() throws -> Value? {
countDownLatch?.await()
switch state {
case .resolved(let value):
return value
case .rejected(let e):
throw e
case .waiting:
throw PromisedReplyError.illegalStateError("Called getResult on unresolved promise")
}
}
@discardableResult
public func waitResult() throws -> Bool {
countDownLatch?.await()
return isResolved
}
}