GRPCAsyncBidirectionalStreamingCall.swift 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. public var initialMetadata: HPACKHeaders {
  37. // swiftformat:disable:next redundantGet
  38. get async throws {
  39. try await self.responseParts.initialMetadata.get()
  40. }
  41. }
  42. /// The trailing metadata returned from the server.
  43. ///
  44. /// - Important: Awaiting this property will suspend until the responses have been consumed.
  45. public var trailingMetadata: HPACKHeaders {
  46. // swiftformat:disable:next redundantGet
  47. get async throws {
  48. try await self.responseParts.trailingMetadata.get()
  49. }
  50. }
  51. /// The final status of the the RPC.
  52. ///
  53. /// - Important: Awaiting this property will suspend until the responses have been consumed.
  54. public var status: GRPCStatus {
  55. // swiftformat:disable:next redundantGet
  56. get async {
  57. // force-try acceptable because any error is encapsulated in a successful GRPCStatus future.
  58. try! await self.responseParts.status.get()
  59. }
  60. }
  61. private init(call: Call<Request, Response>) {
  62. self.call = call
  63. // Initialise `responseParts` with an empty response handler because we
  64. // provide the responses as an AsyncSequence in `responseStream`.
  65. self.responseParts = StreamingResponseParts(on: call.eventLoop) { _ in }
  66. // Call and StreamingResponseParts are reference types so we grab a
  67. // referecence to them here to avoid capturing mutable self in the closure
  68. // passed to the AsyncThrowingStream initializer.
  69. //
  70. // The alternative would be to declare the responseStream as:
  71. // ```
  72. // public private(set) var responseStream: AsyncThrowingStream<ResponsePayload>!
  73. // ```
  74. //
  75. // UPDATE: Additionally we expect to replace this soon with an AsyncSequence
  76. // implementation that supports yielding values from outside the closure.
  77. let call = self.call
  78. let responseParts = self.responseParts
  79. let responseStream = AsyncThrowingStream(Response.self) { continuation in
  80. call.invokeStreamingRequests { error in
  81. responseParts.handleError(error)
  82. continuation.finish(throwing: error)
  83. } onResponsePart: { responsePart in
  84. responseParts.handle(responsePart)
  85. switch responsePart {
  86. case let .message(response):
  87. continuation.yield(response)
  88. case .metadata:
  89. break
  90. case .end:
  91. continuation.finish()
  92. }
  93. }
  94. }
  95. self.responses = .init(responseStream)
  96. }
  97. /// We expose this as the only non-private initializer so that the caller
  98. /// knows that invocation is part of initialisation.
  99. internal static func makeAndInvoke(call: Call<Request, Response>) -> Self {
  100. Self(call: call)
  101. }
  102. // MARK: - Requests
  103. /// Sends a message to the service.
  104. ///
  105. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()`.
  106. ///
  107. /// - Parameters:
  108. /// - message: The message to send.
  109. /// - compression: Whether compression should be used for this message. Ignored if compression
  110. /// was not enabled for the RPC.
  111. public func sendMessage(
  112. _ message: Request,
  113. compression: Compression = .deferToCallDefault
  114. ) async throws {
  115. let compress = self.call.compress(compression)
  116. let promise = self.call.eventLoop.makePromise(of: Void.self)
  117. self.call.send(.message(message, .init(compress: compress, flush: true)), promise: promise)
  118. // 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?
  119. try await promise.futureResult.get()
  120. }
  121. /// Sends a sequence of messages to the service.
  122. ///
  123. /// - Important: Callers must terminate the stream of messages by calling `sendEnd()`.
  124. ///
  125. /// - Parameters:
  126. /// - messages: The sequence of messages to send.
  127. /// - compression: Whether compression should be used for this message. Ignored if compression
  128. /// was not enabled for the RPC.
  129. public func sendMessages<S>(
  130. _ messages: S,
  131. compression: Compression = .deferToCallDefault
  132. ) async throws where S: Sequence, S.Element == Request {
  133. let promise = self.call.eventLoop.makePromise(of: Void.self)
  134. self.call.sendMessages(messages, compression: compression, promise: promise)
  135. try await promise.futureResult.get()
  136. }
  137. /// Terminates a stream of messages sent to the service.
  138. ///
  139. /// - Important: This should only ever be called once.
  140. public func sendEnd() async throws {
  141. let promise = self.call.eventLoop.makePromise(of: Void.self)
  142. self.call.send(.end, promise: promise)
  143. try await promise.futureResult.get()
  144. }
  145. }
  146. #endif