Call.swift 9.7 KB

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