GRPCClientTests.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /*
  2. * Copyright 2023, 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 Atomics
  17. import GRPCCore
  18. import GRPCInProcessTransport
  19. import XCTest
  20. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  21. final class GRPCClientTests: XCTestCase {
  22. func withInProcessConnectedClient(
  23. services: [any RegistrableRPCService],
  24. interceptors: [any ClientInterceptor] = [],
  25. _ body: (GRPCClient, GRPCServer) async throws -> Void
  26. ) async throws {
  27. let inProcess = InProcessTransport.makePair()
  28. let client = GRPCClient(transport: inProcess.client, interceptors: interceptors)
  29. let server = GRPCServer(transport: inProcess.server, services: services)
  30. try await withThrowingTaskGroup(of: Void.self) { group in
  31. group.addTask {
  32. try await server.run()
  33. }
  34. group.addTask {
  35. try await client.run()
  36. }
  37. // Make sure both server and client are running
  38. try await Task.sleep(for: .milliseconds(100))
  39. try await body(client, server)
  40. client.close()
  41. server.stopListening()
  42. }
  43. }
  44. struct IdentitySerializer: MessageSerializer {
  45. typealias Message = [UInt8]
  46. func serialize(_ message: [UInt8]) throws -> [UInt8] {
  47. return message
  48. }
  49. }
  50. struct IdentityDeserializer: MessageDeserializer {
  51. typealias Message = [UInt8]
  52. func deserialize(_ serializedMessageBytes: [UInt8]) throws -> [UInt8] {
  53. return serializedMessageBytes
  54. }
  55. }
  56. func testUnary() async throws {
  57. try await self.withInProcessConnectedClient(services: [BinaryEcho()]) { client, _ in
  58. try await client.unary(
  59. request: .init(message: [3, 1, 4, 1, 5]),
  60. descriptor: BinaryEcho.Methods.collect,
  61. serializer: IdentitySerializer(),
  62. deserializer: IdentityDeserializer(),
  63. options: .defaults
  64. ) { response in
  65. let message = try response.message
  66. XCTAssertEqual(message, [3, 1, 4, 1, 5])
  67. }
  68. }
  69. }
  70. func testClientStreaming() async throws {
  71. try await self.withInProcessConnectedClient(services: [BinaryEcho()]) { client, _ in
  72. try await client.clientStreaming(
  73. request: .init(producer: { writer in
  74. for byte in [3, 1, 4, 1, 5] as [UInt8] {
  75. try await writer.write([byte])
  76. }
  77. }),
  78. descriptor: BinaryEcho.Methods.collect,
  79. serializer: IdentitySerializer(),
  80. deserializer: IdentityDeserializer(),
  81. options: .defaults
  82. ) { response in
  83. let message = try response.message
  84. XCTAssertEqual(message, [3, 1, 4, 1, 5])
  85. }
  86. }
  87. }
  88. func testServerStreaming() async throws {
  89. try await self.withInProcessConnectedClient(services: [BinaryEcho()]) { client, _ in
  90. try await client.serverStreaming(
  91. request: .init(message: [3, 1, 4, 1, 5]),
  92. descriptor: BinaryEcho.Methods.expand,
  93. serializer: IdentitySerializer(),
  94. deserializer: IdentityDeserializer(),
  95. options: .defaults
  96. ) { response in
  97. var responseParts = response.messages.makeAsyncIterator()
  98. for byte in [3, 1, 4, 1, 5] as [UInt8] {
  99. let message = try await responseParts.next()
  100. XCTAssertEqual(message, [byte])
  101. }
  102. }
  103. }
  104. }
  105. func testBidirectionalStreaming() async throws {
  106. try await self.withInProcessConnectedClient(services: [BinaryEcho()]) { client, _ in
  107. try await client.bidirectionalStreaming(
  108. request: .init(producer: { writer in
  109. for byte in [3, 1, 4, 1, 5] as [UInt8] {
  110. try await writer.write([byte])
  111. }
  112. }),
  113. descriptor: BinaryEcho.Methods.update,
  114. serializer: IdentitySerializer(),
  115. deserializer: IdentityDeserializer(),
  116. options: .defaults
  117. ) { response in
  118. var responseParts = response.messages.makeAsyncIterator()
  119. for byte in [3, 1, 4, 1, 5] as [UInt8] {
  120. let message = try await responseParts.next()
  121. XCTAssertEqual(message, [byte])
  122. }
  123. }
  124. }
  125. }
  126. func testUnimplementedMethod_Unary() async throws {
  127. try await self.withInProcessConnectedClient(services: [BinaryEcho()]) { client, _ in
  128. try await client.unary(
  129. request: .init(message: [3, 1, 4, 1, 5]),
  130. descriptor: MethodDescriptor(service: "not", method: "implemented"),
  131. serializer: IdentitySerializer(),
  132. deserializer: IdentityDeserializer(),
  133. options: .defaults
  134. ) { response in
  135. XCTAssertThrowsRPCError(try response.accepted.get()) { error in
  136. XCTAssertEqual(error.code, .unimplemented)
  137. }
  138. }
  139. }
  140. }
  141. func testUnimplementedMethod_ClientStreaming() async throws {
  142. try await self.withInProcessConnectedClient(services: [BinaryEcho()]) { client, _ in
  143. try await client.clientStreaming(
  144. request: .init(producer: { writer in
  145. for byte in [3, 1, 4, 1, 5] as [UInt8] {
  146. try await writer.write([byte])
  147. }
  148. }),
  149. descriptor: MethodDescriptor(service: "not", method: "implemented"),
  150. serializer: IdentitySerializer(),
  151. deserializer: IdentityDeserializer(),
  152. options: .defaults
  153. ) { response in
  154. XCTAssertThrowsRPCError(try response.accepted.get()) { error in
  155. XCTAssertEqual(error.code, .unimplemented)
  156. }
  157. }
  158. }
  159. }
  160. func testUnimplementedMethod_ServerStreaming() async throws {
  161. try await self.withInProcessConnectedClient(services: [BinaryEcho()]) { client, _ in
  162. try await client.serverStreaming(
  163. request: .init(message: [3, 1, 4, 1, 5]),
  164. descriptor: MethodDescriptor(service: "not", method: "implemented"),
  165. serializer: IdentitySerializer(),
  166. deserializer: IdentityDeserializer(),
  167. options: .defaults
  168. ) { response in
  169. XCTAssertThrowsRPCError(try response.accepted.get()) { error in
  170. XCTAssertEqual(error.code, .unimplemented)
  171. }
  172. }
  173. }
  174. }
  175. func testUnimplementedMethod_BidirectionalStreaming() async throws {
  176. try await self.withInProcessConnectedClient(services: [BinaryEcho()]) { client, _ in
  177. try await client.bidirectionalStreaming(
  178. request: .init(producer: { writer in
  179. for byte in [3, 1, 4, 1, 5] as [UInt8] {
  180. try await writer.write([byte])
  181. }
  182. }),
  183. descriptor: MethodDescriptor(service: "not", method: "implemented"),
  184. serializer: IdentitySerializer(),
  185. deserializer: IdentityDeserializer(),
  186. options: .defaults
  187. ) { response in
  188. XCTAssertThrowsRPCError(try response.accepted.get()) { error in
  189. XCTAssertEqual(error.code, .unimplemented)
  190. }
  191. }
  192. }
  193. }
  194. func testMultipleConcurrentRequests() async throws {
  195. try await self.withInProcessConnectedClient(services: [BinaryEcho()]) { client, _ in
  196. await withThrowingTaskGroup(of: Void.self) { group in
  197. for i in UInt8.min ..< UInt8.max {
  198. group.addTask {
  199. try await client.unary(
  200. request: .init(message: [i]),
  201. descriptor: BinaryEcho.Methods.collect,
  202. serializer: IdentitySerializer(),
  203. deserializer: IdentityDeserializer(),
  204. options: .defaults
  205. ) { response in
  206. let message = try response.message
  207. XCTAssertEqual(message, [i])
  208. }
  209. }
  210. }
  211. }
  212. }
  213. }
  214. func testInterceptorsAreAppliedInOrder() async throws {
  215. let counter1 = ManagedAtomic(0)
  216. let counter2 = ManagedAtomic(0)
  217. try await self.withInProcessConnectedClient(
  218. services: [BinaryEcho()],
  219. interceptors: [
  220. .requestCounter(counter1),
  221. .rejectAll(with: RPCError(code: .unavailable, message: "")),
  222. .requestCounter(counter2),
  223. ]
  224. ) { client, _ in
  225. try await client.unary(
  226. request: .init(message: [3, 1, 4, 1, 5]),
  227. descriptor: BinaryEcho.Methods.collect,
  228. serializer: IdentitySerializer(),
  229. deserializer: IdentityDeserializer(),
  230. options: .defaults
  231. ) { response in
  232. XCTAssertRejected(response) { error in
  233. XCTAssertEqual(error.code, .unavailable)
  234. }
  235. }
  236. }
  237. XCTAssertEqual(counter1.load(ordering: .sequentiallyConsistent), 1)
  238. XCTAssertEqual(counter2.load(ordering: .sequentiallyConsistent), 0)
  239. }
  240. func testNoNewRPCsAfterClientClose() async throws {
  241. try await withInProcessConnectedClient(services: [BinaryEcho()]) { client, _ in
  242. // Run an RPC so we know the client is running properly.
  243. try await client.unary(
  244. request: .init(message: [3, 1, 4, 1, 5]),
  245. descriptor: BinaryEcho.Methods.collect,
  246. serializer: IdentitySerializer(),
  247. deserializer: IdentityDeserializer(),
  248. options: .defaults
  249. ) { response in
  250. let message = try response.message
  251. XCTAssertEqual(message, [3, 1, 4, 1, 5])
  252. }
  253. // New RPCs should fail immediately after this.
  254. client.close()
  255. // RPC should fail now.
  256. await XCTAssertThrowsErrorAsync(ofType: RuntimeError.self) {
  257. try await client.unary(
  258. request: .init(message: [3, 1, 4, 1, 5]),
  259. descriptor: BinaryEcho.Methods.collect,
  260. serializer: IdentitySerializer(),
  261. deserializer: IdentityDeserializer(),
  262. options: .defaults
  263. ) { _ in }
  264. } errorHandler: { error in
  265. XCTAssertEqual(error.code, .clientIsStopped)
  266. }
  267. }
  268. }
  269. func testInFlightRPCsCanContinueAfterClientIsClosed() async throws {
  270. try await withInProcessConnectedClient(services: [BinaryEcho()]) { client, server in
  271. try await client.clientStreaming(
  272. request: .init(producer: { writer in
  273. // Close the client once this RCP has been started.
  274. client.close()
  275. // Attempts to start a new RPC should fail.
  276. await XCTAssertThrowsErrorAsync(ofType: RuntimeError.self) {
  277. try await client.unary(
  278. request: .init(message: [3, 1, 4, 1, 5]),
  279. descriptor: BinaryEcho.Methods.collect,
  280. serializer: IdentitySerializer(),
  281. deserializer: IdentityDeserializer(),
  282. options: .defaults
  283. ) { _ in }
  284. } errorHandler: { error in
  285. XCTAssertEqual(error.code, .clientIsStopped)
  286. }
  287. // Now write to the already opened stream to confirm that opened streams
  288. // can successfully run to completion.
  289. for byte in [3, 1, 4, 1, 5] as [UInt8] {
  290. try await writer.write([byte])
  291. }
  292. }),
  293. descriptor: BinaryEcho.Methods.collect,
  294. serializer: IdentitySerializer(),
  295. deserializer: IdentityDeserializer(),
  296. options: .defaults
  297. ) { response in
  298. let message = try response.message
  299. XCTAssertEqual(message, [3, 1, 4, 1, 5])
  300. }
  301. }
  302. }
  303. func testCancelRunningClient() async throws {
  304. let inProcess = InProcessTransport.makePair()
  305. let client = GRPCClient(transport: inProcess.client)
  306. try await withThrowingTaskGroup(of: Void.self) { group in
  307. group.addTask {
  308. let server = GRPCServer(transport: inProcess.server, services: [BinaryEcho()])
  309. try await server.run()
  310. }
  311. group.addTask {
  312. try await client.run()
  313. }
  314. // Wait for client and server to be running.
  315. try await Task.sleep(for: .milliseconds(10))
  316. let task = Task {
  317. try await client.clientStreaming(
  318. request: .init(producer: { writer in
  319. try await Task.sleep(for: .seconds(5))
  320. }),
  321. descriptor: BinaryEcho.Methods.collect,
  322. serializer: IdentitySerializer(),
  323. deserializer: IdentityDeserializer(),
  324. options: .defaults
  325. ) { response in
  326. XCTAssertRejected(response) { error in
  327. XCTAssertEqual(error.code, .unknown)
  328. }
  329. }
  330. }
  331. // Check requests are getting through.
  332. try await client.unary(
  333. request: .init(message: [3, 1, 4, 1, 5]),
  334. descriptor: BinaryEcho.Methods.collect,
  335. serializer: IdentitySerializer(),
  336. deserializer: IdentityDeserializer(),
  337. options: .defaults
  338. ) { response in
  339. let message = try response.message
  340. XCTAssertEqual(message, [3, 1, 4, 1, 5])
  341. }
  342. task.cancel()
  343. try await task.value
  344. group.cancelAll()
  345. }
  346. }
  347. func testRunStoppedClient() async throws {
  348. let (_, clientTransport) = InProcessTransport.makePair()
  349. let client = GRPCClient(transport: clientTransport)
  350. // Run the client.
  351. let task = Task { try await client.run() }
  352. task.cancel()
  353. try await task.value
  354. // Client is stopped, should throw an error.
  355. await XCTAssertThrowsErrorAsync(ofType: RuntimeError.self) {
  356. try await client.run()
  357. } errorHandler: { error in
  358. XCTAssertEqual(error.code, .clientIsStopped)
  359. }
  360. }
  361. func testRunAlreadyRunningClient() async throws {
  362. let (_, clientTransport) = InProcessTransport.makePair()
  363. let client = GRPCClient(transport: clientTransport)
  364. // Run the client.
  365. let task = Task { try await client.run() }
  366. // Make sure the client is run for the first time here.
  367. try await Task.sleep(for: .milliseconds(10))
  368. // Client is already running, should throw an error.
  369. await XCTAssertThrowsErrorAsync(ofType: RuntimeError.self) {
  370. try await client.run()
  371. } errorHandler: { error in
  372. XCTAssertEqual(error.code, .clientIsAlreadyRunning)
  373. }
  374. task.cancel()
  375. }
  376. }