Call.swift 9.7 KB

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