Call.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. #endif
  36. import Foundation
  37. public enum CallError : Error {
  38. case ok
  39. case unknown
  40. case notOnServer
  41. case notOnClient
  42. case alreadyAccepted
  43. case alreadyInvoked
  44. case notInvoked
  45. case alreadyFinished
  46. case tooManyOperations
  47. case invalidFlags
  48. case invalidMetadata
  49. case invalidMessage
  50. case notServerCompletionQueue
  51. case batchTooBig
  52. case payloadTypeMismatch
  53. static func callError(grpcCallError error: grpc_call_error) -> CallError {
  54. switch(error) {
  55. case GRPC_CALL_OK:
  56. return .ok
  57. case GRPC_CALL_ERROR:
  58. return .unknown
  59. case GRPC_CALL_ERROR_NOT_ON_SERVER:
  60. return .notOnServer
  61. case GRPC_CALL_ERROR_NOT_ON_CLIENT:
  62. return .notOnClient
  63. case GRPC_CALL_ERROR_ALREADY_ACCEPTED:
  64. return .alreadyAccepted
  65. case GRPC_CALL_ERROR_ALREADY_INVOKED:
  66. return .alreadyInvoked
  67. case GRPC_CALL_ERROR_NOT_INVOKED:
  68. return .notInvoked
  69. case GRPC_CALL_ERROR_ALREADY_FINISHED:
  70. return .alreadyFinished
  71. case GRPC_CALL_ERROR_TOO_MANY_OPERATIONS:
  72. return .tooManyOperations
  73. case GRPC_CALL_ERROR_INVALID_FLAGS:
  74. return .invalidFlags
  75. case GRPC_CALL_ERROR_INVALID_METADATA:
  76. return .invalidMetadata
  77. case GRPC_CALL_ERROR_INVALID_MESSAGE:
  78. return .invalidMessage
  79. case GRPC_CALL_ERROR_NOT_SERVER_COMPLETION_QUEUE:
  80. return .notServerCompletionQueue
  81. case GRPC_CALL_ERROR_BATCH_TOO_BIG:
  82. return .batchTooBig
  83. case GRPC_CALL_ERROR_PAYLOAD_TYPE_MISMATCH:
  84. return .payloadTypeMismatch
  85. default:
  86. return .unknown
  87. }
  88. }
  89. }
  90. public struct CallResult {
  91. public var statusCode : Int
  92. public var statusMessage : String?
  93. public var resultData : Data?
  94. public var initialMetadata : Metadata?
  95. public var trailingMetadata : Metadata?
  96. }
  97. /// A gRPC API call
  98. public class Call {
  99. /// Shared mutex for synchronizing calls to cgrpc_call_perform()
  100. static let callMutex = Mutex()
  101. /// Maximum number of messages that can be queued
  102. static var maximumQueuedMessages = 10
  103. /// Pointer to underlying C representation
  104. private var underlyingCall : UnsafeMutableRawPointer
  105. /// Completion queue used for call
  106. private var completionQueue: CompletionQueue
  107. /// True if this instance is responsible for deleting the underlying C representation
  108. private var owned : Bool
  109. /// A queue of pending messages to send over the call
  110. private var pendingMessages : Array<Data>
  111. /// True if a message write operation is underway
  112. private var writing : Bool
  113. /// Mutex for synchronizing message sending
  114. private var sendMutex : Mutex
  115. /// Dispatch queue used for sending messages asynchronously
  116. private var messageDispatchQueue: DispatchQueue = DispatchQueue.global()
  117. /// Initializes a Call representation
  118. ///
  119. /// - Parameter call: the underlying C representation
  120. /// - Parameter owned: true if this instance is responsible for deleting the underlying call
  121. init(underlyingCall: UnsafeMutableRawPointer, owned: Bool, completionQueue: CompletionQueue) {
  122. self.underlyingCall = underlyingCall
  123. self.owned = owned
  124. self.completionQueue = completionQueue
  125. self.pendingMessages = []
  126. self.writing = false
  127. self.sendMutex = Mutex()
  128. }
  129. deinit {
  130. if (owned) {
  131. cgrpc_call_destroy(underlyingCall)
  132. }
  133. }
  134. /// Initiate performance of a group of operations without waiting for completion
  135. ///
  136. /// - Parameter operations: group of operations to be performed
  137. /// - Returns: the result of initiating the call
  138. internal func perform(_ operations: OperationGroup) throws -> Void {
  139. completionQueue.register(operations)
  140. Call.callMutex.lock()
  141. let error = cgrpc_call_perform(underlyingCall, operations.underlyingOperations, operations.tag)
  142. Call.callMutex.unlock()
  143. if error != GRPC_CALL_OK {
  144. throw CallError.callError(grpcCallError:error)
  145. }
  146. }
  147. /// Performs a nonstreaming gRPC API call
  148. ///
  149. /// - Parameter message: data containing the message to send
  150. /// - Parameter metadata: metadata to send with the call
  151. /// - Parameter callback: a blocko to call with a CallResponse object containing call results
  152. public func perform(message: Data,
  153. metadata: Metadata,
  154. completion: @escaping (CallResult) throws -> Void)
  155. throws -> Void {
  156. let messageBuffer = ByteBuffer(data:message)
  157. let operations = OperationGroup(call:self,
  158. operations:[.sendInitialMetadata(metadata),
  159. .sendMessage(messageBuffer),
  160. .sendCloseFromClient,
  161. .receiveInitialMetadata,
  162. .receiveStatusOnClient,
  163. .receiveMessage],
  164. completion:
  165. {(operationGroup) in
  166. if operationGroup.success {
  167. try completion(CallResult(statusCode:operationGroup.receivedStatusCode()!,
  168. statusMessage:operationGroup.receivedStatusMessage(),
  169. resultData:operationGroup.receivedMessage()?.data(),
  170. initialMetadata:operationGroup.receivedInitialMetadata(),
  171. trailingMetadata:operationGroup.receivedTrailingMetadata()))
  172. } else {
  173. try completion(CallResult(statusCode:0,
  174. statusMessage:nil,
  175. resultData:nil,
  176. initialMetadata:nil,
  177. trailingMetadata:nil))
  178. }
  179. })
  180. try self.perform(operations)
  181. }
  182. /// start a streaming connection
  183. ///
  184. /// Parameter metadata: initial metadata to send
  185. public func start(metadata: Metadata) throws -> Void {
  186. try self.sendInitialMetadata(metadata: metadata)
  187. try self.receiveInitialMetadata()
  188. try self.receiveStatus()
  189. }
  190. /// send a message over a streaming connection
  191. ///
  192. /// Parameter data: the message data to send
  193. /// Returns: true if the message could be queued or sent, false if the queue is full
  194. public func sendMessage(data: Data) -> Bool {
  195. self.sendMutex.lock()
  196. defer {self.sendMutex.unlock()}
  197. if self.writing {
  198. if self.pendingMessages.count == Call.maximumQueuedMessages {
  199. return false
  200. }
  201. self.pendingMessages.append(data) // TODO: return something if we can't accept another message
  202. } else {
  203. self.writing = true
  204. do {
  205. try self.sendWithoutBlocking(data: data)
  206. } catch (let callError) {
  207. print("grpc error: \(callError)")
  208. }
  209. }
  210. return true
  211. }
  212. /// helper for sending queued messages
  213. private func sendWithoutBlocking(data: Data) throws -> Void {
  214. let operations = OperationGroup(call:self, operations:[.sendMessage(ByteBuffer(data:data))])
  215. {(operationGroup) in
  216. if operationGroup.success {
  217. self.messageDispatchQueue.async {
  218. self.sendMutex.synchronize {
  219. // if there are messages pending, send the next one
  220. if self.pendingMessages.count > 0 {
  221. let nextMessage = self.pendingMessages.first!
  222. self.pendingMessages.removeFirst()
  223. do {
  224. try self.sendWithoutBlocking(data: nextMessage)
  225. } catch (let callError) {
  226. print("grpc error: \(callError)")
  227. }
  228. } else {
  229. // otherwise, we are finished writing
  230. self.writing = false
  231. }
  232. }
  233. }
  234. } else {
  235. // TODO: if the event failed, shut down
  236. }
  237. }
  238. try self.perform(operations)
  239. }
  240. // receive a message over a streaming connection
  241. public func receiveMessage(callback:@escaping ((Data!) throws -> Void)) throws -> Void {
  242. let operations = OperationGroup(call:self, operations:[.receiveMessage])
  243. {(operationGroup) in
  244. if operationGroup.success {
  245. if let messageBuffer = operationGroup.receivedMessage() {
  246. try callback(messageBuffer.data())
  247. }
  248. }
  249. }
  250. try self.perform(operations)
  251. }
  252. // send initial metadata over a streaming connection
  253. private func sendInitialMetadata(metadata: Metadata) throws -> Void {
  254. let operations = OperationGroup(call:self, operations:[.sendInitialMetadata(metadata)])
  255. {(operationGroup) in
  256. if operationGroup.success {
  257. } else {
  258. return
  259. }
  260. }
  261. try self.perform(operations)
  262. }
  263. // receive initial metadata from a streaming connection
  264. private func receiveInitialMetadata() throws -> Void {
  265. let operations = OperationGroup(call:self, operations:[.receiveInitialMetadata])
  266. {(operationGroup) in
  267. if operationGroup.success {
  268. if let initialMetadata = operationGroup.receivedInitialMetadata() {
  269. for j in 0..<initialMetadata.count() {
  270. print("Received initial metadata -> " + initialMetadata.key(index:j) + " : " + initialMetadata.value(index:j))
  271. }
  272. }
  273. }
  274. }
  275. try self.perform(operations)
  276. }
  277. // receive status from a streaming connection
  278. private func receiveStatus() throws -> Void {
  279. let operations = OperationGroup(call:self, operations:[.receiveStatusOnClient])
  280. {(operationGroup) in
  281. if operationGroup.success {
  282. print("status = \(operationGroup.receivedStatusCode()), \(operationGroup.receivedStatusMessage())")
  283. }
  284. }
  285. try self.perform(operations)
  286. }
  287. // close a streaming connection
  288. public func close(completion:@escaping (() -> Void)) throws -> Void {
  289. let operations = OperationGroup(call:self, operations:[.sendCloseFromClient])
  290. {(operationGroup) in
  291. if operationGroup.success {
  292. completion()
  293. }
  294. }
  295. try self.perform(operations)
  296. }
  297. }