forked from grpc/grpc-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServerCancellationManager.swift
254 lines (218 loc) · 6.84 KB
/
ServerCancellationManager.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
/*
* Copyright 2024, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
private import Synchronization
/// Stores cancellation state for an RPC on the server .
package final class ServerCancellationManager: Sendable {
private let state: Mutex<State>
package init() {
self.state = Mutex(State())
}
/// Returns whether the RPC has been marked as cancelled.
package var isRPCCancelled: Bool {
self.state.withLock {
return $0.isRPCCancelled
}
}
/// Marks the RPC as cancelled, potentially running any cancellation handlers.
package func cancelRPC() {
switch self.state.withLock({ $0.cancelRPC() }) {
case .executeAndResume(let onCancelHandlers, let onCancelWaiters):
for handler in onCancelHandlers {
handler.handler()
}
for onCancelWaiter in onCancelWaiters {
switch onCancelWaiter {
case .taskCancelled:
()
case .waiting(_, let continuation):
continuation.resume(returning: .rpc)
}
}
case .doNothing:
()
}
}
/// Adds a handler which is invoked when the RPC is cancelled.
///
/// - Returns: The ID of the handler, if it was added, or `nil` if the RPC is already cancelled.
package func addRPCCancelledHandler(_ handler: @Sendable @escaping () -> Void) -> UInt64? {
return self.state.withLock { state -> UInt64? in
state.addRPCCancelledHandler(handler)
}
}
/// Removes a handler by its ID.
package func removeRPCCancelledHandler(withID id: UInt64) {
self.state.withLock { state in
state.removeRPCCancelledHandler(withID: id)
}
}
/// Suspends until the RPC is cancelled or the `Task` is cancelled.
package func suspendUntilRPCIsCancelled() async throws(CancellationError) {
let id = self.state.withLock { $0.nextID() }
let source = await withTaskCancellationHandler {
await withCheckedContinuation { continuation in
let onAddWaiter = self.state.withLock {
$0.addRPCIsCancelledWaiter(continuation: continuation, withID: id)
}
switch onAddWaiter {
case .doNothing:
()
case .complete(let continuation, let result):
continuation.resume(returning: result)
}
}
} onCancel: {
switch self.state.withLock({ $0.cancelRPCCancellationWaiter(withID: id) }) {
case .resume(let continuation, let result):
continuation.resume(returning: result)
case .doNothing:
()
}
}
switch source {
case .rpc:
()
case .task:
throw CancellationError()
}
}
}
extension ServerCancellationManager {
enum CancellationSource {
case rpc
case task
}
struct Handler: Sendable {
var id: UInt64
var handler: @Sendable () -> Void
}
enum Waiter: Sendable {
case waiting(UInt64, CheckedContinuation<CancellationSource, Never>)
case taskCancelled(UInt64)
var id: UInt64 {
switch self {
case .waiting(let id, _):
return id
case .taskCancelled(let id):
return id
}
}
}
struct State {
private var handlers: [Handler]
private var waiters: [Waiter]
private var _nextID: UInt64
var isRPCCancelled: Bool
mutating func nextID() -> UInt64 {
let id = self._nextID
self._nextID &+= 1
return id
}
init() {
self.handlers = []
self.waiters = []
self._nextID = 0
self.isRPCCancelled = false
}
mutating func cancelRPC() -> OnCancelRPC {
let onCancel: OnCancelRPC
if self.isRPCCancelled {
onCancel = .doNothing
} else {
self.isRPCCancelled = true
onCancel = .executeAndResume(self.handlers, self.waiters)
self.handlers = []
self.waiters = []
}
return onCancel
}
mutating func addRPCCancelledHandler(_ handler: @Sendable @escaping () -> Void) -> UInt64? {
if self.isRPCCancelled {
handler()
return nil
} else {
let id = self.nextID()
self.handlers.append(.init(id: id, handler: handler))
return id
}
}
mutating func removeRPCCancelledHandler(withID id: UInt64) {
if let index = self.handlers.firstIndex(where: { $0.id == id }) {
self.handlers.remove(at: index)
}
}
enum OnCancelRPC {
case executeAndResume([Handler], [Waiter])
case doNothing
}
enum OnAddWaiter {
case complete(CheckedContinuation<CancellationSource, Never>, CancellationSource)
case doNothing
}
mutating func addRPCIsCancelledWaiter(
continuation: CheckedContinuation<CancellationSource, Never>,
withID id: UInt64
) -> OnAddWaiter {
let onAddWaiter: OnAddWaiter
if self.isRPCCancelled {
onAddWaiter = .complete(continuation, .rpc)
} else if let index = self.waiters.firstIndex(where: { $0.id == id }) {
switch self.waiters[index] {
case .taskCancelled:
onAddWaiter = .complete(continuation, .task)
case .waiting:
// There's already a continuation enqueued.
fatalError("Inconsistent state")
}
} else {
self.waiters.append(.waiting(id, continuation))
onAddWaiter = .doNothing
}
return onAddWaiter
}
enum OnCancelRPCCancellationWaiter {
case resume(CheckedContinuation<CancellationSource, Never>, CancellationSource)
case doNothing
}
mutating func cancelRPCCancellationWaiter(withID id: UInt64) -> OnCancelRPCCancellationWaiter {
let onCancelWaiter: OnCancelRPCCancellationWaiter
if let index = self.waiters.firstIndex(where: { $0.id == id }) {
let waiter = self.waiters.removeWithoutMaintainingOrder(at: index)
switch waiter {
case .taskCancelled:
onCancelWaiter = .doNothing
case .waiting(_, let continuation):
onCancelWaiter = .resume(continuation, .task)
}
} else {
self.waiters.append(.taskCancelled(id))
onCancelWaiter = .doNothing
}
return onCancelWaiter
}
}
}
extension Array {
fileprivate mutating func removeWithoutMaintainingOrder(at index: Int) -> Element {
let lastElementIndex = self.index(before: self.endIndex)
if index == lastElementIndex {
return self.remove(at: index)
} else {
self.swapAt(index, lastElementIndex)
return self.removeLast()
}
}
}