Handler.swift 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. internal 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. internal lazy var call: Call = {
  47. return Call(underlyingCall: 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 underlyingServer: the underlying C representation of the associated server
  69. init(underlyingServer:UnsafeMutableRawPointer) {
  70. underlyingHandler = cgrpc_handler_create_with_server(underlyingServer)
  71. requestMetadata = Metadata()
  72. completionQueue = CompletionQueue(
  73. underlyingCompletionQueue:cgrpc_handler_get_completion_queue(underlyingHandler))
  74. 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. func requestCall(tag: Int) throws -> Void {
  84. let error = cgrpc_handler_request_call(underlyingHandler, requestMetadata.underlyingArray, tag)
  85. if error != GRPC_CALL_OK {
  86. throw CallError.callError(grpcCallError: error)
  87. }
  88. }
  89. /// Receive the message sent with a call
  90. ///
  91. public func receiveMessage(initialMetadata: Metadata,
  92. completion:@escaping ((Data?) throws -> Void)) throws -> Void {
  93. let operations = OperationGroup(
  94. call:call,
  95. operations:[
  96. .sendInitialMetadata(initialMetadata),
  97. .receiveMessage])
  98. {(operationGroup) in
  99. if operationGroup.success {
  100. try completion(operationGroup.receivedMessage()?.data())
  101. } else {
  102. try completion(nil)
  103. }
  104. }
  105. try call.perform(operations)
  106. }
  107. /// Sends the response to a request
  108. ///
  109. /// - Parameter message: the message to send
  110. /// - Parameter trailingMetadata: trailing metadata to send
  111. public func sendResponse(message: Data,
  112. statusCode: Int,
  113. statusMessage: String,
  114. trailingMetadata: Metadata) throws -> Void {
  115. let messageBuffer = ByteBuffer(data:message)
  116. let operations = OperationGroup(
  117. call:call,
  118. operations:[
  119. .receiveCloseOnServer,
  120. .sendStatusFromServer(statusCode, statusMessage, trailingMetadata),
  121. .sendMessage(messageBuffer)])
  122. {(operationGroup) in
  123. if operationGroup.success {
  124. self.shutdown()
  125. }
  126. }
  127. try call.perform(operations)
  128. }
  129. /// Shuts down the handler's completion queue
  130. public func shutdown() {
  131. completionQueue.shutdown()
  132. }
  133. /// Send initial metadata in response to a connection
  134. ///
  135. /// - Parameter initialMetadata: initial metadata to send
  136. /// - Parameter completion: a completion handler to call after the metadata has been sent
  137. public func sendMetadata(initialMetadata: Metadata,
  138. completion:@escaping (() throws -> Void)) throws -> Void {
  139. let operations = OperationGroup(call:call,
  140. operations:[.sendInitialMetadata(initialMetadata)])
  141. {(operationGroup) in
  142. if operationGroup.success {
  143. try completion()
  144. } else {
  145. try completion()
  146. }
  147. }
  148. try call.perform(operations)
  149. }
  150. /// Receive the message sent with a call
  151. ///
  152. /// - Parameter completion: a completion handler to call after the message has been received
  153. /// - Returns: a tuple containing status codes and a message (if available)
  154. public func receiveMessage(completion:(@escaping (Data?) throws -> Void)) throws -> Void {
  155. let operations = OperationGroup(call:call, operations:[.receiveMessage])
  156. {(operationGroup) in
  157. if operationGroup.success {
  158. if let message = operationGroup.receivedMessage() {
  159. try completion(message.data())
  160. } else {
  161. try completion(nil)
  162. }
  163. } else {
  164. try completion(nil)
  165. }
  166. }
  167. try call.perform(operations)
  168. }
  169. /// Sends the response to a request
  170. ///
  171. /// - Parameter message: the message to send
  172. /// - Parameter completion: a completion handler to call after the response has been sent
  173. public func sendResponse(message: Data,
  174. completion: @escaping () throws -> Void) throws -> Void {
  175. let operations = OperationGroup(call:call,
  176. operations:[.sendMessage(ByteBuffer(data:message))])
  177. {(operationGroup) in
  178. if operationGroup.success {
  179. try completion()
  180. }
  181. }
  182. try call.perform(operations)
  183. }
  184. /// Recognize when the client has closed a request
  185. ///
  186. /// - Parameter completion: a completion handler to call after request has been closed
  187. public func receiveClose(completion: @escaping () throws -> Void) throws -> Void {
  188. let operations = OperationGroup(call:call,
  189. operations:[.receiveCloseOnServer])
  190. {(operationGroup) in
  191. if operationGroup.success {
  192. try completion()
  193. }
  194. }
  195. try call.perform(operations)
  196. }
  197. /// Send final status to the client
  198. ///
  199. /// - Parameter statusCode: status code to send
  200. /// - Parameter statusMessage: status message to send
  201. /// - Parameter trailingMetadata: trailing metadata to send
  202. /// - Parameter completion: a completion handler to call after the status has been sent
  203. public func sendStatus(statusCode: Int,
  204. statusMessage: String,
  205. trailingMetadata: Metadata,
  206. completion:@escaping (() -> Void)) throws -> Void {
  207. let operations = OperationGroup(call:call,
  208. operations:[.sendStatusFromServer(statusCode,
  209. statusMessage,
  210. trailingMetadata)])
  211. {(operationGroup) in
  212. if operationGroup.success {
  213. completion()
  214. }
  215. }
  216. try call.perform(operations)
  217. }
  218. }