ServerCancellationManager.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. @available(gRPCSwift 2.0, *)
  19. package final class ServerCancellationManager: Sendable {
  20. private let state: Mutex<State>
  21. package init() {
  22. self.state = Mutex(State())
  23. }
  24. /// Returns whether the RPC has been marked as cancelled.
  25. package var isRPCCancelled: Bool {
  26. self.state.withLock {
  27. return $0.isRPCCancelled
  28. }
  29. }
  30. /// Marks the RPC as cancelled, potentially running any cancellation handlers.
  31. package func cancelRPC() {
  32. switch self.state.withLock({ $0.cancelRPC() }) {
  33. case .executeAndResume(let onCancelHandlers, let onCancelWaiters):
  34. for handler in onCancelHandlers {
  35. handler.handler()
  36. }
  37. for onCancelWaiter in onCancelWaiters {
  38. switch onCancelWaiter {
  39. case .taskCancelled:
  40. ()
  41. case .waiting(_, let continuation):
  42. continuation.resume(returning: .rpc)
  43. }
  44. }
  45. case .doNothing:
  46. ()
  47. }
  48. }
  49. /// Adds a handler which is invoked when the RPC is cancelled.
  50. ///
  51. /// - Returns: The ID of the handler, if it was added, or `nil` if the RPC is already cancelled.
  52. package func addRPCCancelledHandler(_ handler: @Sendable @escaping () -> Void) -> UInt64? {
  53. return self.state.withLock { state -> UInt64? in
  54. state.addRPCCancelledHandler(handler)
  55. }
  56. }
  57. /// Removes a handler by its ID.
  58. package func removeRPCCancelledHandler(withID id: UInt64) {
  59. self.state.withLock { state in
  60. state.removeRPCCancelledHandler(withID: id)
  61. }
  62. }
  63. /// Suspends until the RPC is cancelled or the `Task` is cancelled.
  64. package func suspendUntilRPCIsCancelled() async throws(CancellationError) {
  65. let id = self.state.withLock { $0.nextID() }
  66. let source = await withTaskCancellationHandler {
  67. await withCheckedContinuation { continuation in
  68. let onAddWaiter = self.state.withLock {
  69. $0.addRPCIsCancelledWaiter(continuation: continuation, withID: id)
  70. }
  71. switch onAddWaiter {
  72. case .doNothing:
  73. ()
  74. case .complete(let continuation, let result):
  75. continuation.resume(returning: result)
  76. }
  77. }
  78. } onCancel: {
  79. switch self.state.withLock({ $0.cancelRPCCancellationWaiter(withID: id) }) {
  80. case .resume(let continuation, let result):
  81. continuation.resume(returning: result)
  82. case .doNothing:
  83. ()
  84. }
  85. }
  86. switch source {
  87. case .rpc:
  88. ()
  89. case .task:
  90. throw CancellationError()
  91. }
  92. }
  93. }
  94. @available(gRPCSwift 2.0, *)
  95. extension ServerCancellationManager {
  96. enum CancellationSource {
  97. case rpc
  98. case task
  99. }
  100. struct Handler: Sendable {
  101. var id: UInt64
  102. var handler: @Sendable () -> Void
  103. }
  104. enum Waiter: Sendable {
  105. case waiting(UInt64, CheckedContinuation<CancellationSource, Never>)
  106. case taskCancelled(UInt64)
  107. var id: UInt64 {
  108. switch self {
  109. case .waiting(let id, _):
  110. return id
  111. case .taskCancelled(let id):
  112. return id
  113. }
  114. }
  115. }
  116. struct State {
  117. private var handlers: [Handler]
  118. private var waiters: [Waiter]
  119. private var _nextID: UInt64
  120. var isRPCCancelled: Bool
  121. mutating func nextID() -> UInt64 {
  122. let id = self._nextID
  123. self._nextID &+= 1
  124. return id
  125. }
  126. init() {
  127. self.handlers = []
  128. self.waiters = []
  129. self._nextID = 0
  130. self.isRPCCancelled = false
  131. }
  132. mutating func cancelRPC() -> OnCancelRPC {
  133. let onCancel: OnCancelRPC
  134. if self.isRPCCancelled {
  135. onCancel = .doNothing
  136. } else {
  137. self.isRPCCancelled = true
  138. onCancel = .executeAndResume(self.handlers, self.waiters)
  139. self.handlers = []
  140. self.waiters = []
  141. }
  142. return onCancel
  143. }
  144. mutating func addRPCCancelledHandler(_ handler: @Sendable @escaping () -> Void) -> UInt64? {
  145. if self.isRPCCancelled {
  146. handler()
  147. return nil
  148. } else {
  149. let id = self.nextID()
  150. self.handlers.append(.init(id: id, handler: handler))
  151. return id
  152. }
  153. }
  154. mutating func removeRPCCancelledHandler(withID id: UInt64) {
  155. if let index = self.handlers.firstIndex(where: { $0.id == id }) {
  156. self.handlers.remove(at: index)
  157. }
  158. }
  159. enum OnCancelRPC {
  160. case executeAndResume([Handler], [Waiter])
  161. case doNothing
  162. }
  163. enum OnAddWaiter {
  164. case complete(CheckedContinuation<CancellationSource, Never>, CancellationSource)
  165. case doNothing
  166. }
  167. mutating func addRPCIsCancelledWaiter(
  168. continuation: CheckedContinuation<CancellationSource, Never>,
  169. withID id: UInt64
  170. ) -> OnAddWaiter {
  171. let onAddWaiter: OnAddWaiter
  172. if self.isRPCCancelled {
  173. onAddWaiter = .complete(continuation, .rpc)
  174. } else if let index = self.waiters.firstIndex(where: { $0.id == id }) {
  175. switch self.waiters[index] {
  176. case .taskCancelled:
  177. onAddWaiter = .complete(continuation, .task)
  178. case .waiting:
  179. // There's already a continuation enqueued.
  180. fatalError("Inconsistent state")
  181. }
  182. } else {
  183. self.waiters.append(.waiting(id, continuation))
  184. onAddWaiter = .doNothing
  185. }
  186. return onAddWaiter
  187. }
  188. enum OnCancelRPCCancellationWaiter {
  189. case resume(CheckedContinuation<CancellationSource, Never>, CancellationSource)
  190. case doNothing
  191. }
  192. mutating func cancelRPCCancellationWaiter(withID id: UInt64) -> OnCancelRPCCancellationWaiter {
  193. let onCancelWaiter: OnCancelRPCCancellationWaiter
  194. if let index = self.waiters.firstIndex(where: { $0.id == id }) {
  195. let waiter = self.waiters.removeWithoutMaintainingOrder(at: index)
  196. switch waiter {
  197. case .taskCancelled:
  198. onCancelWaiter = .doNothing
  199. case .waiting(_, let continuation):
  200. onCancelWaiter = .resume(continuation, .task)
  201. }
  202. } else {
  203. self.waiters.append(.taskCancelled(id))
  204. onCancelWaiter = .doNothing
  205. }
  206. return onCancelWaiter
  207. }
  208. }
  209. }
  210. extension Array {
  211. fileprivate mutating func removeWithoutMaintainingOrder(at index: Int) -> Element {
  212. let lastElementIndex = self.index(before: self.endIndex)
  213. if index == lastElementIndex {
  214. return self.remove(at: index)
  215. } else {
  216. self.swapAt(index, lastElementIndex)
  217. return self.removeLast()
  218. }
  219. }
  220. }