ClientCall.swift 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. /*
  2. * Copyright 2019, 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. import Foundation
  17. import NIO
  18. import NIOHTTP1
  19. import NIOHTTP2
  20. import NIOHPACK
  21. import SwiftProtobuf
  22. /// Base protocol for a client call to a gRPC service.
  23. public protocol ClientCall {
  24. /// The type of the request message for the call.
  25. associatedtype RequestPayload: GRPCPayload
  26. /// The type of the response message for the call.
  27. associatedtype ResponsePayload: GRPCPayload
  28. /// The event loop this call is running on.
  29. var eventLoop: EventLoop { get }
  30. /// The options used to make the RPC.
  31. var options: CallOptions { get }
  32. /// HTTP/2 stream that requests and responses are sent and received on.
  33. var subchannel: EventLoopFuture<Channel> { get }
  34. /// Initial response metadata.
  35. var initialMetadata: EventLoopFuture<HPACKHeaders> { get }
  36. /// Status of this call which may be populated by the server or client.
  37. ///
  38. /// The client may populate the status if, for example, it was not possible to connect to the service.
  39. ///
  40. /// Note: despite `GRPCStatus` conforming to `Error`, the value will be __always__ delivered as a __success__
  41. /// result even if the status represents a __negative__ outcome. This future will __never__ be fulfilled
  42. /// with an error.
  43. var status: EventLoopFuture<GRPCStatus> { get }
  44. /// Trailing response metadata.
  45. var trailingMetadata: EventLoopFuture<HPACKHeaders> { get }
  46. /// Cancel the current call.
  47. ///
  48. /// Closes the HTTP/2 stream once it becomes available. Additional writes to the channel will be ignored.
  49. /// Any unfulfilled promises will be failed with a cancelled status (excepting `status` which will be
  50. /// succeeded, if not already succeeded).
  51. func cancel(promise: EventLoopPromise<Void>?)
  52. }
  53. extension ClientCall {
  54. func cancel() -> EventLoopFuture<Void> {
  55. let promise = self.eventLoop.makePromise(of: Void.self)
  56. self.cancel(promise: promise)
  57. return promise.futureResult
  58. }
  59. }
  60. /// A `ClientCall` with request streaming; i.e. client-streaming and bidirectional-streaming.
  61. public protocol StreamingRequestClientCall: ClientCall {
  62. /// Sends a message to the service.
  63. ///
  64. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()` or `sendEnd(promise:)`.
  65. ///
  66. /// - Parameters:
  67. /// - message: The message to send.
  68. /// - compression: Whether compression should be used for this message. Ignored if compression
  69. /// was not enabled for the RPC.
  70. /// - Returns: A future which will be fullfilled when the message has been sent.
  71. func sendMessage(_ message: RequestPayload, compression: Compression) -> EventLoopFuture<Void>
  72. /// Sends a message to the service.
  73. ///
  74. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()` or `sendEnd(promise:)`.
  75. ///
  76. /// - Parameters:
  77. /// - message: The message to send.
  78. /// - compression: Whether compression should be used for this message. Ignored if compression
  79. /// was not enabled for the RPC.
  80. /// - promise: A promise to be fulfilled when the message has been sent.
  81. func sendMessage(_ message: RequestPayload, compression: Compression, promise: EventLoopPromise<Void>?)
  82. /// Sends a sequence of messages to the service.
  83. ///
  84. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()` or `sendEnd(promise:)`.
  85. ///
  86. /// - Parameters:
  87. /// - messages: The sequence of messages to send.
  88. /// - compression: Whether compression should be used for this message. Ignored if compression
  89. /// was not enabled for the RPC.
  90. func sendMessages<S: Sequence>(_ messages: S, compression: Compression) -> EventLoopFuture<Void> where S.Element == RequestPayload
  91. /// Sends a sequence of messages to the service.
  92. ///
  93. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()` or `sendEnd(promise:)`.
  94. ///
  95. /// - Parameters:
  96. /// - messages: The sequence of messages to send.
  97. /// - compression: Whether compression should be used for this message. Ignored if compression
  98. /// was not enabled for the RPC.
  99. /// - promise: A promise to be fulfilled when all messages have been sent successfully.
  100. func sendMessages<S: Sequence>(_ messages: S, compression: Compression, promise: EventLoopPromise<Void>?) where S.Element == RequestPayload
  101. /// Terminates a stream of messages sent to the service.
  102. ///
  103. /// - Important: This should only ever be called once.
  104. /// - Returns: A future which will be fulfilled when the end has been sent.
  105. func sendEnd() -> EventLoopFuture<Void>
  106. /// Terminates a stream of messages sent to the service.
  107. ///
  108. /// - Important: This should only ever be called once.
  109. /// - Parameter promise: A promise to be fulfilled when the end has been sent.
  110. func sendEnd(promise: EventLoopPromise<Void>?)
  111. }
  112. extension StreamingRequestClientCall {
  113. public func sendMessage(_ message: RequestPayload, compression: Compression = .deferToCallDefault) -> EventLoopFuture<Void> {
  114. let promise = self.eventLoop.makePromise(of: Void.self)
  115. self.sendMessage(message, compression: compression, promise: promise)
  116. return promise.futureResult
  117. }
  118. public func sendMessages<S: Sequence>(_ messages: S, compression: Compression = .deferToCallDefault) -> EventLoopFuture<Void> where S.Element == RequestPayload {
  119. let promise = self.eventLoop.makePromise(of: Void.self)
  120. self.sendMessages(messages, compression: compression, promise: promise)
  121. return promise.futureResult
  122. }
  123. public func sendEnd() -> EventLoopFuture<Void> {
  124. let promise = self.eventLoop.makePromise(of: Void.self)
  125. self.sendEnd(promise: promise)
  126. return promise.futureResult
  127. }
  128. }
  129. /// A `ClientCall` with a unary response; i.e. unary and client-streaming.
  130. public protocol UnaryResponseClientCall: ClientCall {
  131. /// The response message returned from the service if the call is successful. This may be failed
  132. /// if the call encounters an error.
  133. ///
  134. /// Callers should rely on the `status` of the call for the canonical outcome.
  135. var response: EventLoopFuture<ResponsePayload> { get }
  136. }
  137. // These protocols sit between a `*ClientCall` and the channel. The intention behind them is to
  138. // allow the `*ClientCall` types to use a different transport mechanisms. Normally this will be
  139. // a NIO HTTP/2 stream channel.
  140. internal protocol ClientCallInbound {
  141. associatedtype Response: GRPCPayload
  142. typealias ResponsePart = _GRPCClientResponsePart<Response>
  143. /// Receive an error.
  144. func receiveError(_ error: Error)
  145. /// Receive a response part.
  146. func receiveResponse(_ part: ResponsePart)
  147. }
  148. internal protocol ClientCallOutbound {
  149. associatedtype Request: GRPCPayload
  150. typealias RequestPart = _GRPCClientRequestPart<Request>
  151. /// Send a single request part and complete the promise once the part has been sent.
  152. func sendRequest(_ part: RequestPart, promise: EventLoopPromise<Void>?)
  153. /// Send the given request parts and complete the promise once all parts have been sent.
  154. func sendRequests<S: Sequence>(_ parts: S, promise: EventLoopPromise<Void>?) where S.Element == RequestPart
  155. /// Cancel the call and complete the promise once the cancellation has been completed.
  156. func cancel(promise: EventLoopPromise<Void>?)
  157. }
  158. extension ClientCallOutbound {
  159. /// Convenience method for sending all parts of a unary-request RPC.
  160. internal func sendUnary(_ head: _GRPCRequestHead, request: Request, compressed: Bool) {
  161. let parts: [RequestPart] = [
  162. .head(head),
  163. .message(_MessageContext(request, compressed: compressed)),
  164. .end
  165. ]
  166. self.sendRequests(parts, promise: nil)
  167. }
  168. }