ClientCall.swift 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 options used to make the RPC.
  29. var options: CallOptions { get }
  30. /// HTTP/2 stream that requests and responses are sent and received on.
  31. var subchannel: EventLoopFuture<Channel> { get }
  32. /// Initial response metadata.
  33. var initialMetadata: EventLoopFuture<HPACKHeaders> { get }
  34. /// Status of this call which may be populated by the server or client.
  35. ///
  36. /// The client may populate the status if, for example, it was not possible to connect to the service.
  37. ///
  38. /// Note: despite `GRPCStatus` conforming to `Error`, the value will be __always__ delivered as a __success__
  39. /// result even if the status represents a __negative__ outcome. This future will __never__ be fulfilled
  40. /// with an error.
  41. var status: EventLoopFuture<GRPCStatus> { get }
  42. /// Trailing response metadata.
  43. var trailingMetadata: EventLoopFuture<HPACKHeaders> { get }
  44. /// Cancel the current call.
  45. ///
  46. /// Closes the HTTP/2 stream once it becomes available. Additional writes to the channel will be ignored.
  47. /// Any unfulfilled promises will be failed with a cancelled status (excepting `status` which will be
  48. /// succeeded, if not already succeeded).
  49. func cancel() -> EventLoopFuture<Void>
  50. func cancel(promise: EventLoopPromise<Void>?)
  51. }
  52. /// A `ClientCall` with request streaming; i.e. client-streaming and bidirectional-streaming.
  53. public protocol StreamingRequestClientCall: ClientCall {
  54. /// Sends a message to the service.
  55. ///
  56. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()` or `sendEnd(promise:)`.
  57. ///
  58. /// - Parameters:
  59. /// - message: The message to send.
  60. /// - compression: Whether compression should be used for this message. Ignored if compression
  61. /// was not enabled for the RPC.
  62. /// - Returns: A future which will be fullfilled when the message has been sent.
  63. func sendMessage(_ message: RequestPayload, compression: Compression) -> EventLoopFuture<Void>
  64. /// Sends a message to the service.
  65. ///
  66. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()` or `sendEnd(promise:)`.
  67. ///
  68. /// - Parameters:
  69. /// - message: The message to send.
  70. /// - compression: Whether compression should be used for this message. Ignored if compression
  71. /// was not enabled for the RPC.
  72. /// - promise: A promise to be fulfilled when the message has been sent.
  73. func sendMessage(_ message: RequestPayload, compression: Compression, promise: EventLoopPromise<Void>?)
  74. /// Sends a sequence of messages to the service.
  75. ///
  76. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()` or `sendEnd(promise:)`.
  77. ///
  78. /// - Parameters:
  79. /// - messages: The sequence of messages to send.
  80. /// - compression: Whether compression should be used for this message. Ignored if compression
  81. /// was not enabled for the RPC.
  82. func sendMessages<S: Sequence>(_ messages: S, compression: Compression) -> EventLoopFuture<Void> where S.Element == RequestPayload
  83. /// Sends a sequence of messages to the service.
  84. ///
  85. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()` or `sendEnd(promise:)`.
  86. ///
  87. /// - Parameters:
  88. /// - messages: The sequence of messages to send.
  89. /// - compression: Whether compression should be used for this message. Ignored if compression
  90. /// was not enabled for the RPC.
  91. /// - promise: A promise to be fulfilled when all messages have been sent successfully.
  92. func sendMessages<S: Sequence>(_ messages: S, compression: Compression, promise: EventLoopPromise<Void>?) where S.Element == RequestPayload
  93. /// Returns a future which can be used as a message queue.
  94. ///
  95. /// Callers may use this as such:
  96. /// ```
  97. /// var queue = call.newMessageQueue()
  98. /// for message in messagesToSend {
  99. /// queue = queue.then { call.sendMessage(message) }
  100. /// }
  101. /// ```
  102. ///
  103. /// - Returns: A future which may be used as the head of a message queue.
  104. func newMessageQueue() -> EventLoopFuture<Void>
  105. /// Terminates a stream of messages sent to the service.
  106. ///
  107. /// - Important: This should only ever be called once.
  108. /// - Returns: A future which will be fulfilled when the end has been sent.
  109. func sendEnd() -> EventLoopFuture<Void>
  110. /// Terminates a stream of messages sent to the service.
  111. ///
  112. /// - Important: This should only ever be called once.
  113. /// - Parameter promise: A promise to be fulfilled when the end has been sent.
  114. func sendEnd(promise: EventLoopPromise<Void>?)
  115. }
  116. /// A `ClientCall` with a unary response; i.e. unary and client-streaming.
  117. public protocol UnaryResponseClientCall: ClientCall {
  118. /// The response message returned from the service if the call is successful. This may be failed
  119. /// if the call encounters an error.
  120. ///
  121. /// Callers should rely on the `status` of the call for the canonical outcome.
  122. var response: EventLoopFuture<ResponsePayload> { get }
  123. }
  124. extension StreamingRequestClientCall {
  125. public func sendMessage(
  126. _ message: RequestPayload,
  127. compression: Compression = .deferToCallDefault
  128. ) -> EventLoopFuture<Void> {
  129. return self.subchannel.flatMap { channel in
  130. let context = _MessageContext<RequestPayload>(
  131. message,
  132. compressed: compression.isEnabled(enabledOnCall: self.options.messageEncoding.enabledForRequests)
  133. )
  134. return channel.writeAndFlush(_GRPCClientRequestPart.message(context))
  135. }
  136. }
  137. public func sendMessage(
  138. _ message: RequestPayload,
  139. compression: Compression = .deferToCallDefault,
  140. promise: EventLoopPromise<Void>?
  141. ) {
  142. self.subchannel.whenSuccess { channel in
  143. let context = _MessageContext<RequestPayload>(
  144. message,
  145. compressed: compression.isEnabled(enabledOnCall: self.options.messageEncoding.enabledForRequests)
  146. )
  147. channel.writeAndFlush(_GRPCClientRequestPart.message(context), promise: promise)
  148. }
  149. }
  150. public func sendMessages<S: Sequence>(
  151. _ messages: S,
  152. compression: Compression = .deferToCallDefault
  153. ) -> EventLoopFuture<Void> where S.Element == RequestPayload {
  154. return self.subchannel.flatMap { channel -> EventLoopFuture<Void> in
  155. let writeFutures = messages.map { message -> EventLoopFuture<Void> in
  156. let context = _MessageContext<RequestPayload>(
  157. message,
  158. compressed: compression.isEnabled(enabledOnCall: self.options.messageEncoding.enabledForRequests)
  159. )
  160. return channel.write(_GRPCClientRequestPart.message(context))
  161. }
  162. channel.flush()
  163. return EventLoopFuture.andAllSucceed(writeFutures, on: channel.eventLoop)
  164. }
  165. }
  166. public func sendMessages<S: Sequence>(
  167. _ messages: S,
  168. compression: Compression = .deferToCallDefault,
  169. promise: EventLoopPromise<Void>?
  170. ) where S.Element == RequestPayload {
  171. if let promise = promise {
  172. self.sendMessages(messages).cascade(to: promise)
  173. } else {
  174. self.subchannel.whenSuccess { channel in
  175. for message in messages {
  176. let context = _MessageContext<RequestPayload>(
  177. message,
  178. compressed: compression.isEnabled(enabledOnCall: self.options.messageEncoding.enabledForRequests)
  179. )
  180. channel.write(_GRPCClientRequestPart.message(context), promise: nil)
  181. }
  182. channel.flush()
  183. }
  184. }
  185. }
  186. public func sendEnd() -> EventLoopFuture<Void> {
  187. return self.subchannel.flatMap { channel in
  188. return channel.writeAndFlush(_GRPCClientRequestPart<RequestPayload>.end)
  189. }
  190. }
  191. public func sendEnd(promise: EventLoopPromise<Void>?) {
  192. self.subchannel.whenSuccess { channel in
  193. channel.writeAndFlush(_GRPCClientRequestPart<RequestPayload>.end, promise: promise)
  194. }
  195. }
  196. }