Handler.swift 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. public private(set) lazy var call: Call = {
  30. Call(underlyingCall: cgrpc_handler_get_call(self.underlyingHandler),
  31. owned: true,
  32. completionQueue: self.completionQueue)
  33. }()
  34. /// The host name sent with the request
  35. public lazy var host: String? = {
  36. // We actually know that this method will never return nil,
  37. // so we can forcibly unwrap the result. (Also below.)
  38. let string = cgrpc_handler_copy_host(self.underlyingHandler)!
  39. defer { cgrpc_free_copied_string(string) }
  40. return String(cString: string, encoding: .utf8)
  41. }()
  42. /// The method name sent with the request
  43. public lazy var method: String? = {
  44. let string = cgrpc_handler_copy_method(self.underlyingHandler)!
  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. let string = cgrpc_handler_call_peer(self.underlyingHandler)!
  51. defer { cgrpc_free_copied_string(string) }
  52. return String(cString: string, encoding: .utf8)
  53. }()
  54. /// Initializes a Handler
  55. ///
  56. /// - Parameter underlyingServer: the underlying C representation of the associated server
  57. init(underlyingServer: UnsafeMutableRawPointer) {
  58. underlyingHandler = cgrpc_handler_create_with_server(underlyingServer)
  59. requestMetadata = Metadata()
  60. completionQueue = CompletionQueue(
  61. underlyingCompletionQueue: cgrpc_handler_get_completion_queue(underlyingHandler), name: "Handler")
  62. }
  63. deinit {
  64. // Technically unnecessary, because the handler only gets released once the completion queue has already been
  65. // shut down, but it doesn't hurt to keep this here.
  66. completionQueue.shutdown()
  67. cgrpc_handler_destroy(self.underlyingHandler)
  68. }
  69. /// Requests a call for the handler
  70. ///
  71. /// Fills the handler properties with information about the received request
  72. ///
  73. func requestCall(tag: Int) throws {
  74. let error = cgrpc_handler_request_call(underlyingHandler,
  75. try requestMetadata.getUnderlyingArrayAndTransferFieldOwnership(),
  76. UnsafeMutableRawPointer(bitPattern: tag))
  77. if error != GRPC_CALL_OK {
  78. throw CallError.callError(grpcCallError: error)
  79. }
  80. }
  81. /// Shuts down the handler's completion queue
  82. public func shutdown() {
  83. completionQueue.shutdown()
  84. }
  85. /// Send initial metadata in response to a connection
  86. ///
  87. /// - Parameter initialMetadata: initial metadata to send
  88. /// - Parameter completion: a completion handler to call after the metadata has been sent
  89. public func sendMetadata(initialMetadata: Metadata,
  90. completion: ((Bool) -> Void)? = nil) throws {
  91. try call.perform(OperationGroup(
  92. call: call,
  93. operations: [.sendInitialMetadata(initialMetadata.copy())],
  94. completion: completion != nil
  95. ? { operationGroup in completion?(operationGroup.success) }
  96. : nil))
  97. }
  98. /// Receive the message sent with a call
  99. ///
  100. public func receiveMessage(initialMetadata: Metadata,
  101. completion: @escaping (Data?) -> Void) throws {
  102. try call.perform(OperationGroup(
  103. call: call,
  104. operations: [
  105. .sendInitialMetadata(initialMetadata.copy()),
  106. .receiveMessage
  107. ]) { operationGroup in
  108. if operationGroup.success {
  109. completion(operationGroup.receivedMessage()?.data())
  110. } else {
  111. completion(nil)
  112. }
  113. })
  114. }
  115. /// Sends the response to a request.
  116. /// The completion handler does not take an argument because operations containing `.receiveCloseOnServer` always succeed.
  117. public func sendResponse(message: Data, status: ServerStatus,
  118. completion: (() -> Void)? = nil) throws {
  119. let messageBuffer = ByteBuffer(data: message)
  120. try call.perform(OperationGroup(
  121. call: call,
  122. operations: [
  123. .sendMessage(messageBuffer),
  124. .receiveCloseOnServer,
  125. .sendStatusFromServer(status.code, status.message, status.trailingMetadata.copy())
  126. ]) { _ in
  127. completion?()
  128. self.shutdown()
  129. })
  130. }
  131. /// Send final status to the client.
  132. /// The completion handler does not take an argument because operations containing `.receiveCloseOnServer` always succeed.
  133. public func sendStatus(_ status: ServerStatus, completion: (() -> Void)? = nil) throws {
  134. try call.perform(OperationGroup(
  135. call: call,
  136. operations: [
  137. .receiveCloseOnServer,
  138. .sendStatusFromServer(status.code, status.message, status.trailingMetadata.copy())
  139. ]) { _ in
  140. completion?()
  141. self.shutdown()
  142. })
  143. }
  144. }