GRPCAsyncBidirectionalStreamingCall.swift 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. /*
  2. * Copyright 2021, 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 compiler(>=5.5)
  17. import _NIOConcurrency
  18. import NIOHPACK
  19. /// Async-await variant of BidirectionalStreamingCall.
  20. @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)
  21. public struct GRPCAsyncBidirectionalStreamingCall<Request, Response> {
  22. private let call: Call<Request, Response>
  23. private let responseParts: StreamingResponseParts<Response>
  24. /// The stream of responses from the server.
  25. public let responses: GRPCAsyncResponseStream<Response>
  26. /// The options used to make the RPC.
  27. public var options: CallOptions {
  28. return self.call.options
  29. }
  30. /// Cancel this RPC if it hasn't already completed.
  31. public func cancel() async throws {
  32. try await self.call.cancel().get()
  33. }
  34. // MARK: - Response Parts
  35. /// The initial metadata returned from the server.
  36. ///
  37. /// - Important: The initial metadata will only be available when the first response has been
  38. /// received. However, it is not necessary for the response to have been consumed before reading
  39. /// this property.
  40. public var initialMetadata: HPACKHeaders {
  41. // swiftformat:disable:next redundantGet
  42. get async throws {
  43. try await self.responseParts.initialMetadata.get()
  44. }
  45. }
  46. /// The trailing metadata returned from the server.
  47. ///
  48. /// - Important: Awaiting this property will suspend until the responses have been consumed.
  49. public var trailingMetadata: HPACKHeaders {
  50. // swiftformat:disable:next redundantGet
  51. get async throws {
  52. try await self.responseParts.trailingMetadata.get()
  53. }
  54. }
  55. /// The final status of the the RPC.
  56. ///
  57. /// - Important: Awaiting this property will suspend until the responses have been consumed.
  58. public var status: GRPCStatus {
  59. // swiftformat:disable:next redundantGet
  60. get async {
  61. // force-try acceptable because any error is encapsulated in a successful GRPCStatus future.
  62. try! await self.responseParts.status.get()
  63. }
  64. }
  65. private init(call: Call<Request, Response>) {
  66. self.call = call
  67. // Initialise `responseParts` with an empty response handler because we
  68. // provide the responses as an AsyncSequence in `responseStream`.
  69. self.responseParts = StreamingResponseParts(on: call.eventLoop) { _ in }
  70. // Call and StreamingResponseParts are reference types so we grab a
  71. // referecence to them here to avoid capturing mutable self in the closure
  72. // passed to the AsyncThrowingStream initializer.
  73. //
  74. // The alternative would be to declare the responseStream as:
  75. // ```
  76. // public private(set) var responseStream: AsyncThrowingStream<ResponsePayload>!
  77. // ```
  78. //
  79. // UPDATE: Additionally we expect to replace this soon with an AsyncSequence
  80. // implementation that supports yielding values from outside the closure.
  81. let call = self.call
  82. let responseParts = self.responseParts
  83. let responseStream = AsyncThrowingStream(Response.self) { continuation in
  84. call.invokeStreamingRequests { error in
  85. responseParts.handleError(error)
  86. continuation.finish(throwing: error)
  87. } onResponsePart: { responsePart in
  88. responseParts.handle(responsePart)
  89. switch responsePart {
  90. case let .message(response):
  91. continuation.yield(response)
  92. case .metadata:
  93. break
  94. case .end:
  95. continuation.finish()
  96. }
  97. }
  98. }
  99. self.responses = .init(responseStream)
  100. }
  101. /// We expose this as the only non-private initializer so that the caller
  102. /// knows that invocation is part of initialisation.
  103. internal static func makeAndInvoke(call: Call<Request, Response>) -> Self {
  104. Self(call: call)
  105. }
  106. // MARK: - Requests
  107. /// Sends a message to the service.
  108. ///
  109. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()`.
  110. ///
  111. /// - Parameters:
  112. /// - message: The message to send.
  113. /// - compression: Whether compression should be used for this message. Ignored if compression
  114. /// was not enabled for the RPC.
  115. public func sendMessage(
  116. _ message: Request,
  117. compression: Compression = .deferToCallDefault
  118. ) async throws {
  119. let compress = self.call.compress(compression)
  120. let promise = self.call.eventLoop.makePromise(of: Void.self)
  121. self.call.send(.message(message, .init(compress: compress, flush: true)), promise: promise)
  122. // TODO: This waits for the message to be written to the socket. We should probably just wait for it to be written to the channel?
  123. try await promise.futureResult.get()
  124. }
  125. /// Sends a sequence of messages to the service.
  126. ///
  127. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()`.
  128. ///
  129. /// - Parameters:
  130. /// - messages: The sequence of messages to send.
  131. /// - compression: Whether compression should be used for this message. Ignored if compression
  132. /// was not enabled for the RPC.
  133. public func sendMessages<S>(
  134. _ messages: S,
  135. compression: Compression = .deferToCallDefault
  136. ) async throws where S: Sequence, S.Element == Request {
  137. let promise = self.call.eventLoop.makePromise(of: Void.self)
  138. self.call.sendMessages(messages, compression: compression, promise: promise)
  139. try await promise.futureResult.get()
  140. }
  141. /// Terminates a stream of messages sent to the service.
  142. ///
  143. /// - Important: This should only ever be called once.
  144. public func sendEnd() async throws {
  145. let promise = self.call.eventLoop.makePromise(of: Void.self)
  146. self.call.send(.end, promise: promise)
  147. try await promise.futureResult.get()
  148. }
  149. }
  150. #endif