Handler.swift 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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 statusCode: status code to send
  106. /// - Parameter statusMessage: status message to send
  107. /// - Parameter trailingMetadata: trailing metadata to send
  108. public func sendResponse(message: Data,
  109. statusCode: StatusCode,
  110. statusMessage: String,
  111. trailingMetadata: Metadata) throws -> Void {
  112. let messageBuffer = ByteBuffer(data:message)
  113. let operations = OperationGroup(
  114. call:call,
  115. operations:[
  116. .receiveCloseOnServer,
  117. .sendStatusFromServer(statusCode, statusMessage, trailingMetadata),
  118. .sendMessage(messageBuffer)])
  119. {(operationGroup) in
  120. if operationGroup.success {
  121. self.shutdown()
  122. }
  123. }
  124. try call.perform(operations)
  125. }
  126. /// Sends the response to a request
  127. ///
  128. /// - Parameter statusCode: status code to send
  129. /// - Parameter statusMessage: status message to send
  130. /// - Parameter trailingMetadata: trailing metadata to send
  131. public func sendResponse(statusCode: StatusCode,
  132. statusMessage: String,
  133. trailingMetadata: Metadata) throws -> Void {
  134. let operations = OperationGroup(
  135. call:call,
  136. operations:[
  137. .receiveCloseOnServer,
  138. .sendStatusFromServer(statusCode, statusMessage, trailingMetadata)])
  139. {(operationGroup) in
  140. if operationGroup.success {
  141. self.shutdown()
  142. }
  143. }
  144. try call.perform(operations)
  145. }
  146. /// Shuts down the handler's completion queue
  147. public func shutdown() {
  148. completionQueue.shutdown()
  149. }
  150. /// Send initial metadata in response to a connection
  151. ///
  152. /// - Parameter initialMetadata: initial metadata to send
  153. /// - Parameter completion: a completion handler to call after the metadata has been sent
  154. public func sendMetadata(initialMetadata: Metadata,
  155. completion:@escaping (() throws -> Void)) throws -> Void {
  156. let operations = OperationGroup(call:call,
  157. operations:[.sendInitialMetadata(initialMetadata)])
  158. {(operationGroup) in
  159. if operationGroup.success {
  160. try completion()
  161. } else {
  162. try completion()
  163. }
  164. }
  165. try call.perform(operations)
  166. }
  167. /// Receive the message sent with a call
  168. ///
  169. /// - Parameter completion: a completion handler to call after the message has been received
  170. /// - Returns: a tuple containing status codes and a message (if available)
  171. public func receiveMessage(completion:(@escaping (Data?) throws -> Void)) throws -> Void {
  172. let operations = OperationGroup(call:call, operations:[.receiveMessage])
  173. {(operationGroup) in
  174. if operationGroup.success {
  175. if let message = operationGroup.receivedMessage() {
  176. try completion(message.data())
  177. } else {
  178. try completion(nil)
  179. }
  180. } else {
  181. try completion(nil)
  182. }
  183. }
  184. try call.perform(operations)
  185. }
  186. /// Sends the response to a request
  187. ///
  188. /// - Parameter message: the message to send
  189. /// - Parameter completion: a completion handler to call after the response has been sent
  190. public func sendResponse(message: Data,
  191. completion: @escaping () throws -> Void) throws -> Void {
  192. let operations = OperationGroup(call:call,
  193. operations:[.sendMessage(ByteBuffer(data:message))])
  194. {(operationGroup) in
  195. if operationGroup.success {
  196. try completion()
  197. }
  198. }
  199. try call.perform(operations)
  200. }
  201. /// Recognize when the client has closed a request
  202. ///
  203. /// - Parameter completion: a completion handler to call after request has been closed
  204. public func receiveClose(completion: @escaping () throws -> Void) throws -> Void {
  205. let operations = OperationGroup(call:call,
  206. operations:[.receiveCloseOnServer])
  207. {(operationGroup) in
  208. if operationGroup.success {
  209. try completion()
  210. }
  211. }
  212. try call.perform(operations)
  213. }
  214. /// Send final status to the client
  215. ///
  216. /// - Parameter statusCode: status code to send
  217. /// - Parameter statusMessage: status message to send
  218. /// - Parameter trailingMetadata: trailing metadata to send
  219. /// - Parameter completion: a completion handler to call after the status has been sent
  220. public func sendStatus(statusCode: StatusCode,
  221. statusMessage: String,
  222. trailingMetadata: Metadata,
  223. completion:@escaping (() -> Void)) throws -> Void {
  224. let operations = OperationGroup(call:call,
  225. operations:[.sendStatusFromServer(statusCode,
  226. statusMessage,
  227. trailingMetadata)])
  228. {(operationGroup) in
  229. if operationGroup.success {
  230. completion()
  231. }
  232. }
  233. try call.perform(operations)
  234. }
  235. }