Handler.swift 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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 // for String.Encoding
  37. /// A gRPC request handler
  38. public class Handler {
  39. /// Pointer to underlying C representation
  40. var underlyingHandler: UnsafeMutableRawPointer!
  41. /// Completion queue for handler response operations
  42. var completionQueue: CompletionQueue
  43. /// Metadata received with the request
  44. public var requestMetadata: Metadata
  45. /// A Call object that can be used to respond to the request
  46. var call: Call!
  47. /// Initializes a Handler
  48. ///
  49. /// - Parameter h: the underlying C representation
  50. init(underlyingHandler:UnsafeMutableRawPointer!) {
  51. self.underlyingHandler = underlyingHandler;
  52. self.requestMetadata = Metadata()
  53. self.completionQueue = CompletionQueue(underlyingCompletionQueue:cgrpc_handler_get_completion_queue(underlyingHandler))
  54. self.completionQueue.name = "Handler"
  55. }
  56. deinit {
  57. cgrpc_handler_destroy(self.underlyingHandler)
  58. }
  59. /// Gets the host name sent with the request
  60. ///
  61. /// - Returns: the host name sent with the request
  62. public func host() -> String {
  63. return String(cString:cgrpc_handler_host(underlyingHandler), encoding:String.Encoding.utf8)!;
  64. }
  65. /// Gets the method name sent with the request
  66. ///
  67. /// - Returns: the method name sent with the request
  68. public func method() -> String {
  69. return String(cString:cgrpc_handler_method(underlyingHandler), encoding:String.Encoding.utf8)!;
  70. }
  71. /// Gets the caller identity associated with the request
  72. ///
  73. /// - Returns: a string representing the caller address
  74. public func caller() -> String {
  75. return String(cString:cgrpc_handler_call_peer(underlyingHandler), encoding:String.Encoding.utf8)!;
  76. }
  77. /// Requests a call for the handler
  78. ///
  79. /// Fills the handler properties with information about the received request
  80. ///
  81. /// - Returns: a CallError indicating the result of requesting the call
  82. func requestCall(tag: Int) -> CallError {
  83. let error = cgrpc_handler_request_call(underlyingHandler, requestMetadata.array, tag)
  84. return CallError.callError(grpcCallError: error)
  85. }
  86. /// Prepares the handler's call object for response handling
  87. ///
  88. func prepareCall() -> Void {
  89. self.call = Call(call: cgrpc_handler_get_call(underlyingHandler),
  90. owned: false,
  91. completionQueue: self.completionQueue)
  92. }
  93. /// Receive the message sent with a call
  94. ///
  95. /// - Returns: a tuple containing status codes and a message (if available)
  96. public func receiveMessage(initialMetadata: Metadata,
  97. completion:@escaping ((Data?) -> Void)) -> Void {
  98. let operation_sendInitialMetadata = Operation_SendInitialMetadata(metadata:initialMetadata);
  99. let operation_receiveMessage = Operation_ReceiveMessage()
  100. let operations = OperationGroup(
  101. call:call,
  102. operations:[
  103. operation_sendInitialMetadata,
  104. operation_receiveMessage])
  105. {(success) in
  106. if (success) {
  107. completion(operation_receiveMessage.message()!.data())
  108. } else {
  109. completion(nil)
  110. }
  111. }
  112. self.completionQueue.operationGroups[operations.tag] = operations
  113. _ = call.performOperations(operations:operations, tag:operations.tag, completionQueue: self.completionQueue)
  114. }
  115. /// Sends the response to a request
  116. ///
  117. /// - Parameter message: the message to send
  118. /// - Returns: a tuple containing status codes
  119. public func sendResponse(message: Data,
  120. trailingMetadata: Metadata) -> Void {
  121. let operation_receiveCloseOnServer = Operation_ReceiveCloseOnServer();
  122. let operation_sendStatusFromServer = Operation_SendStatusFromServer(status:0,
  123. statusDetails:"OK",
  124. metadata:trailingMetadata)
  125. let messageBuffer = ByteBuffer(data:message)
  126. let operation_sendMessage = Operation_SendMessage(message:messageBuffer)
  127. let operations = OperationGroup(
  128. call:call,
  129. operations:[
  130. operation_receiveCloseOnServer,
  131. operation_sendStatusFromServer,
  132. operation_sendMessage])
  133. {(call_error) in
  134. self.shutdown()
  135. }
  136. self.completionQueue.operationGroups[operations.tag] = operations
  137. _ = call.performOperations(operations:operations, tag:operations.tag, completionQueue: self.completionQueue)
  138. }
  139. /// shutdown the handler's completion queue
  140. public func shutdown() {
  141. cgrpc_completion_queue_shutdown(completionQueue.underlyingCompletionQueue)
  142. }
  143. /// Send initial metadata in response to a connection
  144. public func sendMetadata(initialMetadata: Metadata,
  145. completion:@escaping (() -> Void)) {
  146. let operation_sendInitialMetadata = Operation_SendInitialMetadata(metadata:initialMetadata);
  147. let operations = OperationGroup(call:call, operations:[operation_sendInitialMetadata])
  148. {(success) in
  149. if (success) {
  150. completion()
  151. } else {
  152. completion()
  153. }
  154. }
  155. self.completionQueue.operationGroups[operations.tag] = operations
  156. _ = call.performOperations(operations:operations, tag:operations.tag, completionQueue: self.completionQueue)
  157. }
  158. /// Receive the message sent with a call
  159. ///
  160. /// - Returns: a tuple containing status codes and a message (if available)
  161. public func receiveMessage(completion:(@escaping (Data?) -> Void)) -> Void {
  162. let operation_receiveMessage = Operation_ReceiveMessage()
  163. let operations = OperationGroup(call:call, operations:[operation_receiveMessage])
  164. {(success) in
  165. if (success) {
  166. print("server receiveMessage complete")
  167. if let message = operation_receiveMessage.message() {
  168. completion(message.data())
  169. } else {
  170. completion(nil)
  171. }
  172. } else {
  173. completion(nil)
  174. }
  175. }
  176. self.completionQueue.operationGroups[operations.tag] = operations
  177. let call_error = call.performOperations(operations:operations, tag:operations.tag, completionQueue: self.completionQueue)
  178. print("perform receiveMessage \(call_error)")
  179. }
  180. /// Sends the response to a request
  181. ///
  182. /// - Parameter message: the message to send
  183. /// - Returns: a tuple containing status codes
  184. public func sendResponse(message: Data,
  185. completion: @escaping () -> Void) -> Void {
  186. let operation_sendMessage = Operation_SendMessage(message:ByteBuffer(data:message))
  187. let operations = OperationGroup(call:call, operations:[operation_sendMessage])
  188. {(event) in
  189. print("server sendResponse complete")
  190. completion()
  191. }
  192. self.completionQueue.operationGroups[operations.tag] = operations
  193. _ = call.performOperations(operations:operations, tag:operations.tag, completionQueue: self.completionQueue)
  194. }
  195. /// Recognize when the client has closed a request
  196. public func receiveClose(completion: @escaping () -> Void) -> Void {
  197. let operation_receiveClose = Operation_ReceiveCloseOnServer()
  198. let operations = OperationGroup(call:call, operations:[operation_receiveClose])
  199. {(event) in
  200. print("server receiveClose complete")
  201. completion()
  202. }
  203. self.completionQueue.operationGroups[operations.tag] = operations
  204. let call_error = call.performOperations(operations:operations, tag:operations.tag, completionQueue: self.completionQueue)
  205. print("perform receiveClose \(call_error)")
  206. }
  207. /// Send final status to the client
  208. public func sendStatus(trailingMetadata: Metadata,
  209. completion:@escaping (() -> Void)) -> Void {
  210. let operation_sendStatusFromServer = Operation_SendStatusFromServer(status:0,
  211. statusDetails:"OK",
  212. metadata:trailingMetadata)
  213. let operations = OperationGroup(call:call, operations:[operation_sendStatusFromServer])
  214. {(event) in
  215. print("server sendStatus complete")
  216. completion()
  217. }
  218. self.completionQueue.operationGroups[operations.tag] = operations
  219. _ = call.performOperations(operations:operations, tag:operations.tag, completionQueue: self.completionQueue)
  220. }
  221. }