GRPCClientTests.swift 14 KB

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