Call.swift 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. /*
  2. * Copyright 2016, 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. #if SWIFT_PACKAGE
  17. import CgRPC
  18. import Dispatch
  19. #endif
  20. import Foundation
  21. public enum CallStyle {
  22. case unary
  23. case serverStreaming
  24. case clientStreaming
  25. case bidiStreaming
  26. }
  27. public enum CallWarning: Error {
  28. case blocked
  29. }
  30. /// A gRPC API call
  31. public class Call {
  32. /// Shared mutex for synchronizing calls to cgrpc_call_perform()
  33. private static let callMutex = Mutex()
  34. /// Maximum number of messages that can be queued
  35. public static var messageQueueMaxLength: Int? = nil
  36. /// Pointer to underlying C representation
  37. private let underlyingCall: UnsafeMutableRawPointer
  38. /// Completion queue used for call
  39. private let completionQueue: CompletionQueue
  40. /// True if this instance is responsible for deleting the underlying C representation
  41. private let owned: Bool
  42. /// A queue of pending messages to send over the call
  43. private var messageQueue: [(dataToSend: Data, completion: ((Error?) -> Void)?)] = []
  44. /// A dispatch group that contains all pending send operations.
  45. /// You can wait on it to ensure that all currently enqueued messages have been sent.
  46. public let messageQueueEmpty = DispatchGroup()
  47. /// True if a message write operation is underway
  48. private var writing: Bool
  49. /// Mutex for synchronizing message sending
  50. private let sendMutex: Mutex
  51. /// Initializes a Call representation
  52. ///
  53. /// - Parameter call: the underlying C representation
  54. /// - Parameter owned: true if this instance is responsible for deleting the underlying call
  55. init(underlyingCall: UnsafeMutableRawPointer, owned: Bool, completionQueue: CompletionQueue) {
  56. self.underlyingCall = underlyingCall
  57. self.owned = owned
  58. self.completionQueue = completionQueue
  59. writing = false
  60. sendMutex = Mutex()
  61. }
  62. deinit {
  63. if owned {
  64. cgrpc_call_destroy(underlyingCall)
  65. }
  66. }
  67. /// Initiates performance of a group of operations without waiting for completion.
  68. ///
  69. /// - Parameter operations: group of operations to be performed
  70. /// - Returns: the result of initiating the call
  71. /// - Throws: `CallError` if fails to call.
  72. func perform(_ operations: OperationGroup) throws {
  73. try completionQueue.register(operations) {
  74. Call.callMutex.lock()
  75. // We need to do the perform *inside* the `completionQueue.register` call, to ensure that the queue can't get
  76. // shutdown in between registering the operation group and calling `cgrpc_call_perform`.
  77. let error = cgrpc_call_perform(underlyingCall, operations.underlyingOperations, operations.tag)
  78. Call.callMutex.unlock()
  79. if error != GRPC_CALL_OK {
  80. throw CallError.callError(grpcCallError: error)
  81. }
  82. }
  83. }
  84. /// Starts a gRPC API call.
  85. ///
  86. /// - Parameter style: the style of call to start
  87. /// - Parameter metadata: metadata to send with the call
  88. /// - Parameter message: data containing the message to send (.unary and .serverStreaming only)
  89. /// - Parameter completion: a block to call with call results
  90. /// The argument to `completion` will always have `.success = true`
  91. /// because operations containing `.receiveCloseOnClient` always succeed.
  92. /// - Throws: `CallError` if fails to call.
  93. public func start(_ style: CallStyle,
  94. metadata: Metadata,
  95. message: Data? = nil,
  96. completion: ((CallResult) -> Void)? = nil) throws {
  97. var operations: [Operation] = []
  98. switch style {
  99. case .unary:
  100. guard let message = message else {
  101. throw CallError.invalidMessage
  102. }
  103. operations = [
  104. .sendInitialMetadata(metadata.copy()),
  105. .sendMessage(ByteBuffer(data:message)),
  106. .sendCloseFromClient,
  107. .receiveInitialMetadata,
  108. .receiveMessage,
  109. .receiveStatusOnClient,
  110. ]
  111. case .serverStreaming:
  112. guard let message = message else {
  113. throw CallError.invalidMessage
  114. }
  115. operations = [
  116. .sendInitialMetadata(metadata.copy()),
  117. .sendMessage(ByteBuffer(data:message)),
  118. .sendCloseFromClient,
  119. .receiveInitialMetadata,
  120. .receiveStatusOnClient,
  121. ]
  122. case .clientStreaming, .bidiStreaming:
  123. try perform(OperationGroup(call: self,
  124. operations: [
  125. .sendInitialMetadata(metadata.copy()),
  126. .receiveInitialMetadata
  127. ],
  128. completion: nil))
  129. try perform(OperationGroup(call: self,
  130. operations: [.receiveStatusOnClient],
  131. completion: completion != nil
  132. ? { op in completion?(CallResult(op)) }
  133. : nil))
  134. return
  135. }
  136. try perform(OperationGroup(call: self,
  137. operations: operations,
  138. completion: completion != nil
  139. ? { op in completion?(CallResult(op)) }
  140. : nil))
  141. }
  142. /// Sends a message over a streaming connection.
  143. ///
  144. /// Parameter data: the message data to send
  145. /// - Throws: `CallError` if fails to call. `CallWarning` if blocked.
  146. public func sendMessage(data: Data, completion: ((Error?) -> Void)? = nil) throws {
  147. try sendMutex.synchronize {
  148. if writing {
  149. if let messageQueueMaxLength = Call.messageQueueMaxLength,
  150. messageQueue.count >= messageQueueMaxLength {
  151. throw CallWarning.blocked
  152. }
  153. messageQueue.append((dataToSend: data, completion: completion))
  154. } else {
  155. writing = true
  156. try sendWithoutBlocking(data: data, completion: completion)
  157. }
  158. messageQueueEmpty.enter()
  159. }
  160. }
  161. /// helper for sending queued messages
  162. private func sendWithoutBlocking(data: Data, completion: ((Error?) -> Void)?) throws {
  163. try perform(OperationGroup(
  164. call: self,
  165. operations: [.sendMessage(ByteBuffer(data: data))]) { operationGroup in
  166. // Always enqueue the next message, even if sending this one failed. This ensures that all send completion
  167. // handlers are called eventually.
  168. self.sendMutex.synchronize {
  169. // if there are messages pending, send the next one
  170. if self.messageQueue.count > 0 {
  171. let (nextMessage, nextCompletionHandler) = self.messageQueue.removeFirst()
  172. do {
  173. try self.sendWithoutBlocking(data: nextMessage, completion: nextCompletionHandler)
  174. } catch {
  175. nextCompletionHandler?(error)
  176. }
  177. } else {
  178. // otherwise, we are finished writing
  179. self.writing = false
  180. }
  181. }
  182. completion?(operationGroup.success ? nil : CallError.unknown)
  183. self.messageQueueEmpty.leave()
  184. })
  185. }
  186. // Receive a message over a streaming connection.
  187. /// - Throws: `CallError` if fails to call.
  188. public func closeAndReceiveMessage(completion: @escaping (CallResult) -> Void) throws {
  189. try perform(OperationGroup(call: self, operations: [.sendCloseFromClient, .receiveMessage]) { operationGroup in
  190. completion(CallResult(operationGroup))
  191. })
  192. }
  193. // Receive a message over a streaming connection.
  194. /// - Throws: `CallError` if fails to call.
  195. public func receiveMessage(completion: @escaping (CallResult) -> Void) throws {
  196. try perform(OperationGroup(call: self, operations: [.receiveMessage]) { operationGroup in
  197. completion(CallResult(operationGroup))
  198. })
  199. }
  200. // Closes a streaming connection.
  201. /// - Throws: `CallError` if fails to call.
  202. public func close(completion: (() -> Void)? = nil) throws {
  203. try perform(OperationGroup(call: self, operations: [.sendCloseFromClient],
  204. completion: completion != nil
  205. ? { op in completion?() }
  206. : nil))
  207. }
  208. // Get the current message queue length
  209. public func messageQueueLength() -> Int {
  210. return messageQueue.count
  211. }
  212. /// Finishes the request side of this call, notifies the server that the RPC should be cancelled,
  213. /// and finishes the response side of the call with an error of code CANCELED.
  214. public func cancel() {
  215. Call.callMutex.synchronize {
  216. cgrpc_call_cancel(underlyingCall)
  217. }
  218. }
  219. }