ServerCancellationManager.swift 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. private import Synchronization
  17. /// Stores cancellation state for an RPC on the server .
  18. package final class ServerCancellationManager: Sendable {
  19. private let state: Mutex<State>
  20. package init() {
  21. self.state = Mutex(State())
  22. }
  23. /// Returns whether the RPC has been marked as cancelled.
  24. package var isRPCCancelled: Bool {
  25. self.state.withLock {
  26. return $0.isRPCCancelled
  27. }
  28. }
  29. /// Marks the RPC as cancelled, potentially running any cancellation handlers.
  30. package func cancelRPC() {
  31. switch self.state.withLock({ $0.cancelRPC() }) {
  32. case .executeAndResume(let onCancelHandlers, let onCancelWaiters):
  33. for handler in onCancelHandlers {
  34. handler.handler()
  35. }
  36. for onCancelWaiter in onCancelWaiters {
  37. switch onCancelWaiter {
  38. case .taskCancelled:
  39. ()
  40. case .waiting(_, let continuation):
  41. continuation.resume(returning: .rpc)
  42. }
  43. }
  44. case .doNothing:
  45. ()
  46. }
  47. }
  48. /// Adds a handler which is invoked when the RPC is cancelled.
  49. ///
  50. /// - Returns: The ID of the handler, if it was added, or `nil` if the RPC is already cancelled.
  51. package func addRPCCancelledHandler(_ handler: @Sendable @escaping () -> Void) -> UInt64? {
  52. return self.state.withLock { state -> UInt64? in
  53. state.addRPCCancelledHandler(handler)
  54. }
  55. }
  56. /// Removes a handler by its ID.
  57. package func removeRPCCancelledHandler(withID id: UInt64) {
  58. self.state.withLock { state in
  59. state.removeRPCCancelledHandler(withID: id)
  60. }
  61. }
  62. /// Suspends until the RPC is cancelled or the `Task` is cancelled.
  63. package func suspendUntilRPCIsCancelled() async throws(CancellationError) {
  64. let id = self.state.withLock { $0.nextID() }
  65. let source = await withTaskCancellationHandler {
  66. await withCheckedContinuation { continuation in
  67. let onAddWaiter = self.state.withLock {
  68. $0.addRPCIsCancelledWaiter(continuation: continuation, withID: id)
  69. }
  70. switch onAddWaiter {
  71. case .doNothing:
  72. ()
  73. case .complete(let continuation, let result):
  74. continuation.resume(returning: result)
  75. }
  76. }
  77. } onCancel: {
  78. switch self.state.withLock({ $0.cancelRPCCancellationWaiter(withID: id) }) {
  79. case .resume(let continuation, let result):
  80. continuation.resume(returning: result)
  81. case .doNothing:
  82. ()
  83. }
  84. }
  85. switch source {
  86. case .rpc:
  87. ()
  88. case .task:
  89. throw CancellationError()
  90. }
  91. }
  92. }
  93. extension ServerCancellationManager {
  94. enum CancellationSource {
  95. case rpc
  96. case task
  97. }
  98. struct Handler: Sendable {
  99. var id: UInt64
  100. var handler: @Sendable () -> Void
  101. }
  102. enum Waiter: Sendable {
  103. case waiting(UInt64, CheckedContinuation<CancellationSource, Never>)
  104. case taskCancelled(UInt64)
  105. var id: UInt64 {
  106. switch self {
  107. case .waiting(let id, _):
  108. return id
  109. case .taskCancelled(let id):
  110. return id
  111. }
  112. }
  113. }
  114. struct State {
  115. private var handlers: [Handler]
  116. private var waiters: [Waiter]
  117. private var _nextID: UInt64
  118. var isRPCCancelled: Bool
  119. mutating func nextID() -> UInt64 {
  120. let id = self._nextID
  121. self._nextID &+= 1
  122. return id
  123. }
  124. init() {
  125. self.handlers = []
  126. self.waiters = []
  127. self._nextID = 0
  128. self.isRPCCancelled = false
  129. }
  130. mutating func cancelRPC() -> OnCancelRPC {
  131. let onCancel: OnCancelRPC
  132. if self.isRPCCancelled {
  133. onCancel = .doNothing
  134. } else {
  135. self.isRPCCancelled = true
  136. onCancel = .executeAndResume(self.handlers, self.waiters)
  137. self.handlers = []
  138. self.waiters = []
  139. }
  140. return onCancel
  141. }
  142. mutating func addRPCCancelledHandler(_ handler: @Sendable @escaping () -> Void) -> UInt64? {
  143. if self.isRPCCancelled {
  144. handler()
  145. return nil
  146. } else {
  147. let id = self.nextID()
  148. self.handlers.append(.init(id: id, handler: handler))
  149. return id
  150. }
  151. }
  152. mutating func removeRPCCancelledHandler(withID id: UInt64) {
  153. if let index = self.handlers.firstIndex(where: { $0.id == id }) {
  154. self.handlers.remove(at: index)
  155. }
  156. }
  157. enum OnCancelRPC {
  158. case executeAndResume([Handler], [Waiter])
  159. case doNothing
  160. }
  161. enum OnAddWaiter {
  162. case complete(CheckedContinuation<CancellationSource, Never>, CancellationSource)
  163. case doNothing
  164. }
  165. mutating func addRPCIsCancelledWaiter(
  166. continuation: CheckedContinuation<CancellationSource, Never>,
  167. withID id: UInt64
  168. ) -> OnAddWaiter {
  169. let onAddWaiter: OnAddWaiter
  170. if self.isRPCCancelled {
  171. onAddWaiter = .complete(continuation, .rpc)
  172. } else if let index = self.waiters.firstIndex(where: { $0.id == id }) {
  173. switch self.waiters[index] {
  174. case .taskCancelled:
  175. onAddWaiter = .complete(continuation, .task)
  176. case .waiting:
  177. // There's already a continuation enqueued.
  178. fatalError("Inconsistent state")
  179. }
  180. } else {
  181. self.waiters.append(.waiting(id, continuation))
  182. onAddWaiter = .doNothing
  183. }
  184. return onAddWaiter
  185. }
  186. enum OnCancelRPCCancellationWaiter {
  187. case resume(CheckedContinuation<CancellationSource, Never>, CancellationSource)
  188. case doNothing
  189. }
  190. mutating func cancelRPCCancellationWaiter(withID id: UInt64) -> OnCancelRPCCancellationWaiter {
  191. let onCancelWaiter: OnCancelRPCCancellationWaiter
  192. if let index = self.waiters.firstIndex(where: { $0.id == id }) {
  193. let waiter = self.waiters.removeWithoutMaintainingOrder(at: index)
  194. switch waiter {
  195. case .taskCancelled:
  196. onCancelWaiter = .doNothing
  197. case .waiting(_, let continuation):
  198. onCancelWaiter = .resume(continuation, .task)
  199. }
  200. } else {
  201. self.waiters.append(.taskCancelled(id))
  202. onCancelWaiter = .doNothing
  203. }
  204. return onCancelWaiter
  205. }
  206. }
  207. }
  208. extension Array {
  209. fileprivate mutating func removeWithoutMaintainingOrder(at index: Int) -> Element {
  210. let lastElementIndex = self.index(before: self.endIndex)
  211. if index == lastElementIndex {
  212. return self.remove(at: index)
  213. } else {
  214. self.swapAt(index, lastElementIndex)
  215. return self.removeLast()
  216. }
  217. }
  218. }