Handler.swift 7.7 KB

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