Call.swift 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. /// Singleton class that provides a mutex for synchronizing calls to cgrpc_call_perform()
  38. private class CallLock {
  39. var mutex : Mutex
  40. private init() {
  41. mutex = Mutex()
  42. }
  43. static let sharedInstance = CallLock()
  44. }
  45. public typealias CallCompletion = (Int, String?, Data?, Metadata?, Metadata?) -> Void
  46. public typealias SendMessageCompletion = (grpc_call_error) -> Void
  47. /// A gRPC API call
  48. public class Call {
  49. /// Pointer to underlying C representation
  50. private var call : UnsafeMutableRawPointer!
  51. /// Completion queue used for call
  52. private var completionQueue: CompletionQueue
  53. /// True if this instance is responsible for deleting the underlying C representation
  54. private var owned : Bool
  55. /// A queue of pending messages to send over the call
  56. private var pendingMessages : Array<Data>
  57. /// True if a message write operation is underway
  58. private var writing : Bool
  59. /// Initializes a Call representation
  60. ///
  61. /// - Parameter call: the underlying C representation
  62. /// - Parameter owned: true if this instance is responsible for deleting the underlying call
  63. init(call: UnsafeMutableRawPointer, owned: Bool, completionQueue: CompletionQueue) {
  64. self.call = call
  65. self.owned = owned
  66. self.completionQueue = completionQueue
  67. self.pendingMessages = []
  68. self.writing = false
  69. }
  70. deinit {
  71. if (owned) {
  72. cgrpc_call_destroy(call)
  73. }
  74. }
  75. /// Initiate performance of a call without waiting for completion
  76. ///
  77. /// - Parameter operations: array of operations to be performed
  78. /// - Parameter tag: integer tag that will be attached to these operations
  79. /// - Returns: the result of initiating the call
  80. func performOperations(operations: OperationGroup,
  81. tag: Int64,
  82. completionQueue: CompletionQueue)
  83. -> grpc_call_error {
  84. let mutex = CallLock.sharedInstance.mutex
  85. mutex.lock()
  86. let error = cgrpc_call_perform(call, operations.operations, tag)
  87. mutex.unlock()
  88. return error
  89. }
  90. /// Performs a nonstreaming gRPC API call
  91. ///
  92. /// - Parameter message: a ByteBuffer containing the message to send
  93. /// - Parameter metadata: metadata to send with the call
  94. /// - Returns: a CallResponse object containing results of the call
  95. public func performNonStreamingCall(messageData: Data,
  96. metadata: Metadata,
  97. completion: @escaping CallCompletion) -> grpc_call_error {
  98. let messageBuffer = ByteBuffer(data:messageData)
  99. let operation_sendInitialMetadata = Operation_SendInitialMetadata(metadata:metadata);
  100. let operation_sendMessage = Operation_SendMessage(message:messageBuffer)
  101. let operation_sendCloseFromClient = Operation_SendCloseFromClient()
  102. let operation_receiveInitialMetadata = Operation_ReceiveInitialMetadata()
  103. let operation_receiveStatusOnClient = Operation_ReceiveStatusOnClient()
  104. let operation_receiveMessage = Operation_ReceiveMessage()
  105. let group = OperationGroup(call:self,
  106. operations:[operation_sendInitialMetadata,
  107. operation_sendMessage,
  108. operation_sendCloseFromClient,
  109. operation_receiveInitialMetadata,
  110. operation_receiveStatusOnClient,
  111. operation_receiveMessage],
  112. completion:
  113. {(success) in
  114. if success {
  115. completion(operation_receiveStatusOnClient.status(),
  116. operation_receiveStatusOnClient.statusDetails(),
  117. operation_receiveMessage.message()?.data(),
  118. operation_receiveInitialMetadata.metadata(),
  119. operation_receiveStatusOnClient.metadata())
  120. } else {
  121. completion(0, nil, nil, nil, nil)
  122. }
  123. })
  124. return self.perform(operations: group)
  125. }
  126. // perform a group of operations (used internally)
  127. private func perform(operations: OperationGroup) -> grpc_call_error {
  128. self.completionQueue.operationGroups[operations.tag] = operations
  129. return performOperations(operations:operations,
  130. tag:operations.tag,
  131. completionQueue: self.completionQueue)
  132. }
  133. // start a streaming connection
  134. public func start(metadata: Metadata) -> grpc_call_error {
  135. var error : grpc_call_error
  136. error = self.sendInitialMetadata(metadata: metadata)
  137. if error != GRPC_CALL_OK {
  138. return error
  139. }
  140. error = self.receiveInitialMetadata()
  141. if error != GRPC_CALL_OK {
  142. return error
  143. }
  144. return self.receiveStatus()
  145. }
  146. // send a message over a streaming connection
  147. public func sendMessage(data: Data,
  148. callback:@escaping SendMessageCompletion = {(error) in })
  149. -> Void {
  150. DispatchQueue.main.async {
  151. if self.writing {
  152. self.pendingMessages.append(data) // TODO: return something if we can't accept another message
  153. callback(GRPC_CALL_OK)
  154. } else {
  155. self.writing = true
  156. let error = self.sendWithoutBlocking(data: data)
  157. callback(error)
  158. }
  159. }
  160. }
  161. private func sendWithoutBlocking(data: Data) -> grpc_call_error {
  162. let messageBuffer = ByteBuffer(data:data)
  163. let operation_sendMessage = Operation_SendMessage(message:messageBuffer)
  164. let operations = OperationGroup(call:self, operations:[operation_sendMessage])
  165. { (event) in
  166. // TODO: if the event failed, shut down
  167. DispatchQueue.main.async {
  168. if self.pendingMessages.count > 0 {
  169. let nextMessage = self.pendingMessages.first!
  170. self.pendingMessages.removeFirst()
  171. _ = self.sendWithoutBlocking(data: nextMessage)
  172. } else {
  173. self.writing = false
  174. }
  175. }
  176. }
  177. return self.perform(operations:operations)
  178. }
  179. // receive a message over a streaming connection
  180. public func receiveMessage(callback:@escaping ((Data!) -> Void)) -> grpc_call_error {
  181. let operation_receiveMessage = Operation_ReceiveMessage()
  182. let operations = OperationGroup(call:self, operations:[operation_receiveMessage])
  183. { (event) in
  184. if let messageBuffer = operation_receiveMessage.message() {
  185. callback(messageBuffer.data())
  186. }
  187. }
  188. return self.perform(operations:operations)
  189. }
  190. // send initial metadata over a streaming connection
  191. private func sendInitialMetadata(metadata: Metadata) -> grpc_call_error {
  192. let operation_sendInitialMetadata = Operation_SendInitialMetadata(metadata:metadata);
  193. let operations = OperationGroup(call:self, operations:[operation_sendInitialMetadata])
  194. { (success) in
  195. if (success) {
  196. print("call successful")
  197. } else {
  198. return
  199. }
  200. }
  201. return self.perform(operations:operations)
  202. }
  203. // receive initial metadata from a streaming connection
  204. private func receiveInitialMetadata() -> grpc_call_error {
  205. let operation_receiveInitialMetadata = Operation_ReceiveInitialMetadata()
  206. let operations = OperationGroup(call:self, operations:[operation_receiveInitialMetadata])
  207. { (event) in
  208. let initialMetadata = operation_receiveInitialMetadata.metadata()
  209. for j in 0..<initialMetadata.count() {
  210. print("Received initial metadata -> " + initialMetadata.key(index:j) + " : " + initialMetadata.value(index:j))
  211. }
  212. }
  213. return self.perform(operations:operations)
  214. }
  215. // receive status from a streaming connection
  216. private func receiveStatus() -> grpc_call_error {
  217. let operation_receiveStatus = Operation_ReceiveStatusOnClient()
  218. let operations = OperationGroup(call:self,
  219. operations:[operation_receiveStatus])
  220. { (event) in
  221. print("status = \(operation_receiveStatus.status()), \(operation_receiveStatus.statusDetails())")
  222. }
  223. return self.perform(operations:operations)
  224. }
  225. // close a streaming connection
  226. public func close(completion:@escaping (() -> Void)) -> grpc_call_error {
  227. let operation_sendCloseFromClient = Operation_SendCloseFromClient()
  228. let operations = OperationGroup(call:self, operations:[operation_sendCloseFromClient])
  229. { (event) in
  230. completion()
  231. }
  232. return self.perform(operations:operations)
  233. }
  234. }