Handler.swift 9.8 KB

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