Call.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. public enum CallError : Error {
  38. case ok
  39. case unknown
  40. case notOnServer
  41. case notOnClient
  42. case alreadyAccepted
  43. case alreadyInvoked
  44. case notInvoked
  45. case alreadyFinished
  46. case tooManyOperations
  47. case invalidFlags
  48. case invalidMetadata
  49. case invalidMessage
  50. case notServerCompletionQueue
  51. case batchTooBig
  52. case payloadTypeMismatch
  53. static func callError(grpcCallError error: grpc_call_error) -> CallError {
  54. switch(error) {
  55. case GRPC_CALL_OK:
  56. return .ok
  57. case GRPC_CALL_ERROR:
  58. return .unknown
  59. case GRPC_CALL_ERROR_NOT_ON_SERVER:
  60. return .notOnServer
  61. case GRPC_CALL_ERROR_NOT_ON_CLIENT:
  62. return .notOnClient
  63. case GRPC_CALL_ERROR_ALREADY_ACCEPTED:
  64. return .alreadyAccepted
  65. case GRPC_CALL_ERROR_ALREADY_INVOKED:
  66. return .alreadyInvoked
  67. case GRPC_CALL_ERROR_NOT_INVOKED:
  68. return .notInvoked
  69. case GRPC_CALL_ERROR_ALREADY_FINISHED:
  70. return .alreadyFinished
  71. case GRPC_CALL_ERROR_TOO_MANY_OPERATIONS:
  72. return .tooManyOperations
  73. case GRPC_CALL_ERROR_INVALID_FLAGS:
  74. return .invalidFlags
  75. case GRPC_CALL_ERROR_INVALID_METADATA:
  76. return .invalidMetadata
  77. case GRPC_CALL_ERROR_INVALID_MESSAGE:
  78. return .invalidMessage
  79. case GRPC_CALL_ERROR_NOT_SERVER_COMPLETION_QUEUE:
  80. return .notServerCompletionQueue
  81. case GRPC_CALL_ERROR_BATCH_TOO_BIG:
  82. return .batchTooBig
  83. case GRPC_CALL_ERROR_PAYLOAD_TYPE_MISMATCH:
  84. return .payloadTypeMismatch
  85. default:
  86. return .unknown
  87. }
  88. }
  89. }
  90. public struct CallResult {
  91. public var statusCode : Int
  92. public var statusMessage : String?
  93. public var resultData : Data?
  94. public var initialMetadata : Metadata?
  95. public var trailingMetadata : Metadata?
  96. }
  97. /// A gRPC API call
  98. public class Call {
  99. /// Shared mutex for synchronizing calls to cgrpc_call_perform()
  100. static let callMutex = Mutex()
  101. /// Pointer to underlying C representation
  102. private var underlyingCall : UnsafeMutableRawPointer
  103. /// Completion queue used for call
  104. private var completionQueue: CompletionQueue
  105. /// True if this instance is responsible for deleting the underlying C representation
  106. private var owned : Bool
  107. /// A queue of pending messages to send over the call
  108. private var pendingMessages : Array<Data>
  109. /// True if a message write operation is underway
  110. private var writing : Bool
  111. /// Mutex for synchronizing message sending
  112. private var sendMutex : Mutex
  113. /// Dispatch queue used for sending messages asynchronously
  114. private var messageDispatchQueue: DispatchQueue = DispatchQueue.global()
  115. /// Initializes a Call representation
  116. ///
  117. /// - Parameter call: the underlying C representation
  118. /// - Parameter owned: true if this instance is responsible for deleting the underlying call
  119. init(underlyingCall: UnsafeMutableRawPointer, owned: Bool, completionQueue: CompletionQueue) {
  120. self.underlyingCall = underlyingCall
  121. self.owned = owned
  122. self.completionQueue = completionQueue
  123. self.pendingMessages = []
  124. self.writing = false
  125. self.sendMutex = Mutex()
  126. }
  127. deinit {
  128. if (owned) {
  129. cgrpc_call_destroy(underlyingCall)
  130. }
  131. }
  132. /// Initiate performance of a group of operations without waiting for completion
  133. ///
  134. /// - Parameter operations: group of operations to be performed
  135. /// - Returns: the result of initiating the call
  136. func perform(_ operations: OperationGroup) throws -> Void {
  137. completionQueue.register(operations)
  138. Call.callMutex.lock()
  139. let error = cgrpc_call_perform(underlyingCall, operations.underlyingOperations, operations.tag)
  140. Call.callMutex.unlock()
  141. if error != GRPC_CALL_OK {
  142. throw CallError.callError(grpcCallError:error)
  143. }
  144. }
  145. /// Performs a nonstreaming gRPC API call
  146. ///
  147. /// - Parameter message: data containing the message to send
  148. /// - Parameter metadata: metadata to send with the call
  149. /// - Parameter callback: a blocko to call with a CallResponse object containing call results
  150. public func performNonStreamingCall(message: Data,
  151. metadata: Metadata,
  152. completion: @escaping (CallResult) throws -> Void)
  153. throws -> Void {
  154. let messageBuffer = ByteBuffer(data:message)
  155. let operations = OperationGroup(call:self,
  156. operations:[.sendInitialMetadata(metadata),
  157. .sendMessage(messageBuffer),
  158. .sendCloseFromClient,
  159. .receiveInitialMetadata,
  160. .receiveStatusOnClient,
  161. .receiveMessage],
  162. completion:
  163. {(operationGroup) in
  164. if operationGroup.success {
  165. try completion(CallResult(statusCode:operationGroup.receivedStatusCode()!,
  166. statusMessage:operationGroup.receivedStatusMessage(),
  167. resultData:operationGroup.receivedMessage()?.data(),
  168. initialMetadata:operationGroup.receivedInitialMetadata(),
  169. trailingMetadata:operationGroup.receivedTrailingMetadata()))
  170. } else {
  171. try completion(CallResult(statusCode:0,
  172. statusMessage:nil,
  173. resultData:nil,
  174. initialMetadata:nil,
  175. trailingMetadata:nil))
  176. }
  177. })
  178. try self.perform(operations)
  179. }
  180. // start a streaming connection
  181. public func start(metadata: Metadata) throws -> Void {
  182. try self.sendInitialMetadata(metadata: metadata)
  183. try self.receiveInitialMetadata()
  184. try self.receiveStatus()
  185. }
  186. // send a message over a streaming connection
  187. public func sendMessage(data: Data) -> Void {
  188. self.sendMutex.synchronize {
  189. if self.writing {
  190. self.pendingMessages.append(data) // TODO: return something if we can't accept another message
  191. } else {
  192. self.writing = true
  193. do {
  194. try self.sendWithoutBlocking(data: data)
  195. } catch (let callError) {
  196. print("grpc error: \(callError)")
  197. }
  198. }
  199. }
  200. }
  201. private func sendWithoutBlocking(data: Data) throws -> Void {
  202. let messageBuffer = ByteBuffer(data:data)
  203. let operations = OperationGroup(call:self, operations:[.sendMessage(messageBuffer)])
  204. {(operationGroup) in
  205. if operationGroup.success {
  206. self.messageDispatchQueue.async {
  207. self.sendMutex.synchronize {
  208. // if there are messages pending, send the next one
  209. if self.pendingMessages.count > 0 {
  210. let nextMessage = self.pendingMessages.first!
  211. self.pendingMessages.removeFirst()
  212. do {
  213. try self.sendWithoutBlocking(data: nextMessage)
  214. } catch (let callError) {
  215. print("grpc error: \(callError)")
  216. }
  217. } else {
  218. // otherwise, we are finished writing
  219. self.writing = false
  220. }
  221. }
  222. }
  223. } else {
  224. // TODO: if the event failed, shut down
  225. }
  226. }
  227. try self.perform(operations)
  228. }
  229. // receive a message over a streaming connection
  230. public func receiveMessage(callback:@escaping ((Data!) throws -> Void)) throws -> Void {
  231. let operations = OperationGroup(call:self, operations:[.receiveMessage])
  232. {(operationGroup) in
  233. if operationGroup.success {
  234. if let messageBuffer = operationGroup.receivedMessage() {
  235. try callback(messageBuffer.data())
  236. }
  237. }
  238. }
  239. try self.perform(operations)
  240. }
  241. // send initial metadata over a streaming connection
  242. private func sendInitialMetadata(metadata: Metadata) throws -> Void {
  243. let operations = OperationGroup(call:self, operations:[.sendInitialMetadata(metadata)])
  244. {(operationGroup) in
  245. if operationGroup.success {
  246. print("call successful")
  247. } else {
  248. return
  249. }
  250. }
  251. try self.perform(operations)
  252. }
  253. // receive initial metadata from a streaming connection
  254. private func receiveInitialMetadata() throws -> Void {
  255. let operations = OperationGroup(call:self, operations:[.receiveInitialMetadata])
  256. {(operationGroup) in
  257. if operationGroup.success {
  258. if let initialMetadata = operationGroup.receivedInitialMetadata() {
  259. for j in 0..<initialMetadata.count() {
  260. print("Received initial metadata -> " + initialMetadata.key(index:j) + " : " + initialMetadata.value(index:j))
  261. }
  262. }
  263. }
  264. }
  265. try self.perform(operations)
  266. }
  267. // receive status from a streaming connection
  268. private func receiveStatus() throws -> Void {
  269. let operations = OperationGroup(call:self, operations:[.receiveStatusOnClient])
  270. {(operationGroup) in
  271. if operationGroup.success {
  272. print("status = \(operationGroup.receivedStatusCode()), \(operationGroup.receivedStatusMessage())")
  273. }
  274. }
  275. try self.perform(operations)
  276. }
  277. // close a streaming connection
  278. public func close(completion:@escaping (() -> Void)) throws -> Void {
  279. let operations = OperationGroup(call:self, operations:[.sendCloseFromClient])
  280. {(operationGroup) in
  281. if operationGroup.success {
  282. completion()
  283. }
  284. }
  285. try self.perform(operations)
  286. }
  287. }