InProcessClientTransportTests.swift 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. 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(
  92. descriptor: .init(service: "test", method: "test"),
  93. options: .defaults
  94. ) { _ in
  95. // Once the pending stream is opened, close the client to new connections,
  96. // so that, once this closure is executed and this stream is closed,
  97. // the client will return from `connect()`.
  98. client.beginGracefulShutdown()
  99. }
  100. }
  101. group.addTask {
  102. // Add a sleep to make sure connection happens after `withStream` has been called,
  103. // to test pending streams are handled correctly.
  104. try await Task.sleep(for: .milliseconds(100))
  105. try await client.connect()
  106. }
  107. try await group.waitForAll()
  108. }
  109. }
  110. func testOpenStreamWhenClosed() async {
  111. let client = makeClient()
  112. client.beginGracefulShutdown()
  113. await XCTAssertThrowsErrorAsync(ofType: RPCError.self) {
  114. try await client.withStream(
  115. descriptor: .init(service: "test", method: "test"),
  116. options: .defaults
  117. ) { _ in }
  118. } errorHandler: { error in
  119. XCTAssertEqual(error.code, .failedPrecondition)
  120. }
  121. }
  122. func testOpenStreamSuccessfullyAndThenClose() async throws {
  123. let server = InProcessTransport.Server()
  124. let client = makeClient(server: server)
  125. try await withThrowingTaskGroup(of: Void.self) { group in
  126. group.addTask {
  127. try await client.connect()
  128. }
  129. group.addTask {
  130. try await client.withStream(
  131. descriptor: .init(service: "test", method: "test"),
  132. options: .defaults
  133. ) { stream in
  134. try await stream.outbound.write(.message([1]))
  135. await stream.outbound.finish()
  136. let receivedMessages = try await stream.inbound.reduce(into: []) { $0.append($1) }
  137. XCTAssertEqual(receivedMessages, [.message([42])])
  138. }
  139. }
  140. group.addTask {
  141. try await server.listen { stream, context in
  142. let receivedMessages = try? await stream.inbound.reduce(into: []) { $0.append($1) }
  143. try? await stream.outbound.write(RPCResponsePart.message([42]))
  144. await stream.outbound.finish()
  145. XCTAssertEqual(receivedMessages, [.message([1])])
  146. }
  147. }
  148. group.addTask {
  149. try await Task.sleep(for: .milliseconds(100))
  150. client.beginGracefulShutdown()
  151. }
  152. try await group.next()
  153. group.cancelAll()
  154. }
  155. }
  156. func testExecutionConfiguration() {
  157. let policy = HedgingPolicy(
  158. maxAttempts: 10,
  159. hedgingDelay: .seconds(1),
  160. nonFatalStatusCodes: []
  161. )
  162. var serviceConfig = ServiceConfig(
  163. methodConfig: [
  164. MethodConfig(
  165. names: [
  166. MethodConfig.Name(service: "", method: "")
  167. ],
  168. executionPolicy: .hedge(policy)
  169. )
  170. ]
  171. )
  172. var client = InProcessTransport.Client(
  173. server: InProcessTransport.Server(),
  174. serviceConfig: serviceConfig
  175. )
  176. let firstDescriptor = MethodDescriptor(service: "test", method: "first")
  177. XCTAssertEqual(
  178. client.config(forMethod: firstDescriptor),
  179. serviceConfig.methodConfig.first
  180. )
  181. let retryPolicy = RetryPolicy(
  182. maxAttempts: 10,
  183. initialBackoff: .seconds(1),
  184. maxBackoff: .seconds(1),
  185. backoffMultiplier: 1.0,
  186. retryableStatusCodes: [.unavailable]
  187. )
  188. let overrideConfiguration = MethodConfig(
  189. names: [MethodConfig.Name(service: "test", method: "second")],
  190. executionPolicy: .retry(retryPolicy)
  191. )
  192. serviceConfig.methodConfig.append(overrideConfiguration)
  193. client = InProcessTransport.Client(
  194. server: InProcessTransport.Server(),
  195. serviceConfig: serviceConfig
  196. )
  197. let secondDescriptor = MethodDescriptor(service: "test", method: "second")
  198. XCTAssertEqual(
  199. client.config(forMethod: firstDescriptor),
  200. serviceConfig.methodConfig.first
  201. )
  202. XCTAssertEqual(
  203. client.config(forMethod: secondDescriptor),
  204. serviceConfig.methodConfig.last
  205. )
  206. }
  207. func testOpenMultipleStreamsThenClose() async throws {
  208. let server = InProcessTransport.Server()
  209. let client = makeClient(server: server)
  210. try await withThrowingTaskGroup(of: Void.self) { group in
  211. group.addTask {
  212. try await client.connect()
  213. }
  214. group.addTask {
  215. try await client.withStream(
  216. descriptor: .init(service: "test", method: "test"),
  217. options: .defaults
  218. ) { stream in
  219. try await Task.sleep(for: .milliseconds(100))
  220. }
  221. }
  222. group.addTask {
  223. try await client.withStream(
  224. descriptor: .init(service: "test", method: "test"),
  225. options: .defaults
  226. ) { stream in
  227. try await Task.sleep(for: .milliseconds(100))
  228. }
  229. }
  230. group.addTask {
  231. try await Task.sleep(for: .milliseconds(50))
  232. client.beginGracefulShutdown()
  233. }
  234. try await group.next()
  235. }
  236. }
  237. func makeClient(
  238. server: InProcessTransport.Server = InProcessTransport.Server()
  239. ) -> InProcessTransport.Client {
  240. let defaultPolicy = RetryPolicy(
  241. maxAttempts: 10,
  242. initialBackoff: .seconds(1),
  243. maxBackoff: .seconds(1),
  244. backoffMultiplier: 1.0,
  245. retryableStatusCodes: [.unavailable]
  246. )
  247. let serviceConfig = ServiceConfig(
  248. methodConfig: [
  249. MethodConfig(
  250. names: [MethodConfig.Name(service: "", method: "")],
  251. executionPolicy: .retry(defaultPolicy)
  252. )
  253. ]
  254. )
  255. return InProcessTransport.Client(
  256. server: server,
  257. serviceConfig: serviceConfig
  258. )
  259. }
  260. }