Call.swift 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. /// Dispatch queue used for sending messages asynchronously
  52. private let messageDispatchQueue: DispatchQueue = DispatchQueue.global()
  53. /// Initializes a Call representation
  54. ///
  55. /// - Parameter call: the underlying C representation
  56. /// - Parameter owned: true if this instance is responsible for deleting the underlying call
  57. init(underlyingCall: UnsafeMutableRawPointer, owned: Bool, completionQueue: CompletionQueue) {
  58. self.underlyingCall = underlyingCall
  59. self.owned = owned
  60. self.completionQueue = completionQueue
  61. writing = false
  62. sendMutex = Mutex()
  63. }
  64. deinit {
  65. if owned {
  66. cgrpc_call_destroy(underlyingCall)
  67. }
  68. }
  69. /// Initiates performance of a group of operations without waiting for completion.
  70. ///
  71. /// - Parameter operations: group of operations to be performed
  72. /// - Returns: the result of initiating the call
  73. /// - Throws: `CallError` if fails to call.
  74. func perform(_ operations: OperationGroup) throws {
  75. completionQueue.register(operations)
  76. Call.callMutex.lock()
  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. /// Starts a gRPC API call.
  84. ///
  85. /// - Parameter style: the style of call to start
  86. /// - Parameter metadata: metadata to send with the call
  87. /// - Parameter message: data containing the message to send (.unary and .serverStreaming only)
  88. /// - Parameter completion: a block to call with call results
  89. /// - Throws: `CallError` if fails to call.
  90. public func start(_ style: CallStyle,
  91. metadata: Metadata,
  92. message: Data? = nil,
  93. completion: ((CallResult) -> Void)? = nil) throws {
  94. var operations: [Operation] = []
  95. switch style {
  96. case .unary:
  97. guard let message = message else {
  98. throw CallError.invalidMessage
  99. }
  100. operations = [
  101. .sendInitialMetadata(metadata.copy()),
  102. .sendMessage(ByteBuffer(data:message)),
  103. .sendCloseFromClient,
  104. .receiveInitialMetadata,
  105. .receiveMessage,
  106. .receiveStatusOnClient,
  107. ]
  108. case .serverStreaming:
  109. guard let message = message else {
  110. throw CallError.invalidMessage
  111. }
  112. operations = [
  113. .sendInitialMetadata(metadata.copy()),
  114. .sendMessage(ByteBuffer(data:message)),
  115. .sendCloseFromClient,
  116. .receiveInitialMetadata,
  117. .receiveStatusOnClient,
  118. ]
  119. case .clientStreaming, .bidiStreaming:
  120. try perform(OperationGroup(call: self,
  121. operations: [
  122. .sendInitialMetadata(metadata.copy()),
  123. .receiveInitialMetadata
  124. ],
  125. completion: nil))
  126. try perform(OperationGroup(call: self,
  127. operations: [.receiveStatusOnClient],
  128. completion: completion != nil
  129. ? { op in completion?(CallResult(op)) }
  130. : nil))
  131. return
  132. }
  133. try perform(OperationGroup(call: self,
  134. operations: operations,
  135. completion: completion != nil
  136. ? { op in completion?(CallResult(op)) }
  137. : nil))
  138. }
  139. /// Sends a message over a streaming connection.
  140. ///
  141. /// Parameter data: the message data to send
  142. /// - Throws: `CallError` if fails to call. `CallWarning` if blocked.
  143. public func sendMessage(data: Data, completion: ((Error?) -> Void)? = nil) throws {
  144. messageQueueEmpty.enter()
  145. try sendMutex.synchronize {
  146. if writing {
  147. if let messageQueueMaxLength = Call.messageQueueMaxLength,
  148. messageQueue.count >= messageQueueMaxLength {
  149. throw CallWarning.blocked
  150. }
  151. messageQueue.append((dataToSend: data, completion: completion))
  152. } else {
  153. writing = true
  154. try sendWithoutBlocking(data: data, completion: completion)
  155. }
  156. }
  157. }
  158. /// helper for sending queued messages
  159. private func sendWithoutBlocking(data: Data, completion: ((Error?) -> Void)?) throws {
  160. try perform(OperationGroup(call: self,
  161. operations: [.sendMessage(ByteBuffer(data: data))]) { operationGroup in
  162. // TODO(timburks, danielalm): Is the `async` dispatch here needed, and/or should we call the completion handler
  163. // and leave `messageQueueEmpty` in the `async` block as well?
  164. self.messageDispatchQueue.async {
  165. // Always enqueue the next message, even if sending this one failed. This ensures that all send completion
  166. // handlers are called eventually.
  167. self.sendMutex.synchronize {
  168. // if there are messages pending, send the next one
  169. if self.messageQueue.count > 0 {
  170. let (nextMessage, nextCompletionHandler) = self.messageQueue.removeFirst()
  171. do {
  172. try self.sendWithoutBlocking(data: nextMessage, completion: nextCompletionHandler)
  173. } catch (let callError) {
  174. nextCompletionHandler?(callError)
  175. }
  176. } else {
  177. // otherwise, we are finished writing
  178. self.writing = false
  179. }
  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. }