ClientStreamingCall.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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 NIO
  17. import NIOHTTP2
  18. import NIOHPACK
  19. import Logging
  20. /// A client-streaming gRPC call.
  21. ///
  22. /// Messages should be sent via the `sendMessage` and `sendMessages` methods; the stream of messages
  23. /// must be terminated by calling `sendEnd` to indicate the final message has been sent.
  24. public final class ClientStreamingCall<
  25. RequestPayload: GRPCPayload,
  26. ResponsePayload: GRPCPayload
  27. > : StreamingRequestClientCall, UnaryResponseClientCall {
  28. private let transport: ChannelTransport<RequestPayload, ResponsePayload>
  29. /// The options used to make the RPC.
  30. public let options: CallOptions
  31. /// The `Channel` used to transport messages for this RPC.
  32. public var subchannel: EventLoopFuture<Channel> {
  33. return self.transport.streamChannel()
  34. }
  35. /// The `EventLoop` this call is running on.
  36. public var eventLoop: EventLoop {
  37. return self.transport.eventLoop
  38. }
  39. /// Cancel this RPC if it hasn't already completed.
  40. public func cancel(promise: EventLoopPromise<Void>?) {
  41. self.transport.cancel(promise: promise)
  42. }
  43. // MARK: - Response Parts
  44. /// The initial metadata returned from the server.
  45. public var initialMetadata: EventLoopFuture<HPACKHeaders> {
  46. if self.eventLoop.inEventLoop {
  47. return self.transport.responseContainer.lazyInitialMetadataPromise.getFutureResult()
  48. } else {
  49. return self.eventLoop.flatSubmit {
  50. return self.transport.responseContainer.lazyInitialMetadataPromise.getFutureResult()
  51. }
  52. }
  53. }
  54. /// The response returned by the server.
  55. public let response: EventLoopFuture<ResponsePayload>
  56. /// The trailing metadata returned from the server.
  57. public var trailingMetadata: EventLoopFuture<HPACKHeaders> {
  58. if self.eventLoop.inEventLoop {
  59. return self.transport.responseContainer.lazyTrailingMetadataPromise.getFutureResult()
  60. } else {
  61. return self.eventLoop.flatSubmit {
  62. return self.transport.responseContainer.lazyTrailingMetadataPromise.getFutureResult()
  63. }
  64. }
  65. }
  66. /// The final status of the the RPC.
  67. public var status: EventLoopFuture<GRPCStatus> {
  68. if self.eventLoop.inEventLoop {
  69. return self.transport.responseContainer.lazyStatusPromise.getFutureResult()
  70. } else {
  71. return self.eventLoop.flatSubmit {
  72. return self.transport.responseContainer.lazyStatusPromise.getFutureResult()
  73. }
  74. }
  75. }
  76. // MARK: - Request
  77. /// Sends a message to the service.
  78. ///
  79. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()` or
  80. /// `sendEnd(promise:)`.
  81. ///
  82. /// - Parameters:
  83. /// - message: The message to send.
  84. /// - compression: Whether compression should be used for this message. Ignored if compression
  85. /// was not enabled for the RPC.
  86. /// - promise: A promise to fulfill with the outcome of the send operation.
  87. public func sendMessage(
  88. _ message: RequestPayload,
  89. compression: Compression = .deferToCallDefault,
  90. promise: EventLoopPromise<Void>?
  91. ) {
  92. let compressed = compression.isEnabled(enabledOnCall: self.options.messageEncoding.enabledForRequests)
  93. let messageContext = _MessageContext(message, compressed: compressed)
  94. self.transport.sendRequest(.message(messageContext), promise: promise)
  95. }
  96. /// Sends a sequence of messages to the service.
  97. ///
  98. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()` or
  99. /// `sendEnd(promise:)`.
  100. ///
  101. /// - Parameters:
  102. /// - messages: The sequence of messages to send.
  103. /// - compression: Whether compression should be used for this message. Ignored if compression
  104. /// was not enabled for the RPC.
  105. /// - promise: A promise to fulfill with the outcome of the send operation. It will only succeed
  106. /// if all messages were written successfully.
  107. public func sendMessages<S>(
  108. _ messages: S,
  109. compression: Compression = .deferToCallDefault,
  110. promise: EventLoopPromise<Void>?
  111. ) where S: Sequence, S.Element == RequestPayload {
  112. let compressed = compression.isEnabled(enabledOnCall: self.options.messageEncoding.enabledForRequests)
  113. self.transport.sendRequests(messages.map {
  114. .message(_MessageContext($0, compressed: compressed))
  115. }, promise: promise)
  116. }
  117. /// Terminates a stream of messages sent to the service.
  118. ///
  119. /// - Important: This should only ever be called once.
  120. /// - Parameter promise: A promise to be fulfilled when the end has been sent.
  121. public func sendEnd(promise: EventLoopPromise<Void>?) {
  122. self.transport.sendRequest(.end, promise: promise)
  123. }
  124. internal init(
  125. path: String,
  126. scheme: String,
  127. authority: String,
  128. callOptions: CallOptions,
  129. eventLoop: EventLoop,
  130. multiplexer: EventLoopFuture<HTTP2StreamMultiplexer>,
  131. errorDelegate: ClientErrorDelegate?,
  132. logger: Logger
  133. ) {
  134. let requestID = callOptions.requestIDProvider.requestID()
  135. var logger = logger
  136. logger[metadataKey: MetadataKey.requestID] = "\(requestID)"
  137. logger.debug("starting rpc", metadata: ["path": "\(path)"])
  138. let responsePromise: EventLoopPromise<ResponsePayload> = eventLoop.makePromise()
  139. self.transport = ChannelTransport(
  140. multiplexer: multiplexer,
  141. responseContainer: .init(eventLoop: eventLoop, unaryResponsePromise: responsePromise),
  142. callType: .clientStreaming,
  143. timeLimit: callOptions.timeLimit,
  144. errorDelegate: errorDelegate,
  145. logger: logger
  146. )
  147. self.options = callOptions
  148. self.response = responsePromise.futureResult
  149. let requestHead = _GRPCRequestHead(
  150. scheme: scheme,
  151. path: path,
  152. host: authority,
  153. requestID: requestID,
  154. options: callOptions
  155. )
  156. self.transport.sendRequest(.head(requestHead), promise: nil)
  157. }
  158. }