Call.swift 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. /// The argument to `completion` will always have `.success = true`
  88. /// because operations containing `.receiveCloseOnClient` always succeed.
  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. try sendMutex.synchronize {
  145. if writing {
  146. if let messageQueueMaxLength = Call.messageQueueMaxLength,
  147. messageQueue.count >= messageQueueMaxLength {
  148. throw CallWarning.blocked
  149. }
  150. messageQueue.append((dataToSend: data, completion: completion))
  151. } else {
  152. writing = true
  153. try sendWithoutBlocking(data: data, completion: completion)
  154. }
  155. messageQueueEmpty.enter()
  156. }
  157. }
  158. /// helper for sending queued messages
  159. private func sendWithoutBlocking(data: Data, completion: ((Error?) -> Void)?) throws {
  160. try perform(OperationGroup(
  161. call: self,
  162. operations: [.sendMessage(ByteBuffer(data: data))]) { operationGroup in
  163. // Always enqueue the next message, even if sending this one failed. This ensures that all send completion
  164. // handlers are called eventually.
  165. self.sendMutex.synchronize {
  166. // if there are messages pending, send the next one
  167. if self.messageQueue.count > 0 {
  168. let (nextMessage, nextCompletionHandler) = self.messageQueue.removeFirst()
  169. do {
  170. try self.sendWithoutBlocking(data: nextMessage, completion: nextCompletionHandler)
  171. } catch {
  172. nextCompletionHandler?(error)
  173. }
  174. } else {
  175. // otherwise, we are finished writing
  176. self.writing = false
  177. }
  178. }
  179. completion?(operationGroup.success ? nil : CallError.unknown)
  180. self.messageQueueEmpty.leave()
  181. })
  182. }
  183. // Receive a message over a streaming connection.
  184. /// - Throws: `CallError` if fails to call.
  185. public func closeAndReceiveMessage(completion: @escaping (CallResult) -> Void) throws {
  186. try perform(OperationGroup(call: self, operations: [.sendCloseFromClient, .receiveMessage]) { operationGroup in
  187. completion(CallResult(operationGroup))
  188. })
  189. }
  190. // Receive a message over a streaming connection.
  191. /// - Throws: `CallError` if fails to call.
  192. public func receiveMessage(completion: @escaping (CallResult) -> Void) throws {
  193. try perform(OperationGroup(call: self, operations: [.receiveMessage]) { operationGroup in
  194. completion(CallResult(operationGroup))
  195. })
  196. }
  197. // Closes a streaming connection.
  198. /// - Throws: `CallError` if fails to call.
  199. public func close(completion: (() -> Void)? = nil) throws {
  200. try perform(OperationGroup(call: self, operations: [.sendCloseFromClient],
  201. completion: completion != nil
  202. ? { op in completion?() }
  203. : nil))
  204. }
  205. // Get the current message queue length
  206. public func messageQueueLength() -> Int {
  207. return messageQueue.count
  208. }
  209. /// Finishes the request side of this call, notifies the server that the RPC should be cancelled,
  210. /// and finishes the response side of the call with an error of code CANCELED.
  211. public func cancel() {
  212. Call.callMutex.synchronize {
  213. cgrpc_call_cancel(underlyingCall)
  214. }
  215. }
  216. }