Call.swift 10 KB

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