SubchannelTests.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. 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.shutDown()
  35. }
  36. func testMakeStreamOnShutdownSubchannel() async throws {
  37. let subchannel = self.makeSubchannel(
  38. address: .unixDomainSocket(path: "ignored"),
  39. connector: .never
  40. )
  41. subchannel.shutDown()
  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.shutDown()
  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(10))
  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.shutDown()
  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.shutDown()
  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.shutDown()
  225. case .connectivityStateChanged(.shutdown):
  226. group.cancelAll()
  227. default:
  228. ()
  229. }
  230. }
  231. }
  232. }
  233. func testIdleTimeout() async throws {
  234. let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
  235. let address = try await server.bind()
  236. let subchannel = self.makeSubchannel(
  237. address: address,
  238. connector: .posix(maxIdleTime: .milliseconds(1)) // Aggressively idle
  239. )
  240. await withThrowingTaskGroup(of: Void.self) { group in
  241. group.addTask {
  242. await subchannel.run()
  243. }
  244. group.addTask {
  245. try await server.run { _, _ in
  246. XCTFail("Unexpected stream")
  247. }
  248. }
  249. var idleCount = 0
  250. var events = [Subchannel.Event]()
  251. for await event in subchannel.events {
  252. events.append(event)
  253. switch event {
  254. case .connectivityStateChanged(.idle):
  255. idleCount += 1
  256. if idleCount == 1 {
  257. subchannel.connect()
  258. } else {
  259. subchannel.shutDown()
  260. }
  261. case .connectivityStateChanged(.shutdown):
  262. group.cancelAll()
  263. default:
  264. ()
  265. }
  266. }
  267. let expected: [Subchannel.Event] = [
  268. .connectivityStateChanged(.idle),
  269. .connectivityStateChanged(.connecting),
  270. .connectivityStateChanged(.ready),
  271. .connectivityStateChanged(.idle),
  272. .connectivityStateChanged(.shutdown),
  273. ]
  274. XCTAssertEqual(events, expected)
  275. }
  276. }
  277. func testConnectionDropWhenIdle() async throws {
  278. let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
  279. let address = try await server.bind()
  280. let subchannel = self.makeSubchannel(address: address, connector: .posix())
  281. await withThrowingTaskGroup(of: Void.self) { group in
  282. group.addTask {
  283. await subchannel.run()
  284. }
  285. group.addTask {
  286. try await server.run { _, _ in
  287. XCTFail("Unexpected RPC")
  288. }
  289. }
  290. var events = [Subchannel.Event]()
  291. var idleCount = 0
  292. for await event in subchannel.events {
  293. events.append(event)
  294. switch event {
  295. case .connectivityStateChanged(.idle):
  296. idleCount += 1
  297. switch idleCount {
  298. case 1:
  299. subchannel.connect()
  300. case 2:
  301. subchannel.shutDown()
  302. default:
  303. XCTFail("Unexpected idle")
  304. }
  305. case .connectivityStateChanged(.ready):
  306. // Close the connection without a GOAWAY.
  307. server.clients.first?.close(mode: .all, promise: nil)
  308. case .connectivityStateChanged(.shutdown):
  309. group.cancelAll()
  310. default:
  311. ()
  312. }
  313. }
  314. let expected: [Subchannel.Event] = [
  315. .connectivityStateChanged(.idle),
  316. .connectivityStateChanged(.connecting),
  317. .connectivityStateChanged(.ready),
  318. .connectivityStateChanged(.idle),
  319. .connectivityStateChanged(.shutdown),
  320. ]
  321. XCTAssertEqual(events, expected)
  322. }
  323. }
  324. func testConnectionDropWithOpenStreams() async throws {
  325. let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
  326. let address = try await server.bind()
  327. let subchannel = self.makeSubchannel(address: address, connector: .posix())
  328. try await withThrowingTaskGroup(of: Void.self) { group in
  329. group.addTask {
  330. await subchannel.run()
  331. }
  332. group.addTask {
  333. try await server.run(.echo)
  334. }
  335. var events = [Subchannel.Event]()
  336. var readyCount = 0
  337. for await event in subchannel.events {
  338. events.append(event)
  339. switch event {
  340. case .connectivityStateChanged(.idle):
  341. subchannel.connect()
  342. case .connectivityStateChanged(.ready):
  343. readyCount += 1
  344. // When the connection becomes ready the first time, open a stream and forcibly close the
  345. // channel. This will result in an automatic reconnect. Close the subchannel when that
  346. // happens.
  347. if readyCount == 1 {
  348. let stream = try await subchannel.makeStream(descriptor: .echoGet, options: .defaults)
  349. try await stream.execute { inbound, outbound in
  350. try await outbound.write(.metadata([:]))
  351. // Wait for the metadata to be echo'd back.
  352. var iterator = inbound.makeAsyncIterator()
  353. let _ = try await iterator.next()
  354. // Stream is definitely open. Bork the connection.
  355. server.clients.first?.close(mode: .all, promise: nil)
  356. // Wait for the next message which won't arrive, client won't send a message. The
  357. // stream should fail
  358. let _ = try await iterator.next()
  359. }
  360. } else if readyCount == 2 {
  361. subchannel.shutDown()
  362. }
  363. case .connectivityStateChanged(.shutdown):
  364. group.cancelAll()
  365. default:
  366. ()
  367. }
  368. }
  369. let expected: [Subchannel.Event] = [
  370. .connectivityStateChanged(.idle),
  371. .connectivityStateChanged(.connecting),
  372. .connectivityStateChanged(.ready),
  373. .connectivityStateChanged(.transientFailure),
  374. .requiresNameResolution,
  375. .connectivityStateChanged(.connecting),
  376. .connectivityStateChanged(.ready),
  377. .connectivityStateChanged(.shutdown),
  378. ]
  379. XCTAssertEqual(events, expected)
  380. }
  381. }
  382. func testConnectedReceivesGoAway() async throws {
  383. let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
  384. let address = try await server.bind()
  385. let subchannel = self.makeSubchannel(address: address, connector: .posix())
  386. try await withThrowingTaskGroup(of: Void.self) { group in
  387. group.addTask {
  388. try await server.run { _, _ in
  389. XCTFail("Unexpected stream")
  390. }
  391. }
  392. group.addTask {
  393. await subchannel.run()
  394. }
  395. var events = [Subchannel.Event]()
  396. var idleCount = 0
  397. for await event in subchannel.events {
  398. events.append(event)
  399. switch event {
  400. case .connectivityStateChanged(.idle):
  401. idleCount += 1
  402. if idleCount == 1 {
  403. subchannel.connect()
  404. } else if idleCount == 2 {
  405. subchannel.shutDown()
  406. }
  407. case .connectivityStateChanged(.ready):
  408. // Now the subchannel is ready, send a GOAWAY from the server.
  409. let channel = try XCTUnwrap(server.clients.first)
  410. let goAway = HTTP2Frame(
  411. streamID: .rootStream,
  412. payload: .goAway(lastStreamID: 0, errorCode: .cancel, opaqueData: nil)
  413. )
  414. try await channel.writeAndFlush(goAway)
  415. case .connectivityStateChanged(.shutdown):
  416. group.cancelAll()
  417. default:
  418. ()
  419. }
  420. }
  421. let expectedEvents: [Subchannel.Event] = [
  422. // Normal connect flow.
  423. .connectivityStateChanged(.idle),
  424. .connectivityStateChanged(.connecting),
  425. .connectivityStateChanged(.ready),
  426. // GOAWAY triggers name resolution and idling.
  427. .goingAway,
  428. .requiresNameResolution,
  429. .connectivityStateChanged(.idle),
  430. // The second idle triggers a close.
  431. .connectivityStateChanged(.shutdown),
  432. ]
  433. XCTAssertEqual(expectedEvents, events)
  434. }
  435. }
  436. func testCancelReadySubchannel() async throws {
  437. let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
  438. let address = try await server.bind()
  439. let subchannel = self.makeSubchannel(address: address, connector: .posix())
  440. await withThrowingTaskGroup(of: Void.self) { group in
  441. group.addTask {
  442. try await server.run { _, _ in
  443. XCTFail("Unexpected stream")
  444. }
  445. }
  446. group.addTask {
  447. subchannel.connect()
  448. await subchannel.run()
  449. }
  450. for await event in subchannel.events {
  451. switch event {
  452. case .connectivityStateChanged(.ready):
  453. group.cancelAll()
  454. default:
  455. ()
  456. }
  457. }
  458. }
  459. }
  460. private func makeSubchannel(
  461. addresses: [GRPCHTTP2Core.SocketAddress],
  462. connector: any HTTP2Connector,
  463. backoff: ConnectionBackoff? = nil
  464. ) -> Subchannel {
  465. return Subchannel(
  466. endpoint: Endpoint(addresses: addresses),
  467. id: SubchannelID(),
  468. connector: connector,
  469. backoff: backoff ?? .defaults,
  470. defaultCompression: .none,
  471. enabledCompression: .none
  472. )
  473. }
  474. private func makeSubchannel(
  475. address: GRPCHTTP2Core.SocketAddress,
  476. connector: any HTTP2Connector,
  477. backoff: ConnectionBackoff? = nil
  478. ) -> Subchannel {
  479. self.makeSubchannel(addresses: [address], connector: connector, backoff: backoff)
  480. }
  481. }
  482. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  483. extension ConnectionBackoff {
  484. static func fixed(at interval: Duration, jitter: Double = 0.0) -> Self {
  485. return Self(initial: interval, max: interval, multiplier: 1.0, jitter: jitter)
  486. }
  487. static var defaults: Self {
  488. ConnectionBackoff(initial: .seconds(10), max: .seconds(120), multiplier: 1.6, jitter: 1.2)
  489. }
  490. }