2
0

Handler.swift 9.6 KB

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