Handler.swift 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. /*
  2. * Copyright 2016, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #if SWIFT_PACKAGE
  17. import CgRPC
  18. #endif
  19. import Foundation // for String.Encoding
  20. /// A gRPC request handler
  21. public class Handler {
  22. /// Pointer to underlying C representation
  23. fileprivate let underlyingHandler: UnsafeMutableRawPointer
  24. /// Completion queue for handler response operations
  25. let completionQueue: CompletionQueue
  26. /// Metadata received with the request
  27. public let requestMetadata: Metadata
  28. /// A Call object that can be used to respond to the request
  29. lazy var call: Call = {
  30. Call(underlyingCall: cgrpc_handler_get_call(self.underlyingHandler),
  31. owned: false,
  32. completionQueue: self.completionQueue)
  33. }()
  34. /// The host name sent with the request
  35. public lazy var host: String = {
  36. if let string = cgrpc_handler_copy_host(self.underlyingHandler) {
  37. defer {
  38. cgrpc_free_copied_string(string)
  39. }
  40. return String(cString: string, encoding: .utf8)!
  41. } else {
  42. return ""
  43. }
  44. }()
  45. /// The method name sent with the request
  46. public lazy var method: String = {
  47. if let string = cgrpc_handler_copy_method(self.underlyingHandler) {
  48. defer {
  49. cgrpc_free_copied_string(string)
  50. }
  51. return String(cString: string, encoding: .utf8)!
  52. } else {
  53. return ""
  54. }
  55. }()
  56. /// The caller address associated with the request
  57. public lazy var caller: String = {
  58. String(cString: cgrpc_handler_call_peer(self.underlyingHandler),
  59. encoding: .utf8)!
  60. }()
  61. /// Initializes a Handler
  62. ///
  63. /// - Parameter underlyingServer: the underlying C representation of the associated server
  64. init(underlyingServer: UnsafeMutableRawPointer) {
  65. underlyingHandler = cgrpc_handler_create_with_server(underlyingServer)
  66. requestMetadata = Metadata()
  67. completionQueue = CompletionQueue(underlyingCompletionQueue: cgrpc_handler_get_completion_queue(underlyingHandler))
  68. completionQueue.name = "Handler"
  69. }
  70. deinit {
  71. cgrpc_handler_destroy(self.underlyingHandler)
  72. }
  73. /// Requests a call for the handler
  74. ///
  75. /// Fills the handler properties with information about the received request
  76. ///
  77. func requestCall(tag: Int) throws {
  78. let error = cgrpc_handler_request_call(underlyingHandler, requestMetadata.underlyingArray, tag)
  79. if error != GRPC_CALL_OK {
  80. throw CallError.callError(grpcCallError: error)
  81. }
  82. }
  83. /// Receive the message sent with a call
  84. ///
  85. public func receiveMessage(initialMetadata: Metadata,
  86. completion: @escaping ((Data?) throws -> Void)) throws {
  87. let operations = OperationGroup(call: call,
  88. operations: [
  89. .sendInitialMetadata(initialMetadata),
  90. .receiveMessage
  91. ]) { operationGroup in
  92. if operationGroup.success {
  93. try completion(operationGroup.receivedMessage()?.data())
  94. } else {
  95. try completion(nil)
  96. }
  97. }
  98. try call.perform(operations)
  99. }
  100. /// Sends the response to a request
  101. ///
  102. /// - Parameter message: the message to send
  103. /// - Parameter statusCode: status code to send
  104. /// - Parameter statusMessage: status message to send
  105. /// - Parameter trailingMetadata: trailing metadata to send
  106. public func sendResponse(message: Data,
  107. statusCode: StatusCode,
  108. statusMessage: String,
  109. trailingMetadata: Metadata) throws {
  110. let messageBuffer = ByteBuffer(data: message)
  111. let operations = OperationGroup(call: call,
  112. operations: [
  113. .receiveCloseOnServer,
  114. .sendStatusFromServer(statusCode, statusMessage, trailingMetadata),
  115. .sendMessage(messageBuffer)
  116. ]) { operationGroup in
  117. if operationGroup.success {
  118. self.shutdown()
  119. }
  120. }
  121. try call.perform(operations)
  122. }
  123. /// Sends the response to a request
  124. ///
  125. /// - Parameter statusCode: status code to send
  126. /// - Parameter statusMessage: status message to send
  127. /// - Parameter trailingMetadata: trailing metadata to send
  128. public func sendResponse(statusCode: StatusCode,
  129. statusMessage: String,
  130. trailingMetadata: Metadata) throws {
  131. let operations = OperationGroup(call: call,
  132. operations: [
  133. .receiveCloseOnServer,
  134. .sendStatusFromServer(statusCode, statusMessage, trailingMetadata)
  135. ]) { operationGroup in
  136. if operationGroup.success {
  137. self.shutdown()
  138. }
  139. }
  140. try call.perform(operations)
  141. }
  142. /// Shuts down the handler's completion queue
  143. public func shutdown() {
  144. completionQueue.shutdown()
  145. }
  146. /// Send initial metadata in response to a connection
  147. ///
  148. /// - Parameter initialMetadata: initial metadata to send
  149. /// - Parameter completion: a completion handler to call after the metadata has been sent
  150. public func sendMetadata(initialMetadata: Metadata,
  151. completion: @escaping (() throws -> Void)) throws {
  152. let operations = OperationGroup(call: call,
  153. operations: [.sendInitialMetadata(initialMetadata)]) { operationGroup in
  154. if operationGroup.success {
  155. try completion()
  156. } else {
  157. try completion()
  158. }
  159. }
  160. try call.perform(operations)
  161. }
  162. /// Receive the message sent with a call
  163. ///
  164. /// - Parameter completion: a completion handler to call after the message has been received
  165. /// - Returns: a tuple containing status codes and a message (if available)
  166. public func receiveMessage(completion: (@escaping (Data?) throws -> Void)) throws {
  167. let operations = OperationGroup(call: call, operations: [.receiveMessage]) { operationGroup in
  168. if operationGroup.success {
  169. if let message = operationGroup.receivedMessage() {
  170. try completion(message.data())
  171. } else {
  172. try completion(nil)
  173. }
  174. } else {
  175. try completion(nil)
  176. }
  177. }
  178. try call.perform(operations)
  179. }
  180. /// Sends the response to a request
  181. ///
  182. /// - Parameter message: the message to send
  183. /// - Parameter completion: a completion handler to call after the response has been sent
  184. public func sendResponse(message: Data,
  185. completion: @escaping () throws -> Void) throws {
  186. let operations = OperationGroup(call: call,
  187. operations: [.sendMessage(ByteBuffer(data: message))]) { operationGroup in
  188. if operationGroup.success {
  189. try completion()
  190. }
  191. }
  192. try call.perform(operations)
  193. }
  194. /// Recognize when the client has closed a request
  195. ///
  196. /// - Parameter completion: a completion handler to call after request has been closed
  197. public func receiveClose(completion: @escaping () throws -> Void) throws {
  198. let operations = OperationGroup(call: call,
  199. operations: [.receiveCloseOnServer]) { operationGroup in
  200. if operationGroup.success {
  201. try completion()
  202. }
  203. }
  204. try call.perform(operations)
  205. }
  206. /// Send final status to the client
  207. ///
  208. /// - Parameter statusCode: status code to send
  209. /// - Parameter statusMessage: status message to send
  210. /// - Parameter trailingMetadata: trailing metadata to send
  211. /// - Parameter completion: a completion handler to call after the status has been sent
  212. public func sendStatus(statusCode: StatusCode,
  213. statusMessage: String,
  214. trailingMetadata: Metadata,
  215. completion: @escaping (() -> Void)) throws {
  216. let operations = OperationGroup(call: call,
  217. operations: [
  218. .sendStatusFromServer(statusCode,
  219. statusMessage,
  220. trailingMetadata)
  221. ]) { operationGroup in
  222. if operationGroup.success {
  223. completion()
  224. }
  225. }
  226. try call.perform(operations)
  227. }
  228. }
  229. extension Handler: Hashable {
  230. public var hashValue: Int { return underlyingHandler.hashValue }
  231. public static func ==(A: Handler, B: Handler) -> Bool {
  232. return A === B
  233. }
  234. }