SubchannelTests.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /*
  2. * Copyright 2024, 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. @_spi(Package) @testable import GRPCHTTP2Core
  18. import NIOCore
  19. import NIOHTTP2
  20. import NIOPosix
  21. import XCTest
  22. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  23. final class SubchannelTests: XCTestCase {
  24. func testMakeStreamOnIdleSubchannel() async throws {
  25. let subchannel = self.makeSubchannel(
  26. address: .unixDomainSocket(path: "ignored"),
  27. connector: .never
  28. )
  29. await XCTAssertThrowsErrorAsync(ofType: RPCError.self) {
  30. try await subchannel.makeStream(descriptor: .echoGet, options: .defaults)
  31. } errorHandler: { error in
  32. XCTAssertEqual(error.code, .unavailable)
  33. }
  34. subchannel.close()
  35. }
  36. func testMakeStreamOnShutdownSubchannel() async throws {
  37. let subchannel = self.makeSubchannel(
  38. address: .unixDomainSocket(path: "ignored"),
  39. connector: .never
  40. )
  41. subchannel.close()
  42. await subchannel.run()
  43. await XCTAssertThrowsErrorAsync(ofType: RPCError.self) {
  44. try await subchannel.makeStream(descriptor: .echoGet, options: .defaults)
  45. } errorHandler: { error in
  46. XCTAssertEqual(error.code, .unavailable)
  47. }
  48. }
  49. func testMakeStreamOnReadySubchannel() async throws {
  50. let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
  51. let address = try await server.bind()
  52. let subchannel = self.makeSubchannel(address: address, connector: .posix())
  53. try await withThrowingTaskGroup(of: Void.self) { group in
  54. group.addTask {
  55. try await server.run { inbound, outbound in
  56. for try await part in inbound {
  57. switch part {
  58. case .metadata:
  59. try await outbound.write(.metadata([:]))
  60. case .message(let message):
  61. try await outbound.write(.message(message))
  62. }
  63. }
  64. try await outbound.write(.status(Status(code: .ok, message: ""), [:]))
  65. }
  66. }
  67. group.addTask {
  68. await subchannel.run()
  69. }
  70. subchannel.connect()
  71. for await event in subchannel.events {
  72. switch event {
  73. case .connectivityStateChanged(.ready):
  74. let stream = try await subchannel.makeStream(descriptor: .echoGet, options: .defaults)
  75. try await stream.execute { inbound, outbound in
  76. try await outbound.write(.metadata([:]))
  77. try await outbound.write(.message([0, 1, 2]))
  78. outbound.finish()
  79. for try await part in inbound {
  80. switch part {
  81. case .metadata:
  82. () // Don't validate, contains http/2 specific metadata too.
  83. case .message(let message):
  84. XCTAssertEqual(message, [0, 1, 2])
  85. case .status(let status, _):
  86. XCTAssertEqual(status.code, .ok)
  87. XCTAssertEqual(status.message, "")
  88. }
  89. }
  90. }
  91. subchannel.close()
  92. default:
  93. ()
  94. }
  95. }
  96. group.cancelAll()
  97. }
  98. }
  99. func testConnectEventuallySucceeds() async throws {
  100. let path = "test-connect-eventually-succeeds"
  101. let subchannel = self.makeSubchannel(
  102. address: .unixDomainSocket(path: path),
  103. connector: .posix(),
  104. backoff: .fixed(at: .milliseconds(100))
  105. )
  106. await withThrowingTaskGroup(of: Void.self) { group in
  107. group.addTask { await subchannel.run() }
  108. var hasServer = false
  109. var events = [Subchannel.Event]()
  110. for await event in subchannel.events {
  111. events.append(event)
  112. switch event {
  113. case .connectivityStateChanged(.idle):
  114. subchannel.connect()
  115. case .connectivityStateChanged(.transientFailure):
  116. // Don't start more than one server.
  117. if hasServer { continue }
  118. hasServer = true
  119. group.addTask {
  120. let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
  121. _ = try await server.bind(to: .uds(path))
  122. try await server.run { _, _ in
  123. XCTFail("Unexpected stream")
  124. }
  125. }
  126. case .connectivityStateChanged(.ready):
  127. subchannel.close()
  128. case .connectivityStateChanged(.shutdown):
  129. group.cancelAll()
  130. default:
  131. ()
  132. }
  133. }
  134. // First four events are known:
  135. XCTAssertEqual(
  136. Array(events.prefix(4)),
  137. [
  138. .connectivityStateChanged(.idle),
  139. .connectivityStateChanged(.connecting),
  140. .connectivityStateChanged(.transientFailure),
  141. .connectivityStateChanged(.connecting),
  142. ]
  143. )
  144. // Because there is backoff timing involved, the subchannel may flip from transient failure
  145. // to connecting multiple times. Just check that it eventually becomes ready and is then
  146. // shutdown.
  147. XCTAssertEqual(
  148. Array(events.suffix(2)),
  149. [
  150. .connectivityStateChanged(.ready),
  151. .connectivityStateChanged(.shutdown),
  152. ]
  153. )
  154. }
  155. }
  156. func testConnectIteratesThroughAddresses() async throws {
  157. let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
  158. let address = try await server.bind()
  159. let subchannel = self.makeSubchannel(
  160. addresses: [
  161. .unixDomainSocket(path: "not-listening-1"),
  162. .unixDomainSocket(path: "not-listening-2"),
  163. address,
  164. ],
  165. connector: .posix()
  166. )
  167. await withThrowingTaskGroup(of: Void.self) { group in
  168. group.addTask {
  169. try await server.run { _, _ in
  170. XCTFail("Unexpected stream")
  171. }
  172. }
  173. group.addTask {
  174. await subchannel.run()
  175. }
  176. for await event in subchannel.events {
  177. switch event {
  178. case .connectivityStateChanged(.idle):
  179. subchannel.connect()
  180. case .connectivityStateChanged(.ready):
  181. subchannel.close()
  182. case .connectivityStateChanged(.shutdown):
  183. group.cancelAll()
  184. default:
  185. ()
  186. }
  187. }
  188. }
  189. }
  190. func testConnectIteratesThroughAddressesWithBackoff() async throws {
  191. let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
  192. let udsPath = "test-wrap-around-addrs"
  193. let subchannel = self.makeSubchannel(
  194. addresses: [
  195. .unixDomainSocket(path: "not-listening-1"),
  196. .unixDomainSocket(path: "not-listening-2"),
  197. .unixDomainSocket(path: udsPath),
  198. ],
  199. connector: .posix(),
  200. backoff: .fixed(at: .zero) // Skip the backoff period
  201. )
  202. try await withThrowingTaskGroup(of: Void.self) { group in
  203. group.addTask {
  204. await subchannel.run()
  205. }
  206. var isServerRunning = false
  207. for await event in subchannel.events {
  208. switch event {
  209. case .connectivityStateChanged(.idle):
  210. subchannel.connect()
  211. case .connectivityStateChanged(.transientFailure):
  212. // The subchannel enters the transient failure state when all addresses have been tried.
  213. // Bind the server now so that the next attempts succeeds.
  214. if isServerRunning { break }
  215. isServerRunning = true
  216. let address = try await server.bind(to: .uds(udsPath))
  217. XCTAssertEqual(address, .unixDomainSocket(path: udsPath))
  218. group.addTask {
  219. try await server.run { _, _ in
  220. XCTFail("Unexpected stream")
  221. }
  222. }
  223. case .connectivityStateChanged(.ready):
  224. subchannel.close()
  225. case .connectivityStateChanged(.shutdown):
  226. group.cancelAll()
  227. default:
  228. ()
  229. }
  230. }
  231. }
  232. }
  233. func testConnectedReceivesGoAway() async throws {
  234. let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
  235. let address = try await server.bind()
  236. let subchannel = self.makeSubchannel(address: address, connector: .posix())
  237. try await withThrowingTaskGroup(of: Void.self) { group in
  238. group.addTask {
  239. try await server.run { _, _ in
  240. XCTFail("Unexpected stream")
  241. }
  242. }
  243. group.addTask {
  244. await subchannel.run()
  245. }
  246. var events = [Subchannel.Event]()
  247. for await event in subchannel.events {
  248. events.append(event)
  249. switch event {
  250. case .connectivityStateChanged(.idle):
  251. subchannel.connect()
  252. case .connectivityStateChanged(.ready):
  253. // Now the subchannel is ready, send a GOAWAY from the server.
  254. let channel = try XCTUnwrap(server.clients.first)
  255. let goAway = HTTP2Frame(
  256. streamID: .rootStream,
  257. payload: .goAway(lastStreamID: 0, errorCode: .cancel, opaqueData: nil)
  258. )
  259. try await channel.writeAndFlush(goAway)
  260. case .connectivityStateChanged(.shutdown):
  261. group.cancelAll()
  262. default:
  263. ()
  264. }
  265. }
  266. let expectedEvents: [Subchannel.Event] = [
  267. // Normal connect flow.
  268. .connectivityStateChanged(.idle),
  269. .connectivityStateChanged(.connecting),
  270. .connectivityStateChanged(.ready),
  271. // GOAWAY triggers name resolution too.
  272. .goingAway,
  273. .requiresNameResolution,
  274. // Finally, shutdown.
  275. .connectivityStateChanged(.shutdown),
  276. ]
  277. XCTAssertEqual(expectedEvents, events)
  278. }
  279. }
  280. func testCancelReadySubchannel() async throws {
  281. let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
  282. let address = try await server.bind()
  283. let subchannel = self.makeSubchannel(address: address, connector: .posix())
  284. await withThrowingTaskGroup(of: Void.self) { group in
  285. group.addTask {
  286. try await server.run { _, _ in
  287. XCTFail("Unexpected stream")
  288. }
  289. }
  290. group.addTask {
  291. subchannel.connect()
  292. await subchannel.run()
  293. }
  294. for await event in subchannel.events {
  295. switch event {
  296. case .connectivityStateChanged(.ready):
  297. group.cancelAll()
  298. default:
  299. ()
  300. }
  301. }
  302. }
  303. }
  304. private func makeSubchannel(
  305. addresses: [GRPCHTTP2Core.SocketAddress],
  306. connector: any HTTP2Connector,
  307. backoff: ConnectionBackoff? = nil
  308. ) -> Subchannel {
  309. return Subchannel(
  310. endpoint: Endpoint(addresses: addresses),
  311. id: SubchannelID(),
  312. connector: connector,
  313. backoff: backoff ?? .defaults,
  314. defaultCompression: .none,
  315. enabledCompression: .none
  316. )
  317. }
  318. private func makeSubchannel(
  319. address: GRPCHTTP2Core.SocketAddress,
  320. connector: any HTTP2Connector,
  321. backoff: ConnectionBackoff? = nil
  322. ) -> Subchannel {
  323. self.makeSubchannel(addresses: [address], connector: connector, backoff: backoff)
  324. }
  325. }
  326. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  327. extension ConnectionBackoff {
  328. static func fixed(at interval: Duration, jitter: Double = 0.0) -> Self {
  329. return Self(initial: interval, max: interval, multiplier: 1.0, jitter: jitter)
  330. }
  331. static var defaults: Self {
  332. ConnectionBackoff(initial: .seconds(10), max: .seconds(120), multiplier: 1.6, jitter: 1.2)
  333. }
  334. }