InProcessClientTransportTests.swift 8.4 KB

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