Call.swift 10 KB

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