GRPCAsyncClientCallTests.swift 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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.6)
  17. import EchoImplementation
  18. import EchoModel
  19. @testable import GRPC
  20. import NIOHPACK
  21. import NIOPosix
  22. import XCTest
  23. @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)
  24. class GRPCAsyncClientCallTests: GRPCTestCase {
  25. private var group: MultiThreadedEventLoopGroup?
  26. private var server: Server?
  27. private var channel: ClientConnection?
  28. private static let OKInitialMetadata = HPACKHeaders([
  29. (":status", "200"),
  30. ("content-type", "application/grpc"),
  31. ])
  32. private static let OKTrailingMetadata = HPACKHeaders([
  33. ("grpc-status", "0"),
  34. ])
  35. private func setUpServerAndChannel() throws -> ClientConnection {
  36. let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  37. self.group = group
  38. let server = try Server.insecure(group: group)
  39. .withServiceProviders([EchoProvider()])
  40. .withLogger(self.serverLogger)
  41. .bind(host: "127.0.0.1", port: 0)
  42. .wait()
  43. self.server = server
  44. let channel = ClientConnection.insecure(group: group)
  45. .withBackgroundActivityLogger(self.clientLogger)
  46. .connect(host: "127.0.0.1", port: server.channel.localAddress!.port!)
  47. self.channel = channel
  48. return channel
  49. }
  50. override func tearDown() {
  51. if let channel = self.channel {
  52. XCTAssertNoThrow(try channel.close().wait())
  53. }
  54. if let server = self.server {
  55. XCTAssertNoThrow(try server.close().wait())
  56. }
  57. if let group = self.group {
  58. XCTAssertNoThrow(try group.syncShutdownGracefully())
  59. }
  60. super.tearDown()
  61. }
  62. func testAsyncUnaryCall() async throws {
  63. let channel = try self.setUpServerAndChannel()
  64. let get: GRPCAsyncUnaryCall<Echo_EchoRequest, Echo_EchoResponse> = channel.makeAsyncUnaryCall(
  65. path: "/echo.Echo/Get",
  66. request: .with { $0.text = "holt" },
  67. callOptions: .init()
  68. )
  69. await assertThat(try await get.initialMetadata, .is(.equalTo(Self.OKInitialMetadata)))
  70. await assertThat(try await get.response, .doesNotThrow())
  71. await assertThat(try await get.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata)))
  72. await assertThat(await get.status, .hasCode(.ok))
  73. print(try await get.trailingMetadata)
  74. }
  75. func testAsyncClientStreamingCall() async throws {
  76. let channel = try self.setUpServerAndChannel()
  77. let collect: GRPCAsyncClientStreamingCall<Echo_EchoRequest, Echo_EchoResponse> = channel
  78. .makeAsyncClientStreamingCall(
  79. path: "/echo.Echo/Collect",
  80. callOptions: .init()
  81. )
  82. for word in ["boyle", "jeffers", "holt"] {
  83. try await collect.requestStream.send(.with { $0.text = word })
  84. }
  85. try await collect.requestStream.finish()
  86. await assertThat(try await collect.initialMetadata, .is(.equalTo(Self.OKInitialMetadata)))
  87. await assertThat(try await collect.response, .doesNotThrow())
  88. await assertThat(try await collect.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata)))
  89. await assertThat(await collect.status, .hasCode(.ok))
  90. }
  91. func testAsyncServerStreamingCall() async throws {
  92. let channel = try self.setUpServerAndChannel()
  93. let expand: GRPCAsyncServerStreamingCall<Echo_EchoRequest, Echo_EchoResponse> = channel
  94. .makeAsyncServerStreamingCall(
  95. path: "/echo.Echo/Expand",
  96. request: .with { $0.text = "boyle jeffers holt" },
  97. callOptions: .init()
  98. )
  99. await assertThat(try await expand.initialMetadata, .is(.equalTo(Self.OKInitialMetadata)))
  100. let numResponses = try await expand.responseStream.map { _ in 1 }.reduce(0, +)
  101. await assertThat(numResponses, .is(.equalTo(3)))
  102. await assertThat(try await expand.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata)))
  103. await assertThat(await expand.status, .hasCode(.ok))
  104. }
  105. func testAsyncBidirectionalStreamingCall() async throws {
  106. let channel = try self.setUpServerAndChannel()
  107. let update: GRPCAsyncBidirectionalStreamingCall<Echo_EchoRequest, Echo_EchoResponse> = channel
  108. .makeAsyncBidirectionalStreamingCall(
  109. path: "/echo.Echo/Update",
  110. callOptions: .init()
  111. )
  112. let requests = ["boyle", "jeffers", "holt"]
  113. .map { word in Echo_EchoRequest.with { $0.text = word } }
  114. for request in requests {
  115. try await update.requestStream.send(request)
  116. }
  117. try await update.requestStream.send(requests)
  118. try await update.requestStream.finish()
  119. let numResponses = try await update.responseStream.map { _ in 1 }.reduce(0, +)
  120. await assertThat(numResponses, .is(.equalTo(6)))
  121. await assertThat(try await update.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata)))
  122. await assertThat(await update.status, .hasCode(.ok))
  123. }
  124. func testAsyncBidirectionalStreamingCall_InterleavedRequestsAndResponses() async throws {
  125. let channel = try self.setUpServerAndChannel()
  126. let update: GRPCAsyncBidirectionalStreamingCall<Echo_EchoRequest, Echo_EchoResponse> = channel
  127. .makeAsyncBidirectionalStreamingCall(
  128. path: "/echo.Echo/Update",
  129. callOptions: .init()
  130. )
  131. await assertThat(try await update.initialMetadata, .is(.equalTo(Self.OKInitialMetadata)))
  132. var responseStreamIterator = update.responseStream.makeAsyncIterator()
  133. for word in ["boyle", "jeffers", "holt"] {
  134. try await update.requestStream.send(.with { $0.text = word })
  135. await assertThat(try await responseStreamIterator.next(), .is(.notNil()))
  136. }
  137. try await update.requestStream.finish()
  138. await assertThat(try await responseStreamIterator.next(), .is(.nil()))
  139. await assertThat(try await update.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata)))
  140. await assertThat(await update.status, .hasCode(.ok))
  141. }
  142. func testAsyncBidirectionalStreamingCall_ConcurrentTasks() async throws {
  143. let channel = try self.setUpServerAndChannel()
  144. let update: GRPCAsyncBidirectionalStreamingCall<Echo_EchoRequest, Echo_EchoResponse> = channel
  145. .makeAsyncBidirectionalStreamingCall(
  146. path: "/echo.Echo/Update",
  147. callOptions: .init()
  148. )
  149. await assertThat(try await update.initialMetadata, .is(.equalTo(Self.OKInitialMetadata)))
  150. let counter = RequestResponseCounter()
  151. // Send the requests and get responses in separate concurrent tasks and await the group.
  152. _ = await withThrowingTaskGroup(of: Void.self) { taskGroup in
  153. // Send requests, then end, in a task.
  154. taskGroup.addTask {
  155. for word in ["boyle", "jeffers", "holt"] {
  156. try await update.requestStream.send(.with { $0.text = word })
  157. await counter.incrementRequests()
  158. }
  159. try await update.requestStream.finish()
  160. }
  161. // Get responses in a separate task.
  162. taskGroup.addTask {
  163. for try await _ in update.responseStream {
  164. await counter.incrementResponses()
  165. }
  166. }
  167. }
  168. await assertThat(await counter.numRequests, .is(.equalTo(3)))
  169. await assertThat(await counter.numResponses, .is(.equalTo(3)))
  170. await assertThat(try await update.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata)))
  171. await assertThat(await update.status, .hasCode(.ok))
  172. }
  173. }
  174. // Workaround https://bugs.swift.org/browse/SR-15070 (compiler crashes when defining a class/actor
  175. // in an async context).
  176. @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)
  177. fileprivate actor RequestResponseCounter {
  178. var numResponses = 0
  179. var numRequests = 0
  180. func incrementResponses() async {
  181. self.numResponses += 1
  182. }
  183. func incrementRequests() async {
  184. self.numRequests += 1
  185. }
  186. }
  187. #endif