Call.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /*
  2. *
  3. * Copyright 2016, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. #if SWIFT_PACKAGE
  34. import CgRPC
  35. import Dispatch
  36. #endif
  37. import Foundation
  38. public enum CallStyle {
  39. case unary
  40. case serverStreaming
  41. case clientStreaming
  42. case bidiStreaming
  43. }
  44. public enum CallWarning : Error {
  45. case blocked
  46. }
  47. public enum CallError : Error {
  48. case ok
  49. case unknown
  50. case notOnServer
  51. case notOnClient
  52. case alreadyAccepted
  53. case alreadyInvoked
  54. case notInvoked
  55. case alreadyFinished
  56. case tooManyOperations
  57. case invalidFlags
  58. case invalidMetadata
  59. case invalidMessage
  60. case notServerCompletionQueue
  61. case batchTooBig
  62. case payloadTypeMismatch
  63. static func callError(grpcCallError error: grpc_call_error) -> CallError {
  64. switch(error) {
  65. case GRPC_CALL_OK:
  66. return .ok
  67. case GRPC_CALL_ERROR:
  68. return .unknown
  69. case GRPC_CALL_ERROR_NOT_ON_SERVER:
  70. return .notOnServer
  71. case GRPC_CALL_ERROR_NOT_ON_CLIENT:
  72. return .notOnClient
  73. case GRPC_CALL_ERROR_ALREADY_ACCEPTED:
  74. return .alreadyAccepted
  75. case GRPC_CALL_ERROR_ALREADY_INVOKED:
  76. return .alreadyInvoked
  77. case GRPC_CALL_ERROR_NOT_INVOKED:
  78. return .notInvoked
  79. case GRPC_CALL_ERROR_ALREADY_FINISHED:
  80. return .alreadyFinished
  81. case GRPC_CALL_ERROR_TOO_MANY_OPERATIONS:
  82. return .tooManyOperations
  83. case GRPC_CALL_ERROR_INVALID_FLAGS:
  84. return .invalidFlags
  85. case GRPC_CALL_ERROR_INVALID_METADATA:
  86. return .invalidMetadata
  87. case GRPC_CALL_ERROR_INVALID_MESSAGE:
  88. return .invalidMessage
  89. case GRPC_CALL_ERROR_NOT_SERVER_COMPLETION_QUEUE:
  90. return .notServerCompletionQueue
  91. case GRPC_CALL_ERROR_BATCH_TOO_BIG:
  92. return .batchTooBig
  93. case GRPC_CALL_ERROR_PAYLOAD_TYPE_MISMATCH:
  94. return .payloadTypeMismatch
  95. default:
  96. return .unknown
  97. }
  98. }
  99. }
  100. public struct CallResult {
  101. public var statusCode : Int
  102. public var statusMessage : String?
  103. public var resultData : Data?
  104. public var initialMetadata : Metadata?
  105. public var trailingMetadata : Metadata?
  106. fileprivate init(_ op : OperationGroup) {
  107. if (op.success) {
  108. self.statusCode = op.receivedStatusCode()!
  109. self.statusMessage = op.receivedStatusMessage()
  110. self.resultData = op.receivedMessage()?.data()
  111. self.initialMetadata = op.receivedInitialMetadata()
  112. self.trailingMetadata = op.receivedTrailingMetadata()
  113. } else {
  114. self.statusCode = 0
  115. self.statusMessage = nil
  116. self.resultData = nil
  117. self.initialMetadata = nil
  118. self.trailingMetadata = nil
  119. }
  120. }
  121. }
  122. /// A gRPC API call
  123. public class Call {
  124. /// Shared mutex for synchronizing calls to cgrpc_call_perform()
  125. private static let callMutex = Mutex()
  126. /// Maximum number of messages that can be queued
  127. private static var maximumQueuedMessages = 10
  128. /// Pointer to underlying C representation
  129. private var underlyingCall : UnsafeMutableRawPointer
  130. /// Completion queue used for call
  131. private var completionQueue: CompletionQueue
  132. /// True if this instance is responsible for deleting the underlying C representation
  133. private var owned : Bool
  134. /// A queue of pending messages to send over the call
  135. private var pendingMessages : Array<Data>
  136. /// True if a message write operation is underway
  137. private var writing : Bool
  138. /// Mutex for synchronizing message sending
  139. private var sendMutex : Mutex
  140. /// Dispatch queue used for sending messages asynchronously
  141. private var messageDispatchQueue: DispatchQueue = DispatchQueue.global()
  142. /// Initializes a Call representation
  143. ///
  144. /// - Parameter call: the underlying C representation
  145. /// - Parameter owned: true if this instance is responsible for deleting the underlying call
  146. init(underlyingCall: UnsafeMutableRawPointer, owned: Bool, completionQueue: CompletionQueue) {
  147. self.underlyingCall = underlyingCall
  148. self.owned = owned
  149. self.completionQueue = completionQueue
  150. self.pendingMessages = []
  151. self.writing = false
  152. self.sendMutex = Mutex()
  153. }
  154. deinit {
  155. if (owned) {
  156. cgrpc_call_destroy(underlyingCall)
  157. }
  158. }
  159. /// Initiates performance of a group of operations without waiting for completion.
  160. ///
  161. /// - Parameter operations: group of operations to be performed
  162. /// - Returns: the result of initiating the call
  163. internal func perform(_ operations: OperationGroup) throws -> Void {
  164. completionQueue.register(operations)
  165. Call.callMutex.lock()
  166. let error = cgrpc_call_perform(underlyingCall, operations.underlyingOperations, operations.tag)
  167. Call.callMutex.unlock()
  168. if error != GRPC_CALL_OK {
  169. throw CallError.callError(grpcCallError:error)
  170. }
  171. }
  172. /// Starts a gRPC API call.
  173. ///
  174. /// - Parameter style: the style of call to start
  175. /// - Parameter metadata: metadata to send with the call
  176. /// - Parameter message: data containing the message to send (.unary and .serverStreaming only)
  177. /// - Parameter callback: a block to call with call results
  178. public func start(_ style: CallStyle,
  179. metadata: Metadata,
  180. message: Data? = nil,
  181. completion: @escaping (CallResult) -> Void)
  182. throws -> Void {
  183. var operations : [Operation] = []
  184. switch style {
  185. case .unary:
  186. guard let message = message else {
  187. throw CallError.invalidMessage
  188. }
  189. operations = [.sendInitialMetadata(metadata.copy() as! Metadata),
  190. .receiveInitialMetadata,
  191. .receiveStatusOnClient,
  192. .sendMessage(ByteBuffer(data:message)),
  193. .sendCloseFromClient,
  194. .receiveMessage]
  195. case .serverStreaming:
  196. guard let message = message else {
  197. throw CallError.invalidMessage
  198. }
  199. operations = [.sendInitialMetadata(metadata.copy() as! Metadata),
  200. .receiveInitialMetadata,
  201. .receiveStatusOnClient,
  202. .sendMessage(ByteBuffer(data:message)),
  203. .sendCloseFromClient]
  204. case .clientStreaming, .bidiStreaming:
  205. operations = [.sendInitialMetadata(metadata.copy() as! Metadata),
  206. .receiveInitialMetadata,
  207. .receiveStatusOnClient]
  208. }
  209. try self.perform(OperationGroup(call:self,
  210. operations:operations,
  211. completion:{(op) in completion(CallResult(op))}))
  212. }
  213. /// Sends a message over a streaming connection.
  214. ///
  215. /// Parameter data: the message data to send
  216. public func sendMessage(data: Data) throws {
  217. self.sendMutex.lock()
  218. defer {self.sendMutex.unlock()}
  219. if self.writing {
  220. if self.pendingMessages.count == Call.maximumQueuedMessages {
  221. throw CallWarning.blocked
  222. }
  223. self.pendingMessages.append(data)
  224. } else {
  225. self.writing = true
  226. try self.sendWithoutBlocking(data: data)
  227. }
  228. }
  229. /// helper for sending queued messages
  230. private func sendWithoutBlocking(data: Data) throws -> Void {
  231. try self.perform(OperationGroup(call:self,
  232. operations:[.sendMessage(ByteBuffer(data:data))])
  233. {(operationGroup) in
  234. if operationGroup.success {
  235. self.messageDispatchQueue.async {
  236. self.sendMutex.synchronize {
  237. // if there are messages pending, send the next one
  238. if self.pendingMessages.count > 0 {
  239. let nextMessage = self.pendingMessages.first!
  240. self.pendingMessages.removeFirst()
  241. do {
  242. try self.sendWithoutBlocking(data: nextMessage)
  243. } catch (let callError) {
  244. print("Call sendWithoutBlocking: grpc error \(callError)")
  245. }
  246. } else {
  247. // otherwise, we are finished writing
  248. self.writing = false
  249. }
  250. }
  251. }
  252. } else {
  253. // TODO: if the event failed, shut down
  254. self.writing = false
  255. }
  256. })
  257. }
  258. // Receive a message over a streaming connection.
  259. public func receiveMessage(callback:@escaping ((Data!) throws -> Void)) throws -> Void {
  260. try self.perform(OperationGroup(call:self, operations:[.receiveMessage])
  261. {(operationGroup) in
  262. if operationGroup.success {
  263. if let messageBuffer = operationGroup.receivedMessage() {
  264. try callback(messageBuffer.data())
  265. } else {
  266. try callback(nil) // an empty response signals the end of a connection
  267. }
  268. }
  269. })
  270. }
  271. // Closes a streaming connection.
  272. public func close(completion:@escaping (() -> Void)) throws -> Void {
  273. try self.perform(OperationGroup(call:self, operations:[.sendCloseFromClient])
  274. {(operationGroup) in completion()
  275. })
  276. }
  277. }