Handler.swift 7.4 KB

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