ClientCall.swift 7.9 KB

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