ServerContext+RPCCancellationHandle.swift 4.0 KB

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