Handler.swift 8.7 KB

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