ServerContext+RPCCancellationHandle.swift 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. @available(gRPCSwift 2.0, *)
  18. extension ServerContext {
  19. @TaskLocal
  20. internal static var rpcCancellation: RPCCancellationHandle?
  21. /// A handle for the cancellation status of the RPC.
  22. public struct RPCCancellationHandle: Sendable {
  23. internal let manager: ServerCancellationManager
  24. /// Create a cancellation handle.
  25. ///
  26. /// To create an instance of this handle appropriately bound to a `Task`
  27. /// use ``withServerContextRPCCancellationHandle(_:)``.
  28. public init() {
  29. self.manager = ServerCancellationManager()
  30. }
  31. /// Returns whether the RPC has been cancelled.
  32. public var isCancelled: Bool {
  33. self.manager.isRPCCancelled
  34. }
  35. /// Waits until the RPC has been cancelled.
  36. ///
  37. /// Throws a `CancellationError` if the `Task` is cancelled.
  38. ///
  39. /// You can also be notified when an RPC is cancelled by using
  40. /// ``withRPCCancellationHandler(operation:onCancelRPC:)``.
  41. public var cancelled: Void {
  42. get async throws {
  43. try await self.manager.suspendUntilRPCIsCancelled()
  44. }
  45. }
  46. /// Signal that the RPC should be cancelled.
  47. ///
  48. /// This is idempotent: calling it more than once has no effect.
  49. public func cancel() {
  50. self.manager.cancelRPC()
  51. }
  52. }
  53. }
  54. /// Execute an operation with an RPC cancellation handler that's immediately invoked
  55. /// if the RPC is canceled.
  56. ///
  57. /// RPCs can be cancelled for a number of reasons including:
  58. /// 1. The RPC was taking too long to process and a timeout passed.
  59. /// 2. The remote peer closed the underlying stream, either because they were no longer
  60. /// interested in the result or due to a broken connection.
  61. /// 3. The server began shutting down.
  62. ///
  63. /// - Important: This only applies to RPCs on the server.
  64. /// - Parameters:
  65. /// - operation: The operation to execute.
  66. /// - handler: The handler which is invoked when the RPC is cancelled.
  67. /// - Throws: Any error thrown by the `operation` closure.
  68. /// - Returns: The result of the `operation` closure.
  69. @available(gRPCSwift 2.0, *)
  70. public func withRPCCancellationHandler<Result, Failure: Error>(
  71. operation: () async throws(Failure) -> Result,
  72. onCancelRPC handler: @Sendable @escaping () -> Void
  73. ) async throws(Failure) -> Result {
  74. guard let manager = ServerContext.rpcCancellation?.manager,
  75. let id = manager.addRPCCancelledHandler(handler)
  76. else {
  77. return try await operation()
  78. }
  79. defer {
  80. manager.removeRPCCancelledHandler(withID: id)
  81. }
  82. return try await operation()
  83. }
  84. /// Provides scoped access to a server RPC cancellation handle.
  85. ///
  86. /// The cancellation handle should be passed to a ``ServerContext`` and last
  87. /// the duration of the RPC.
  88. ///
  89. /// - Important: This function is intended for use when implementing
  90. /// a ``ServerTransport``.
  91. ///
  92. /// If you want to be notified about RPCs being cancelled
  93. /// use ``withRPCCancellationHandler(operation:onCancelRPC:)``.
  94. ///
  95. /// - Parameter operation: The operation to execute with the handle.
  96. @available(gRPCSwift 2.0, *)
  97. public func withServerContextRPCCancellationHandle<Success, Failure: Error>(
  98. _ operation: (ServerContext.RPCCancellationHandle) async throws(Failure) -> Success
  99. ) async throws(Failure) -> Success {
  100. let handle = ServerContext.RPCCancellationHandle()
  101. let result = await ServerContext.$rpcCancellation.withValue(handle) {
  102. // Wrap up the outcome in a result as 'withValue' doesn't support typed throws.
  103. return await Swift.Result { () async throws(Failure) -> Success in
  104. return try await operation(handle)
  105. }
  106. }
  107. return try result.get()
  108. }