Handler.swift 8.5 KB

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