GRPCAsyncResponseStreamWriter.swift 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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. import NIOCore
  17. /// Writer for server-streaming RPC handlers to provide responses.
  18. ///
  19. /// To enable testability this type provides a static ``GRPCAsyncResponseStreamWriter/makeTestingResponseStreamWriter()``
  20. /// method which allows you to create a stream that you can drive.
  21. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  22. public struct GRPCAsyncResponseStreamWriter<Response: Sendable>: Sendable {
  23. @usableFromInline
  24. internal typealias AsyncWriter = NIOAsyncWriter<
  25. (Response, Compression),
  26. GRPCAsyncWriterSinkDelegate<(Response, Compression)>
  27. >
  28. /// An `AsyncSequence` backing a ``GRPCAsyncResponseStreamWriter`` for testing purposes.
  29. ///
  30. /// - Important: This `AsyncSequence` is never finishing.
  31. public struct ResponseStream: AsyncSequence {
  32. public typealias Element = (Response, Compression)
  33. @usableFromInline
  34. internal let stream: AsyncStream<(Response, Compression)>
  35. @usableFromInline
  36. internal let continuation: AsyncStream<(Response, Compression)>.Continuation
  37. @inlinable
  38. init(
  39. stream: AsyncStream<(Response, Compression)>,
  40. continuation: AsyncStream<(Response, Compression)>.Continuation
  41. ) {
  42. self.stream = stream
  43. self.continuation = continuation
  44. }
  45. public func makeAsyncIterator() -> AsyncIterator {
  46. AsyncIterator(iterator: self.stream.makeAsyncIterator())
  47. }
  48. /// Finishes the response stream.
  49. ///
  50. /// This is useful in tests to finish the stream after the async method finished and allows you to collect all written responses.
  51. public func finish() {
  52. self.continuation.finish()
  53. }
  54. public struct AsyncIterator: AsyncIteratorProtocol {
  55. @usableFromInline
  56. internal var iterator: AsyncStream<(Response, Compression)>.AsyncIterator
  57. @inlinable
  58. init(iterator: AsyncStream<(Response, Compression)>.AsyncIterator) {
  59. self.iterator = iterator
  60. }
  61. public mutating func next() async -> Element? {
  62. await self.iterator.next()
  63. }
  64. }
  65. }
  66. /// Simple struct for the return type of ``GRPCAsyncResponseStreamWriter/makeTestingResponseStreamWriter()``.
  67. ///
  68. /// This struct contains two properties:
  69. /// 1. The ``writer`` which is the actual ``GRPCAsyncResponseStreamWriter`` and should be passed to the method under testing.
  70. /// 2. The ``stream`` which can be used to observe the written responses.
  71. public struct TestingStreamWriter {
  72. /// The actual writer.
  73. public let writer: GRPCAsyncResponseStreamWriter<Response>
  74. /// The written responses in a stream.
  75. ///
  76. /// - Important: This `AsyncSequence` is never finishing.
  77. public let stream: ResponseStream
  78. @inlinable
  79. init(writer: GRPCAsyncResponseStreamWriter<Response>, stream: ResponseStream) {
  80. self.writer = writer
  81. self.stream = stream
  82. }
  83. }
  84. @usableFromInline
  85. enum Backing: Sendable {
  86. case asyncWriter(AsyncWriter)
  87. case closure(@Sendable ((Response, Compression)) async -> Void)
  88. }
  89. @usableFromInline
  90. internal let backing: Backing
  91. @inlinable
  92. internal init(wrapping asyncWriter: AsyncWriter) {
  93. self.backing = .asyncWriter(asyncWriter)
  94. }
  95. @inlinable
  96. internal init(onWrite: @escaping @Sendable ((Response, Compression)) async -> Void) {
  97. self.backing = .closure(onWrite)
  98. }
  99. @inlinable
  100. public func send(
  101. _ response: Response,
  102. compression: Compression = .deferToCallDefault
  103. ) async throws {
  104. switch self.backing {
  105. case let .asyncWriter(writer):
  106. try await writer.yield((response, compression))
  107. case let .closure(closure):
  108. await closure((response, compression))
  109. }
  110. }
  111. @inlinable
  112. public func send<S: Sequence>(
  113. contentsOf responses: S,
  114. compression: Compression = .deferToCallDefault
  115. ) async throws where S.Element == Response {
  116. let responsesWithCompression = responses.lazy.map { ($0, compression) }
  117. switch self.backing {
  118. case let .asyncWriter(writer):
  119. try await writer.yield(contentsOf: responsesWithCompression)
  120. case let .closure(closure):
  121. for response in responsesWithCompression {
  122. await closure(response)
  123. }
  124. }
  125. }
  126. /// Creates a new `GRPCAsyncResponseStreamWriter` backed by a ``ResponseStream``.
  127. /// This is mostly useful for testing purposes where one wants to observe the written responses.
  128. ///
  129. /// - Note: For most tests it is useful to call ``ResponseStream/finish()`` after the async method under testing
  130. /// resumed. This allows you to easily collect all written responses.
  131. @inlinable
  132. public static func makeTestingResponseStreamWriter() -> TestingStreamWriter {
  133. var continuation: AsyncStream<(Response, Compression)>.Continuation!
  134. let asyncStream = AsyncStream<(Response, Compression)> { cont in
  135. continuation = cont
  136. }
  137. let writer = Self.init { [continuation] in
  138. continuation!.yield($0)
  139. }
  140. let responseStream = ResponseStream(
  141. stream: asyncStream,
  142. continuation: continuation
  143. )
  144. return TestingStreamWriter(writer: writer, stream: responseStream)
  145. }
  146. }