GRPCAsyncClientCallTests.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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 EchoImplementation
  17. import EchoModel
  18. @testable import GRPC
  19. import NIOHPACK
  20. import NIOPosix
  21. import XCTest
  22. @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)
  23. class GRPCAsyncClientCallTests: GRPCTestCase {
  24. private var group: MultiThreadedEventLoopGroup?
  25. private var server: Server?
  26. private var channel: ClientConnection?
  27. private static let OKInitialMetadata = HPACKHeaders([
  28. (":status", "200"),
  29. ("content-type", "application/grpc"),
  30. ])
  31. private static let OKTrailingMetadata = HPACKHeaders([
  32. ("grpc-status", "0"),
  33. ])
  34. private func setUpServerAndChannel(
  35. service: CallHandlerProvider = EchoProvider()
  36. ) throws -> ClientConnection {
  37. let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  38. self.group = group
  39. let server = try Server.insecure(group: group)
  40. .withServiceProviders([service])
  41. .withLogger(self.serverLogger)
  42. .bind(host: "127.0.0.1", port: 0)
  43. .wait()
  44. self.server = server
  45. let channel = ClientConnection.insecure(group: group)
  46. .withBackgroundActivityLogger(self.clientLogger)
  47. .connect(host: "127.0.0.1", port: server.channel.localAddress!.port!)
  48. self.channel = channel
  49. return channel
  50. }
  51. override func tearDown() {
  52. if let channel = self.channel {
  53. XCTAssertNoThrow(try channel.close().wait())
  54. }
  55. if let server = self.server {
  56. XCTAssertNoThrow(try server.close().wait())
  57. }
  58. if let group = self.group {
  59. XCTAssertNoThrow(try group.syncShutdownGracefully())
  60. }
  61. super.tearDown()
  62. }
  63. func testAsyncUnaryCall() async throws {
  64. let channel = try self.setUpServerAndChannel()
  65. let get: GRPCAsyncUnaryCall<Echo_EchoRequest, Echo_EchoResponse> = channel.makeAsyncUnaryCall(
  66. path: "/echo.Echo/Get",
  67. request: .with { $0.text = "holt" },
  68. callOptions: .init()
  69. )
  70. await assertThat(try await get.initialMetadata, .is(.equalTo(Self.OKInitialMetadata)))
  71. await assertThat(try await get.response, .doesNotThrow())
  72. await assertThat(try await get.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata)))
  73. await assertThat(await get.status, .hasCode(.ok))
  74. print(try await get.trailingMetadata)
  75. }
  76. func testAsyncClientStreamingCall() async throws {
  77. let channel = try self.setUpServerAndChannel()
  78. let collect: GRPCAsyncClientStreamingCall<Echo_EchoRequest, Echo_EchoResponse> = channel
  79. .makeAsyncClientStreamingCall(
  80. path: "/echo.Echo/Collect",
  81. callOptions: .init()
  82. )
  83. for word in ["boyle", "jeffers", "holt"] {
  84. try await collect.requestStream.send(.with { $0.text = word })
  85. }
  86. collect.requestStream.finish()
  87. await assertThat(try await collect.initialMetadata, .is(.equalTo(Self.OKInitialMetadata)))
  88. await assertThat(try await collect.response, .doesNotThrow())
  89. await assertThat(try await collect.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata)))
  90. await assertThat(await collect.status, .hasCode(.ok))
  91. }
  92. func testAsyncServerStreamingCall() async throws {
  93. let channel = try self.setUpServerAndChannel()
  94. let expand: GRPCAsyncServerStreamingCall<Echo_EchoRequest, Echo_EchoResponse> = channel
  95. .makeAsyncServerStreamingCall(
  96. path: "/echo.Echo/Expand",
  97. request: .with { $0.text = "boyle jeffers holt" },
  98. callOptions: .init()
  99. )
  100. await assertThat(try await expand.initialMetadata, .is(.equalTo(Self.OKInitialMetadata)))
  101. let numResponses = try await expand.responseStream.map { _ in 1 }.reduce(0, +)
  102. await assertThat(numResponses, .is(.equalTo(3)))
  103. await assertThat(try await expand.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata)))
  104. await assertThat(await expand.status, .hasCode(.ok))
  105. }
  106. func testAsyncBidirectionalStreamingCall() async throws {
  107. let channel = try self.setUpServerAndChannel()
  108. let update: GRPCAsyncBidirectionalStreamingCall<Echo_EchoRequest, Echo_EchoResponse> = channel
  109. .makeAsyncBidirectionalStreamingCall(
  110. path: "/echo.Echo/Update",
  111. callOptions: .init()
  112. )
  113. let requests = ["boyle", "jeffers", "holt"]
  114. .map { word in Echo_EchoRequest.with { $0.text = word } }
  115. for request in requests {
  116. try await update.requestStream.send(request)
  117. }
  118. try await update.requestStream.send(requests)
  119. update.requestStream.finish()
  120. let numResponses = try await update.responseStream.map { _ in 1 }.reduce(0, +)
  121. await assertThat(numResponses, .is(.equalTo(6)))
  122. await assertThat(try await update.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata)))
  123. await assertThat(await update.status, .hasCode(.ok))
  124. }
  125. func testAsyncBidirectionalStreamingCall_InterleavedRequestsAndResponses() async throws {
  126. let channel = try self.setUpServerAndChannel()
  127. let update: GRPCAsyncBidirectionalStreamingCall<Echo_EchoRequest, Echo_EchoResponse> = channel
  128. .makeAsyncBidirectionalStreamingCall(
  129. path: "/echo.Echo/Update",
  130. callOptions: .init()
  131. )
  132. await assertThat(try await update.initialMetadata, .is(.equalTo(Self.OKInitialMetadata)))
  133. var responseStreamIterator = update.responseStream.makeAsyncIterator()
  134. for word in ["boyle", "jeffers", "holt"] {
  135. try await update.requestStream.send(.with { $0.text = word })
  136. await assertThat(try await responseStreamIterator.next(), .is(.some()))
  137. }
  138. update.requestStream.finish()
  139. await assertThat(try await responseStreamIterator.next(), .is(.none()))
  140. await assertThat(try await update.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata)))
  141. await assertThat(await update.status, .hasCode(.ok))
  142. }
  143. func testAsyncBidirectionalStreamingCall_ConcurrentTasks() async throws {
  144. let channel = try self.setUpServerAndChannel()
  145. let update: GRPCAsyncBidirectionalStreamingCall<Echo_EchoRequest, Echo_EchoResponse> = channel
  146. .makeAsyncBidirectionalStreamingCall(
  147. path: "/echo.Echo/Update",
  148. callOptions: .init()
  149. )
  150. await assertThat(try await update.initialMetadata, .is(.equalTo(Self.OKInitialMetadata)))
  151. let counter = RequestResponseCounter()
  152. // Send the requests and get responses in separate concurrent tasks and await the group.
  153. _ = await withThrowingTaskGroup(of: Void.self) { taskGroup in
  154. // Send requests, then end, in a task.
  155. taskGroup.addTask {
  156. for word in ["boyle", "jeffers", "holt"] {
  157. try await update.requestStream.send(.with { $0.text = word })
  158. await counter.incrementRequests()
  159. }
  160. update.requestStream.finish()
  161. }
  162. // Get responses in a separate task.
  163. taskGroup.addTask {
  164. for try await _ in update.responseStream {
  165. await counter.incrementResponses()
  166. }
  167. }
  168. }
  169. await assertThat(await counter.numRequests, .is(.equalTo(3)))
  170. await assertThat(await counter.numResponses, .is(.equalTo(3)))
  171. await assertThat(try await update.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata)))
  172. await assertThat(await update.status, .hasCode(.ok))
  173. }
  174. func testExplicitAcceptUnary(twice: Bool, function: String = #function) async throws {
  175. let headers: HPACKHeaders = ["fn": function]
  176. let channel = try self.setUpServerAndChannel(
  177. service: AsyncEchoProvider(headers: headers, sendTwice: twice)
  178. )
  179. let echo = Echo_EchoAsyncClient(channel: channel)
  180. let call = echo.makeGetCall(.with { $0.text = "" })
  181. let responseHeaders = try await call.initialMetadata
  182. XCTAssertEqual(responseHeaders.first(name: "fn"), function)
  183. let status = await call.status
  184. XCTAssertEqual(status.code, .ok)
  185. }
  186. func testExplicitAcceptUnary() async throws {
  187. try await self.testExplicitAcceptUnary(twice: false)
  188. }
  189. func testExplicitAcceptTwiceUnary() async throws {
  190. try await self.testExplicitAcceptUnary(twice: true)
  191. }
  192. func testExplicitAcceptClientStreaming(twice: Bool, function: String = #function) async throws {
  193. let headers: HPACKHeaders = ["fn": function]
  194. let channel = try self.setUpServerAndChannel(
  195. service: AsyncEchoProvider(headers: headers, sendTwice: twice)
  196. )
  197. let echo = Echo_EchoAsyncClient(channel: channel)
  198. let call = echo.makeCollectCall()
  199. let responseHeaders = try await call.initialMetadata
  200. XCTAssertEqual(responseHeaders.first(name: "fn"), function)
  201. // Close request stream; the response should be empty.
  202. call.requestStream.finish()
  203. let response = try await call.response
  204. XCTAssertEqual(response.text, "")
  205. let status = await call.status
  206. XCTAssertEqual(status.code, .ok)
  207. }
  208. func testExplicitAcceptClientStreaming() async throws {
  209. try await self.testExplicitAcceptClientStreaming(twice: false)
  210. }
  211. func testExplicitAcceptTwiceClientStreaming() async throws {
  212. try await self.testExplicitAcceptClientStreaming(twice: true)
  213. }
  214. func testExplicitAcceptServerStreaming(twice: Bool, function: String = #function) async throws {
  215. let headers: HPACKHeaders = ["fn": #function]
  216. let channel = try self.setUpServerAndChannel(
  217. service: AsyncEchoProvider(headers: headers, sendTwice: twice)
  218. )
  219. let echo = Echo_EchoAsyncClient(channel: channel)
  220. let call = echo.makeExpandCall(.with { $0.text = "foo bar baz" })
  221. let responseHeaders = try await call.initialMetadata
  222. XCTAssertEqual(responseHeaders.first(name: "fn"), #function)
  223. // Close request stream; the response should be empty.
  224. let responses = try await call.responseStream.collect()
  225. XCTAssertEqual(responses.count, 3)
  226. let status = await call.status
  227. XCTAssertEqual(status.code, .ok)
  228. }
  229. func testExplicitAcceptServerStreaming() async throws {
  230. try await self.testExplicitAcceptServerStreaming(twice: false)
  231. }
  232. func testExplicitAcceptTwiceServerStreaming() async throws {
  233. try await self.testExplicitAcceptServerStreaming(twice: true)
  234. }
  235. func testExplicitAcceptBidirectionalStreaming(
  236. twice: Bool,
  237. function: String = #function
  238. ) async throws {
  239. let headers: HPACKHeaders = ["fn": function]
  240. let channel = try self.setUpServerAndChannel(
  241. service: AsyncEchoProvider(headers: headers, sendTwice: twice)
  242. )
  243. let echo = Echo_EchoAsyncClient(channel: channel)
  244. let call = echo.makeUpdateCall()
  245. let responseHeaders = try await call.initialMetadata
  246. XCTAssertEqual(responseHeaders.first(name: "fn"), function)
  247. // Close request stream; there should be no responses.
  248. call.requestStream.finish()
  249. let responses = try await call.responseStream.collect()
  250. XCTAssertEqual(responses.count, 0)
  251. let status = await call.status
  252. XCTAssertEqual(status.code, .ok)
  253. }
  254. func testExplicitAcceptBidirectionalStreaming() async throws {
  255. try await self.testExplicitAcceptBidirectionalStreaming(twice: false)
  256. }
  257. func testExplicitAcceptTwiceBidirectionalStreaming() async throws {
  258. try await self.testExplicitAcceptBidirectionalStreaming(twice: true)
  259. }
  260. }
  261. // Workaround https://bugs.swift.org/browse/SR-15070 (compiler crashes when defining a class/actor
  262. // in an async context).
  263. @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)
  264. private actor RequestResponseCounter {
  265. var numResponses = 0
  266. var numRequests = 0
  267. func incrementResponses() async {
  268. self.numResponses += 1
  269. }
  270. func incrementRequests() async {
  271. self.numRequests += 1
  272. }
  273. }
  274. private final class AsyncEchoProvider: Echo_EchoAsyncProvider {
  275. let headers: HPACKHeaders
  276. let sendTwice: Bool
  277. init(headers: HPACKHeaders, sendTwice: Bool = false) {
  278. self.headers = headers
  279. self.sendTwice = sendTwice
  280. }
  281. private func accept(context: GRPCAsyncServerCallContext) async {
  282. await context.acceptRPC(headers: self.headers)
  283. if self.sendTwice {
  284. await context.acceptRPC(headers: self.headers) // Should be a no-op.
  285. }
  286. }
  287. func get(
  288. request: Echo_EchoRequest,
  289. context: GRPCAsyncServerCallContext
  290. ) async throws -> Echo_EchoResponse {
  291. await self.accept(context: context)
  292. return Echo_EchoResponse.with { $0.text = request.text }
  293. }
  294. func expand(
  295. request: Echo_EchoRequest,
  296. responseStream: GRPCAsyncResponseStreamWriter<Echo_EchoResponse>,
  297. context: GRPCAsyncServerCallContext
  298. ) async throws {
  299. await self.accept(context: context)
  300. for part in request.text.components(separatedBy: " ") {
  301. let response = Echo_EchoResponse.with {
  302. $0.text = part
  303. }
  304. try await responseStream.send(response)
  305. }
  306. }
  307. func collect(
  308. requestStream: GRPCAsyncRequestStream<Echo_EchoRequest>,
  309. context: GRPCAsyncServerCallContext
  310. ) async throws -> Echo_EchoResponse {
  311. await self.accept(context: context)
  312. let collected = try await requestStream.map { $0.text }.collect().joined(separator: " ")
  313. return Echo_EchoResponse.with { $0.text = collected }
  314. }
  315. func update(
  316. requestStream: GRPCAsyncRequestStream<Echo_EchoRequest>,
  317. responseStream: GRPCAsyncResponseStreamWriter<Echo_EchoResponse>,
  318. context: GRPCAsyncServerCallContext
  319. ) async throws {
  320. await self.accept(context: context)
  321. for try await request in requestStream {
  322. let response = Echo_EchoResponse.with { $0.text = request.text }
  323. try await responseStream.send(response)
  324. }
  325. }
  326. }