InProcessClientTransportTests.swift 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /*
  2. * Copyright 2023-2025, 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(gRPCSwift 2.0, *)
  20. final class InProcessClientTransportTests: XCTestCase {
  21. struct FailTest: Error {}
  22. func testConnectWhenConnected() async {
  23. let client = makeClient()
  24. await withThrowingTaskGroup(of: Void.self) { group in
  25. group.addTask {
  26. try await client.connect()
  27. }
  28. group.addTask {
  29. try await client.connect()
  30. }
  31. await XCTAssertThrowsErrorAsync(ofType: RPCError.self) {
  32. try await group.next()
  33. } errorHandler: { error in
  34. XCTAssertEqual(error.code, .failedPrecondition)
  35. }
  36. group.cancelAll()
  37. }
  38. }
  39. func testConnectWhenClosed() async {
  40. let client = makeClient()
  41. client.beginGracefulShutdown()
  42. await XCTAssertThrowsErrorAsync(ofType: RPCError.self) {
  43. try await client.connect()
  44. } errorHandler: { error in
  45. XCTAssertEqual(error.code, .failedPrecondition)
  46. }
  47. }
  48. func testConnectWhenClosedAfterCancellation() async throws {
  49. let client = makeClient()
  50. try await withThrowingTaskGroup(of: Void.self) { group in
  51. group.addTask {
  52. try await client.connect()
  53. }
  54. group.addTask {
  55. try await Task.sleep(for: .milliseconds(100), tolerance: .zero)
  56. }
  57. try await group.next()
  58. group.cancelAll()
  59. await XCTAssertThrowsErrorAsync(ofType: RPCError.self) {
  60. try await client.connect()
  61. } errorHandler: { error in
  62. XCTAssertEqual(error.code, .failedPrecondition)
  63. }
  64. }
  65. }
  66. func testCloseWhenUnconnected() {
  67. let client = makeClient()
  68. XCTAssertNoThrow(client.beginGracefulShutdown())
  69. }
  70. func testCloseWhenClosed() {
  71. let client = makeClient()
  72. client.beginGracefulShutdown()
  73. XCTAssertNoThrow(client.beginGracefulShutdown())
  74. }
  75. func testConnectSuccessfullyAndThenClose() async throws {
  76. let client = makeClient()
  77. try await withThrowingTaskGroup(of: Void.self) { group in
  78. group.addTask {
  79. try await client.connect()
  80. }
  81. group.addTask {
  82. try await Task.sleep(for: .milliseconds(100), tolerance: .zero)
  83. }
  84. try await group.next()
  85. client.beginGracefulShutdown()
  86. }
  87. }
  88. func testOpenStreamWhenUnconnected() async throws {
  89. let client = makeClient()
  90. try await withThrowingTaskGroup(of: Void.self) { group in
  91. group.addTask {
  92. try await client.withStream(descriptor: .testTest, options: .defaults) { _, _ in
  93. // Once the pending stream is opened, close the client to new connections,
  94. // so that, once this closure is executed and this stream is closed,
  95. // the client will return from `connect()`.
  96. client.beginGracefulShutdown()
  97. }
  98. }
  99. group.addTask {
  100. // Add a sleep to make sure connection happens after `withStream` has been called,
  101. // to test pending streams are handled correctly.
  102. try await Task.sleep(for: .milliseconds(100), tolerance: .zero)
  103. try await client.connect()
  104. }
  105. try await group.waitForAll()
  106. }
  107. }
  108. func testOpenStreamWhenClosed() async {
  109. let client = makeClient()
  110. client.beginGracefulShutdown()
  111. await XCTAssertThrowsErrorAsync(ofType: RPCError.self) {
  112. try await client.withStream(descriptor: .testTest, options: .defaults) { _, _ in }
  113. } errorHandler: { error in
  114. XCTAssertEqual(error.code, .failedPrecondition)
  115. }
  116. }
  117. func testOpenStreamSuccessfullyAndThenClose() async throws {
  118. let server = InProcessTransport.Server(peer: "in-process:1234")
  119. let client = makeClient(server: server)
  120. try await withThrowingTaskGroup(of: Void.self) { group in
  121. group.addTask {
  122. try await client.connect()
  123. }
  124. group.addTask {
  125. try await client.withStream(descriptor: .testTest, options: .defaults) { stream, _ in
  126. try await stream.outbound.write(.message([1]))
  127. await stream.outbound.finish()
  128. let receivedMessages = try await stream.inbound.reduce(into: []) { $0.append($1) }
  129. XCTAssertEqual(receivedMessages, [.message([42])])
  130. }
  131. }
  132. group.addTask {
  133. try await server.listen { stream, context in
  134. let receivedMessages = try? await stream.inbound.reduce(into: []) { $0.append($1) }
  135. try? await stream.outbound.write(RPCResponsePart.message([42]))
  136. await stream.outbound.finish()
  137. XCTAssertEqual(receivedMessages, [.message([1])])
  138. }
  139. }
  140. group.addTask {
  141. try await Task.sleep(for: .milliseconds(100), tolerance: .zero)
  142. client.beginGracefulShutdown()
  143. }
  144. try await group.next()
  145. group.cancelAll()
  146. }
  147. }
  148. func testExecutionConfiguration() {
  149. let policy = HedgingPolicy(
  150. maxAttempts: 10,
  151. hedgingDelay: .seconds(1),
  152. nonFatalStatusCodes: []
  153. )
  154. var serviceConfig = ServiceConfig(
  155. methodConfig: [
  156. MethodConfig(
  157. names: [
  158. MethodConfig.Name(service: "", method: "")
  159. ],
  160. executionPolicy: .hedge(policy)
  161. )
  162. ]
  163. )
  164. let peer = "in-process:1234"
  165. var client = InProcessTransport.Client(
  166. server: InProcessTransport.Server(peer: peer),
  167. serviceConfig: serviceConfig,
  168. peer: peer
  169. )
  170. let firstDescriptor = MethodDescriptor(fullyQualifiedService: "test", method: "first")
  171. XCTAssertEqual(
  172. client.config(forMethod: firstDescriptor),
  173. serviceConfig.methodConfig.first
  174. )
  175. let retryPolicy = RetryPolicy(
  176. maxAttempts: 10,
  177. initialBackoff: .seconds(1),
  178. maxBackoff: .seconds(1),
  179. backoffMultiplier: 1.0,
  180. retryableStatusCodes: [.unavailable]
  181. )
  182. let overrideConfiguration = MethodConfig(
  183. names: [MethodConfig.Name(service: "test", method: "second")],
  184. executionPolicy: .retry(retryPolicy)
  185. )
  186. serviceConfig.methodConfig.append(overrideConfiguration)
  187. client = InProcessTransport.Client(
  188. server: InProcessTransport.Server(peer: peer),
  189. serviceConfig: serviceConfig,
  190. peer: peer
  191. )
  192. let secondDescriptor = MethodDescriptor(fullyQualifiedService: "test", method: "second")
  193. XCTAssertEqual(
  194. client.config(forMethod: firstDescriptor),
  195. serviceConfig.methodConfig.first
  196. )
  197. XCTAssertEqual(
  198. client.config(forMethod: secondDescriptor),
  199. serviceConfig.methodConfig.last
  200. )
  201. }
  202. func testOpenMultipleStreamsThenClose() async throws {
  203. let server = InProcessTransport.Server(peer: "in-process:1234")
  204. let client = makeClient(server: server)
  205. try await withThrowingTaskGroup(of: Void.self) { group in
  206. group.addTask {
  207. try await client.connect()
  208. }
  209. group.addTask {
  210. try await client.withStream(descriptor: .testTest, options: .defaults) { stream, _ in
  211. try await Task.sleep(for: .milliseconds(100), tolerance: .zero)
  212. }
  213. }
  214. group.addTask {
  215. try await client.withStream(descriptor: .testTest, options: .defaults) { stream, _ in
  216. try await Task.sleep(for: .milliseconds(100), tolerance: .zero)
  217. }
  218. }
  219. group.addTask {
  220. try await Task.sleep(for: .milliseconds(50), tolerance: .zero)
  221. client.beginGracefulShutdown()
  222. }
  223. try await group.next()
  224. }
  225. }
  226. @available(gRPCSwift 2.0, *)
  227. func makeClient(
  228. server: InProcessTransport.Server = InProcessTransport.Server(peer: "in-process:1234")
  229. ) -> InProcessTransport.Client {
  230. let defaultPolicy = RetryPolicy(
  231. maxAttempts: 10,
  232. initialBackoff: .seconds(1),
  233. maxBackoff: .seconds(1),
  234. backoffMultiplier: 1.0,
  235. retryableStatusCodes: [.unavailable]
  236. )
  237. let serviceConfig = ServiceConfig(
  238. methodConfig: [
  239. MethodConfig(
  240. names: [MethodConfig.Name(service: "", method: "")],
  241. executionPolicy: .retry(defaultPolicy)
  242. )
  243. ]
  244. )
  245. return InProcessTransport.Client(
  246. server: server,
  247. serviceConfig: serviceConfig,
  248. peer: server.peer
  249. )
  250. }
  251. }
  252. @available(gRPCSwift 2.0, *)
  253. extension MethodDescriptor {
  254. static let testTest = Self(fullyQualifiedService: "test", method: "test")
  255. }