Call.swift 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. completionQueue.register(operations)
  74. Call.callMutex.lock()
  75. let error = cgrpc_call_perform(underlyingCall, operations.underlyingOperations, operations.tag)
  76. Call.callMutex.unlock()
  77. if error != GRPC_CALL_OK {
  78. throw CallError.callError(grpcCallError: error)
  79. }
  80. }
  81. /// Starts a gRPC API call.
  82. ///
  83. /// - Parameter style: the style of call to start
  84. /// - Parameter metadata: metadata to send with the call
  85. /// - Parameter message: data containing the message to send (.unary and .serverStreaming only)
  86. /// - Parameter completion: a block to call with call results
  87. /// - Throws: `CallError` if fails to call.
  88. public func start(_ style: CallStyle,
  89. metadata: Metadata,
  90. message: Data? = nil,
  91. completion: ((CallResult) -> Void)? = nil) throws {
  92. var operations: [Operation] = []
  93. switch style {
  94. case .unary:
  95. guard let message = message else {
  96. throw CallError.invalidMessage
  97. }
  98. operations = [
  99. .sendInitialMetadata(metadata.copy()),
  100. .sendMessage(ByteBuffer(data:message)),
  101. .sendCloseFromClient,
  102. .receiveInitialMetadata,
  103. .receiveMessage,
  104. .receiveStatusOnClient,
  105. ]
  106. case .serverStreaming:
  107. guard let message = message else {
  108. throw CallError.invalidMessage
  109. }
  110. operations = [
  111. .sendInitialMetadata(metadata.copy()),
  112. .sendMessage(ByteBuffer(data:message)),
  113. .sendCloseFromClient,
  114. .receiveInitialMetadata,
  115. .receiveStatusOnClient,
  116. ]
  117. case .clientStreaming, .bidiStreaming:
  118. try perform(OperationGroup(call: self,
  119. operations: [
  120. .sendInitialMetadata(metadata.copy()),
  121. .receiveInitialMetadata
  122. ],
  123. completion: nil))
  124. try perform(OperationGroup(call: self,
  125. operations: [.receiveStatusOnClient],
  126. completion: completion != nil
  127. ? { op in completion?(CallResult(op)) }
  128. : nil))
  129. return
  130. }
  131. try perform(OperationGroup(call: self,
  132. operations: operations,
  133. completion: completion != nil
  134. ? { op in completion?(CallResult(op)) }
  135. : nil))
  136. }
  137. /// Sends a message over a streaming connection.
  138. ///
  139. /// Parameter data: the message data to send
  140. /// - Throws: `CallError` if fails to call. `CallWarning` if blocked.
  141. public func sendMessage(data: Data, completion: ((Error?) -> Void)? = nil) throws {
  142. messageQueueEmpty.enter()
  143. try sendMutex.synchronize {
  144. if writing {
  145. if let messageQueueMaxLength = Call.messageQueueMaxLength,
  146. messageQueue.count >= messageQueueMaxLength {
  147. throw CallWarning.blocked
  148. }
  149. messageQueue.append((dataToSend: data, completion: completion))
  150. } else {
  151. writing = true
  152. try sendWithoutBlocking(data: data, completion: completion)
  153. }
  154. }
  155. }
  156. /// helper for sending queued messages
  157. private func sendWithoutBlocking(data: Data, completion: ((Error?) -> Void)?) throws {
  158. try perform(OperationGroup(call: self,
  159. operations: [.sendMessage(ByteBuffer(data: data))]) { operationGroup in
  160. // Always enqueue the next message, even if sending this one failed. This ensures that all send completion
  161. // handlers are called eventually.
  162. self.sendMutex.synchronize {
  163. // if there are messages pending, send the next one
  164. if self.messageQueue.count > 0 {
  165. let (nextMessage, nextCompletionHandler) = self.messageQueue.removeFirst()
  166. do {
  167. try self.sendWithoutBlocking(data: nextMessage, completion: nextCompletionHandler)
  168. } catch {
  169. nextCompletionHandler?(error)
  170. }
  171. } else {
  172. // otherwise, we are finished writing
  173. self.writing = false
  174. }
  175. }
  176. completion?(operationGroup.success ? nil : CallError.unknown)
  177. self.messageQueueEmpty.leave()
  178. })
  179. }
  180. // Receive a message over a streaming connection.
  181. /// - Throws: `CallError` if fails to call.
  182. public func closeAndReceiveMessage(completion: @escaping (CallResult) -> Void) throws {
  183. try perform(OperationGroup(call: self, operations: [.sendCloseFromClient, .receiveMessage]) { operationGroup in
  184. completion(CallResult(operationGroup))
  185. })
  186. }
  187. // Receive a message over a streaming connection.
  188. /// - Throws: `CallError` if fails to call.
  189. public func receiveMessage(completion: @escaping (CallResult) -> Void) throws {
  190. try perform(OperationGroup(call: self, operations: [.receiveMessage]) { operationGroup in
  191. completion(CallResult(operationGroup))
  192. })
  193. }
  194. // Closes a streaming connection.
  195. /// - Throws: `CallError` if fails to call.
  196. public func close(completion: (() -> Void)? = nil) throws {
  197. try perform(OperationGroup(call: self, operations: [.sendCloseFromClient],
  198. completion: completion != nil
  199. ? { op in completion?() }
  200. : nil))
  201. }
  202. // Get the current message queue length
  203. public func messageQueueLength() -> Int {
  204. return messageQueue.count
  205. }
  206. /// Finishes the request side of this call, notifies the server that the RPC should be cancelled,
  207. /// and finishes the response side of the call with an error of code CANCELED.
  208. public func cancel() {
  209. Call.callMutex.synchronize {
  210. cgrpc_call_cancel(underlyingCall)
  211. }
  212. }
  213. }