ConnectionManagerTests.swift 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423
  1. /*
  2. * Copyright 2020, 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 EchoModel
  17. @testable import GRPC
  18. import Logging
  19. import NIOCore
  20. import NIOEmbedded
  21. import NIOHTTP2
  22. import XCTest
  23. class ConnectionManagerTests: GRPCTestCase {
  24. private let loop = EmbeddedEventLoop()
  25. private let recorder = RecordingConnectivityDelegate()
  26. private var monitor: ConnectivityStateMonitor!
  27. private var defaultConfiguration: ClientConnection.Configuration {
  28. var configuration = ClientConnection.Configuration.default(
  29. target: .unixDomainSocket("/ignored"),
  30. eventLoopGroup: self.loop
  31. )
  32. configuration.connectionBackoff = nil
  33. configuration.backgroundActivityLogger = self.clientLogger
  34. return configuration
  35. }
  36. override func setUp() {
  37. super.setUp()
  38. self.monitor = ConnectivityStateMonitor(delegate: self.recorder, queue: nil)
  39. }
  40. override func tearDown() {
  41. XCTAssertNoThrow(try self.loop.syncShutdownGracefully())
  42. super.tearDown()
  43. }
  44. private func makeConnectionManager(
  45. configuration config: ClientConnection.Configuration? = nil,
  46. channelProvider: ((ConnectionManager, EventLoop) -> EventLoopFuture<Channel>)? = nil
  47. ) -> ConnectionManager {
  48. let configuration = config ?? self.defaultConfiguration
  49. return ConnectionManager(
  50. configuration: configuration,
  51. channelProvider: channelProvider.map { HookedChannelProvider($0) },
  52. connectivityDelegate: self.monitor,
  53. logger: self.logger
  54. )
  55. }
  56. private func waitForStateChange<Result>(
  57. from: ConnectivityState,
  58. to: ConnectivityState,
  59. timeout: DispatchTimeInterval = .seconds(1),
  60. file: StaticString = #filePath,
  61. line: UInt = #line,
  62. body: () throws -> Result
  63. ) rethrows -> Result {
  64. self.recorder.expectChange {
  65. XCTAssertEqual($0, Change(from: from, to: to), file: file, line: line)
  66. }
  67. let result = try body()
  68. self.recorder.waitForExpectedChanges(timeout: timeout, file: file, line: line)
  69. return result
  70. }
  71. private func waitForStateChanges<Result>(
  72. _ changes: [Change],
  73. timeout: DispatchTimeInterval = .seconds(1),
  74. file: StaticString = #filePath,
  75. line: UInt = #line,
  76. body: () throws -> Result
  77. ) rethrows -> Result {
  78. self.recorder.expectChanges(changes.count) {
  79. XCTAssertEqual($0, changes)
  80. }
  81. let result = try body()
  82. self.recorder.waitForExpectedChanges(timeout: timeout, file: file, line: line)
  83. return result
  84. }
  85. }
  86. extension ConnectionManagerTests {
  87. func testIdleShutdown() throws {
  88. let manager = self.makeConnectionManager()
  89. try self.waitForStateChange(from: .idle, to: .shutdown) {
  90. let shutdown = manager.shutdown()
  91. self.loop.run()
  92. XCTAssertNoThrow(try shutdown.wait())
  93. }
  94. // Getting a multiplexer should fail.
  95. let multiplexer = manager.getHTTP2Multiplexer()
  96. self.loop.run()
  97. XCTAssertThrowsError(try multiplexer.wait())
  98. }
  99. func testConnectFromIdleFailsWithNoReconnect() {
  100. let channelPromise = self.loop.makePromise(of: Channel.self)
  101. let manager = self.makeConnectionManager { _, _ in
  102. return channelPromise.futureResult
  103. }
  104. let multiplexer: EventLoopFuture<HTTP2StreamMultiplexer> = self
  105. .waitForStateChange(from: .idle, to: .connecting) {
  106. let channel = manager.getHTTP2Multiplexer()
  107. self.loop.run()
  108. return channel
  109. }
  110. self.waitForStateChange(from: .connecting, to: .shutdown) {
  111. channelPromise.fail(DoomedChannelError())
  112. }
  113. XCTAssertThrowsError(try multiplexer.wait()) {
  114. XCTAssertTrue($0 is DoomedChannelError)
  115. }
  116. }
  117. func testConnectAndDisconnect() throws {
  118. let channelPromise = self.loop.makePromise(of: Channel.self)
  119. let manager = self.makeConnectionManager { _, _ in
  120. return channelPromise.futureResult
  121. }
  122. // Start the connection.
  123. self.waitForStateChange(from: .idle, to: .connecting) {
  124. _ = manager.getHTTP2Multiplexer()
  125. self.loop.run()
  126. }
  127. // Setup the real channel and activate it.
  128. let channel = EmbeddedChannel(loop: self.loop)
  129. let h2mux = HTTP2StreamMultiplexer(
  130. mode: .client,
  131. channel: channel,
  132. inboundStreamInitializer: nil
  133. )
  134. try channel.pipeline.addHandler(
  135. GRPCIdleHandler(
  136. connectionManager: manager,
  137. multiplexer: h2mux,
  138. idleTimeout: .minutes(5),
  139. keepalive: .init(),
  140. logger: self.logger
  141. )
  142. ).wait()
  143. channelPromise.succeed(channel)
  144. XCTAssertNoThrow(
  145. try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  146. .wait()
  147. )
  148. // Write a settings frame on the root stream; this'll make the channel 'ready'.
  149. try self.waitForStateChange(from: .connecting, to: .ready) {
  150. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  151. XCTAssertNoThrow(try channel.writeInbound(frame))
  152. }
  153. // Close the channel.
  154. try self.waitForStateChange(from: .ready, to: .shutdown) {
  155. // Now the channel should be available: shut it down.
  156. let shutdown = manager.shutdown()
  157. self.loop.run()
  158. XCTAssertNoThrow(try shutdown.wait())
  159. }
  160. }
  161. func testConnectAndIdle() throws {
  162. let channelPromise = self.loop.makePromise(of: Channel.self)
  163. let manager = self.makeConnectionManager { _, _ in
  164. return channelPromise.futureResult
  165. }
  166. // Start the connection.
  167. let readyChannelMux: EventLoopFuture<HTTP2StreamMultiplexer> = self
  168. .waitForStateChange(from: .idle, to: .connecting) {
  169. let readyChannelMux = manager.getHTTP2Multiplexer()
  170. self.loop.run()
  171. return readyChannelMux
  172. }
  173. // Setup the channel.
  174. let channel = EmbeddedChannel(loop: self.loop)
  175. let h2mux = HTTP2StreamMultiplexer(
  176. mode: .client,
  177. channel: channel,
  178. inboundStreamInitializer: nil
  179. )
  180. try channel.pipeline.addHandler(
  181. GRPCIdleHandler(
  182. connectionManager: manager,
  183. multiplexer: h2mux,
  184. idleTimeout: .minutes(5),
  185. keepalive: .init(),
  186. logger: self.logger
  187. )
  188. ).wait()
  189. channelPromise.succeed(channel)
  190. XCTAssertNoThrow(
  191. try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  192. .wait()
  193. )
  194. // Write a settings frame on the root stream; this'll make the channel 'ready'.
  195. try self.waitForStateChange(from: .connecting, to: .ready) {
  196. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  197. XCTAssertNoThrow(try channel.writeInbound(frame))
  198. // Wait for the multiplexer, it _must_ be ready now.
  199. XCTAssertNoThrow(try readyChannelMux.wait())
  200. }
  201. // Go idle. This will shutdown the channel.
  202. try self.waitForStateChange(from: .ready, to: .idle) {
  203. self.loop.advanceTime(by: .minutes(5))
  204. XCTAssertNoThrow(try channel.closeFuture.wait())
  205. }
  206. // Now shutdown.
  207. try self.waitForStateChange(from: .idle, to: .shutdown) {
  208. let shutdown = manager.shutdown()
  209. self.loop.run()
  210. XCTAssertNoThrow(try shutdown.wait())
  211. }
  212. }
  213. func testChannelInactiveBeforeActiveWithNoReconnect() throws {
  214. let channel = EmbeddedChannel(loop: self.loop)
  215. let channelPromise = self.loop.makePromise(of: Channel.self)
  216. let manager = self.makeConnectionManager { _, _ in
  217. return channelPromise.futureResult
  218. }
  219. // Start the connection.
  220. self.waitForStateChange(from: .idle, to: .connecting) {
  221. // Triggers the connect.
  222. _ = manager.getHTTP2Multiplexer()
  223. self.loop.run()
  224. }
  225. try channel.pipeline.syncOperations.addHandler(
  226. GRPCIdleHandler(
  227. connectionManager: manager,
  228. multiplexer: HTTP2StreamMultiplexer(
  229. mode: .client,
  230. channel: channel,
  231. inboundStreamInitializer: nil
  232. ),
  233. idleTimeout: .minutes(5),
  234. keepalive: .init(),
  235. logger: self.logger
  236. )
  237. )
  238. channelPromise.succeed(channel)
  239. // Oops: wrong way around. We should tolerate this.
  240. self.waitForStateChange(from: .connecting, to: .shutdown) {
  241. channel.pipeline.fireChannelInactive()
  242. }
  243. // Should be ignored.
  244. channel.pipeline.fireChannelActive()
  245. }
  246. func testChannelInactiveBeforeActiveWillReconnect() throws {
  247. var channels = [EmbeddedChannel(loop: self.loop), EmbeddedChannel(loop: self.loop)]
  248. var channelPromises: [EventLoopPromise<Channel>] = [self.loop.makePromise(),
  249. self.loop.makePromise()]
  250. var channelFutures = Array(channelPromises.map { $0.futureResult })
  251. var configuration = self.defaultConfiguration
  252. configuration.connectionBackoff = .oneSecondFixed
  253. let manager = self.makeConnectionManager(configuration: configuration) { _, _ in
  254. return channelFutures.removeLast()
  255. }
  256. // Start the connection.
  257. self.waitForStateChange(from: .idle, to: .connecting) {
  258. // Triggers the connect.
  259. _ = manager.getHTTP2Multiplexer()
  260. self.loop.run()
  261. }
  262. // Setup the channel.
  263. let channel1 = channels.removeLast()
  264. let channel1Promise = channelPromises.removeLast()
  265. try channel1.pipeline.syncOperations.addHandler(
  266. GRPCIdleHandler(
  267. connectionManager: manager,
  268. multiplexer: HTTP2StreamMultiplexer(
  269. mode: .client,
  270. channel: channel1,
  271. inboundStreamInitializer: nil
  272. ),
  273. idleTimeout: .minutes(5),
  274. keepalive: .init(),
  275. logger: self.logger
  276. )
  277. )
  278. channel1Promise.succeed(channel1)
  279. // Oops: wrong way around. We should tolerate this.
  280. self.waitForStateChange(from: .connecting, to: .transientFailure) {
  281. channel1.pipeline.fireChannelInactive()
  282. }
  283. channel1.pipeline.fireChannelActive()
  284. // Start the next attempt.
  285. self.waitForStateChange(from: .transientFailure, to: .connecting) {
  286. self.loop.advanceTime(by: .seconds(1))
  287. }
  288. let channel2 = channels.removeLast()
  289. let channel2Promise = channelPromises.removeLast()
  290. try channel2.pipeline.syncOperations.addHandler(
  291. GRPCIdleHandler(
  292. connectionManager: manager,
  293. multiplexer: HTTP2StreamMultiplexer(
  294. mode: .client,
  295. channel: channel1,
  296. inboundStreamInitializer: nil
  297. ),
  298. idleTimeout: .minutes(5),
  299. keepalive: .init(),
  300. logger: self.logger
  301. )
  302. )
  303. channel2Promise.succeed(channel2)
  304. try self.waitForStateChange(from: .connecting, to: .ready) {
  305. channel2.pipeline.fireChannelActive()
  306. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  307. XCTAssertNoThrow(try channel2.writeInbound(frame))
  308. }
  309. }
  310. func testIdleTimeoutWhenThereAreActiveStreams() throws {
  311. let channelPromise = self.loop.makePromise(of: Channel.self)
  312. let manager = self.makeConnectionManager { _, _ in
  313. return channelPromise.futureResult
  314. }
  315. // Start the connection.
  316. let readyChannelMux: EventLoopFuture<HTTP2StreamMultiplexer> = self
  317. .waitForStateChange(from: .idle, to: .connecting) {
  318. let readyChannelMux = manager.getHTTP2Multiplexer()
  319. self.loop.run()
  320. return readyChannelMux
  321. }
  322. // Setup the channel.
  323. let channel = EmbeddedChannel(loop: self.loop)
  324. let h2mux = HTTP2StreamMultiplexer(
  325. mode: .client,
  326. channel: channel,
  327. inboundStreamInitializer: nil
  328. )
  329. try channel.pipeline.addHandler(
  330. GRPCIdleHandler(
  331. connectionManager: manager,
  332. multiplexer: h2mux,
  333. idleTimeout: .minutes(5),
  334. keepalive: .init(),
  335. logger: self.logger
  336. )
  337. ).wait()
  338. channelPromise.succeed(channel)
  339. XCTAssertNoThrow(
  340. try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  341. .wait()
  342. )
  343. // Write a settings frame on the root stream; this'll make the channel 'ready'.
  344. try self.waitForStateChange(from: .connecting, to: .ready) {
  345. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  346. XCTAssertNoThrow(try channel.writeInbound(frame))
  347. // Wait for the HTTP/2 stream multiplexer, it _must_ be ready now.
  348. XCTAssertNoThrow(try readyChannelMux.wait())
  349. }
  350. // "create" a stream; the details don't matter here.
  351. let streamCreated = NIOHTTP2StreamCreatedEvent(
  352. streamID: 1,
  353. localInitialWindowSize: nil,
  354. remoteInitialWindowSize: nil
  355. )
  356. channel.pipeline.fireUserInboundEventTriggered(streamCreated)
  357. // Wait for the idle timeout: this should _not_ cause the channel to idle.
  358. self.loop.advanceTime(by: .minutes(5))
  359. // Now we're going to close the stream and wait for an idle timeout and then shutdown.
  360. self.waitForStateChange(from: .ready, to: .idle) {
  361. // Close the stream.
  362. let streamClosed = StreamClosedEvent(streamID: 1, reason: nil)
  363. channel.pipeline.fireUserInboundEventTriggered(streamClosed)
  364. // ... wait for the idle timeout,
  365. self.loop.advanceTime(by: .minutes(5))
  366. }
  367. // Now shutdown.
  368. try self.waitForStateChange(from: .idle, to: .shutdown) {
  369. let shutdown = manager.shutdown()
  370. self.loop.run()
  371. XCTAssertNoThrow(try shutdown.wait())
  372. }
  373. }
  374. func testConnectAndThenBecomeInactive() throws {
  375. let channelPromise = self.loop.makePromise(of: Channel.self)
  376. let manager = self.makeConnectionManager { _, _ in
  377. return channelPromise.futureResult
  378. }
  379. let readyChannelMux: EventLoopFuture<HTTP2StreamMultiplexer> = self
  380. .waitForStateChange(from: .idle, to: .connecting) {
  381. let readyChannelMux = manager.getHTTP2Multiplexer()
  382. self.loop.run()
  383. return readyChannelMux
  384. }
  385. // Setup the channel.
  386. let channel = EmbeddedChannel(loop: self.loop)
  387. let h2mux = HTTP2StreamMultiplexer(
  388. mode: .client,
  389. channel: channel,
  390. inboundStreamInitializer: nil
  391. )
  392. try channel.pipeline.addHandler(
  393. GRPCIdleHandler(
  394. connectionManager: manager,
  395. multiplexer: h2mux,
  396. idleTimeout: .minutes(5),
  397. keepalive: .init(),
  398. logger: self.logger
  399. )
  400. ).wait()
  401. channelPromise.succeed(channel)
  402. XCTAssertNoThrow(
  403. try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  404. .wait()
  405. )
  406. try self.waitForStateChange(from: .connecting, to: .shutdown) {
  407. // Okay: now close the channel; the `readyChannel` future has not been completed yet.
  408. let shutdown = manager.shutdown()
  409. self.loop.run()
  410. XCTAssertNoThrow(try shutdown.wait())
  411. }
  412. // We failed to get a channel and we don't have reconnect configured: we should be shutdown and
  413. // the `readyChannelMux` should error.
  414. XCTAssertThrowsError(try readyChannelMux.wait())
  415. }
  416. func testConnectOnSecondAttempt() throws {
  417. let channelPromise: EventLoopPromise<Channel> = self.loop.makePromise()
  418. let channelFutures: [EventLoopFuture<Channel>] = [
  419. self.loop.makeFailedFuture(DoomedChannelError()),
  420. channelPromise.futureResult,
  421. ]
  422. var channelFutureIterator = channelFutures.makeIterator()
  423. var configuration = self.defaultConfiguration
  424. configuration.connectionBackoff = .oneSecondFixed
  425. let manager = self.makeConnectionManager(configuration: configuration) { _, _ in
  426. guard let next = channelFutureIterator.next() else {
  427. XCTFail("Too many channels requested")
  428. return self.loop.makeFailedFuture(DoomedChannelError())
  429. }
  430. return next
  431. }
  432. let readyChannelMux: EventLoopFuture<HTTP2StreamMultiplexer> = self.waitForStateChanges([
  433. Change(from: .idle, to: .connecting),
  434. Change(from: .connecting, to: .transientFailure),
  435. ]) {
  436. // Get a HTTP/2 stream multiplexer.
  437. let readyChannelMux = manager.getHTTP2Multiplexer()
  438. self.loop.run()
  439. return readyChannelMux
  440. }
  441. // Get a HTTP/2 stream mux from the manager - it is a future for the one we made earlier.
  442. let anotherReadyChannelMux = manager.getHTTP2Multiplexer()
  443. self.loop.run()
  444. // Move time forwards by a second to start the next connection attempt.
  445. self.waitForStateChange(from: .transientFailure, to: .connecting) {
  446. self.loop.advanceTime(by: .seconds(1))
  447. }
  448. // Setup the actual channel and complete the promise.
  449. let channel = EmbeddedChannel(loop: self.loop)
  450. let h2mux = HTTP2StreamMultiplexer(
  451. mode: .client,
  452. channel: channel,
  453. inboundStreamInitializer: nil
  454. )
  455. try channel.pipeline.addHandler(
  456. GRPCIdleHandler(
  457. connectionManager: manager,
  458. multiplexer: h2mux,
  459. idleTimeout: .minutes(5),
  460. keepalive: .init(),
  461. logger: self.logger
  462. )
  463. ).wait()
  464. channelPromise.succeed(channel)
  465. XCTAssertNoThrow(
  466. try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  467. .wait()
  468. )
  469. // Write a SETTINGS frame on the root stream.
  470. try self.waitForStateChange(from: .connecting, to: .ready) {
  471. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  472. XCTAssertNoThrow(try channel.writeInbound(frame))
  473. }
  474. // Wait for the HTTP/2 stream multiplexer, it _must_ be ready now.
  475. XCTAssertNoThrow(try readyChannelMux.wait())
  476. XCTAssertNoThrow(try anotherReadyChannelMux.wait())
  477. // Now shutdown.
  478. try self.waitForStateChange(from: .ready, to: .shutdown) {
  479. let shutdown = manager.shutdown()
  480. self.loop.run()
  481. XCTAssertNoThrow(try shutdown.wait())
  482. }
  483. }
  484. func testShutdownWhileConnecting() throws {
  485. let channelPromise = self.loop.makePromise(of: Channel.self)
  486. let manager = self.makeConnectionManager { _, _ in
  487. return channelPromise.futureResult
  488. }
  489. let readyChannelMux: EventLoopFuture<HTTP2StreamMultiplexer> = self
  490. .waitForStateChange(from: .idle, to: .connecting) {
  491. let readyChannelMux = manager.getHTTP2Multiplexer()
  492. self.loop.run()
  493. return readyChannelMux
  494. }
  495. // Now shutdown.
  496. let shutdownFuture: EventLoopFuture<Void> = self.waitForStateChange(
  497. from: .connecting,
  498. to: .shutdown
  499. ) {
  500. let shutdown = manager.shutdown()
  501. self.loop.run()
  502. return shutdown
  503. }
  504. // The multiplexer we were requesting should fail.
  505. XCTAssertThrowsError(try readyChannelMux.wait())
  506. // We still have our channel promise to fulfil: if it succeeds then it too should be closed.
  507. channelPromise.succeed(EmbeddedChannel(loop: self.loop))
  508. let channel = try channelPromise.futureResult.wait()
  509. self.loop.run()
  510. XCTAssertNoThrow(try channel.closeFuture.wait())
  511. XCTAssertNoThrow(try shutdownFuture.wait())
  512. }
  513. func testShutdownWhileTransientFailure() throws {
  514. var configuration = self.defaultConfiguration
  515. configuration.connectionBackoff = .oneSecondFixed
  516. let manager = self.makeConnectionManager(configuration: configuration) { _, _ in
  517. self.loop.makeFailedFuture(DoomedChannelError())
  518. }
  519. let readyChannelMux: EventLoopFuture<HTTP2StreamMultiplexer> = self.waitForStateChanges([
  520. Change(from: .idle, to: .connecting),
  521. Change(from: .connecting, to: .transientFailure),
  522. ]) {
  523. // Get a HTTP/2 stream multiplexer.
  524. let readyChannelMux = manager.getHTTP2Multiplexer()
  525. self.loop.run()
  526. return readyChannelMux
  527. }
  528. // Now shutdown.
  529. try self.waitForStateChange(from: .transientFailure, to: .shutdown) {
  530. let shutdown = manager.shutdown()
  531. self.loop.run()
  532. XCTAssertNoThrow(try shutdown.wait())
  533. }
  534. // The HTTP/2 stream mux we were requesting should fail.
  535. XCTAssertThrowsError(try readyChannelMux.wait())
  536. }
  537. func testShutdownWhileActive() throws {
  538. let channelPromise = self.loop.makePromise(of: Channel.self)
  539. let manager = self.makeConnectionManager { _, _ in
  540. return channelPromise.futureResult
  541. }
  542. let readyChannelMux: EventLoopFuture<HTTP2StreamMultiplexer> = self
  543. .waitForStateChange(from: .idle, to: .connecting) {
  544. let readyChannelMux = manager.getHTTP2Multiplexer()
  545. self.loop.run()
  546. return readyChannelMux
  547. }
  548. // Prepare the channel
  549. let channel = EmbeddedChannel(loop: self.loop)
  550. let h2mux = HTTP2StreamMultiplexer(
  551. mode: .client,
  552. channel: channel,
  553. inboundStreamInitializer: nil
  554. )
  555. try channel.pipeline.addHandler(
  556. GRPCIdleHandler(
  557. connectionManager: manager,
  558. multiplexer: h2mux,
  559. idleTimeout: .minutes(5),
  560. keepalive: .init(),
  561. logger: self.logger
  562. )
  563. ).wait()
  564. channelPromise.succeed(channel)
  565. XCTAssertNoThrow(
  566. try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  567. .wait()
  568. )
  569. // (No state change expected here: active is an internal state.)
  570. // Now shutdown.
  571. try self.waitForStateChange(from: .connecting, to: .shutdown) {
  572. let shutdown = manager.shutdown()
  573. self.loop.run()
  574. XCTAssertNoThrow(try shutdown.wait())
  575. }
  576. // The HTTP/2 stream multiplexer we were requesting should fail.
  577. XCTAssertThrowsError(try readyChannelMux.wait())
  578. }
  579. func testShutdownWhileShutdown() throws {
  580. let manager = self.makeConnectionManager()
  581. try self.waitForStateChange(from: .idle, to: .shutdown) {
  582. let firstShutdown = manager.shutdown()
  583. self.loop.run()
  584. XCTAssertNoThrow(try firstShutdown.wait())
  585. }
  586. let secondShutdown = manager.shutdown()
  587. self.loop.run()
  588. XCTAssertNoThrow(try secondShutdown.wait())
  589. }
  590. func testTransientFailureWhileActive() throws {
  591. var configuration = self.defaultConfiguration
  592. configuration.connectionBackoff = .oneSecondFixed
  593. let channelPromise: EventLoopPromise<Channel> = self.loop.makePromise()
  594. let channelFutures: [EventLoopFuture<Channel>] = [
  595. channelPromise.futureResult,
  596. self.loop.makeFailedFuture(DoomedChannelError()),
  597. ]
  598. var channelFutureIterator = channelFutures.makeIterator()
  599. let manager = self.makeConnectionManager(configuration: configuration) { _, _ in
  600. guard let next = channelFutureIterator.next() else {
  601. XCTFail("Too many channels requested")
  602. return self.loop.makeFailedFuture(DoomedChannelError())
  603. }
  604. return next
  605. }
  606. let readyChannelMux: EventLoopFuture<HTTP2StreamMultiplexer> = self
  607. .waitForStateChange(from: .idle, to: .connecting) {
  608. let readyChannelMux = manager.getHTTP2Multiplexer()
  609. self.loop.run()
  610. return readyChannelMux
  611. }
  612. // Prepare the channel
  613. let firstChannel = EmbeddedChannel(loop: self.loop)
  614. let h2mux = HTTP2StreamMultiplexer(
  615. mode: .client,
  616. channel: firstChannel,
  617. inboundStreamInitializer: nil
  618. )
  619. try firstChannel.pipeline.addHandler(
  620. GRPCIdleHandler(
  621. connectionManager: manager,
  622. multiplexer: h2mux,
  623. idleTimeout: .minutes(5),
  624. keepalive: .init(),
  625. logger: self.logger
  626. )
  627. ).wait()
  628. channelPromise.succeed(firstChannel)
  629. XCTAssertNoThrow(
  630. try firstChannel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  631. .wait()
  632. )
  633. // (No state change expected here: active is an internal state.)
  634. // Close the channel (simulate e.g. TLS handshake failed)
  635. try self.waitForStateChange(from: .connecting, to: .transientFailure) {
  636. XCTAssertNoThrow(try firstChannel.close().wait())
  637. }
  638. // Start connecting again.
  639. self.waitForStateChanges([
  640. Change(from: .transientFailure, to: .connecting),
  641. Change(from: .connecting, to: .transientFailure),
  642. ]) {
  643. self.loop.advanceTime(by: .seconds(1))
  644. }
  645. // Now shutdown
  646. try self.waitForStateChange(from: .transientFailure, to: .shutdown) {
  647. let shutdown = manager.shutdown()
  648. self.loop.run()
  649. XCTAssertNoThrow(try shutdown.wait())
  650. }
  651. // The channel never came up: it should be throw.
  652. XCTAssertThrowsError(try readyChannelMux.wait())
  653. }
  654. func testTransientFailureWhileReady() throws {
  655. var configuration = self.defaultConfiguration
  656. configuration.connectionBackoff = .oneSecondFixed
  657. let firstChannelPromise: EventLoopPromise<Channel> = self.loop.makePromise()
  658. let secondChannelPromise: EventLoopPromise<Channel> = self.loop.makePromise()
  659. let channelFutures: [EventLoopFuture<Channel>] = [
  660. firstChannelPromise.futureResult,
  661. secondChannelPromise.futureResult,
  662. ]
  663. var channelFutureIterator = channelFutures.makeIterator()
  664. let manager = self.makeConnectionManager(configuration: configuration) { _, _ in
  665. guard let next = channelFutureIterator.next() else {
  666. XCTFail("Too many channels requested")
  667. return self.loop.makeFailedFuture(DoomedChannelError())
  668. }
  669. return next
  670. }
  671. let readyChannelMux: EventLoopFuture<HTTP2StreamMultiplexer> = self
  672. .waitForStateChange(from: .idle, to: .connecting) {
  673. let readyChannelMux = manager.getHTTP2Multiplexer()
  674. self.loop.run()
  675. return readyChannelMux
  676. }
  677. // Prepare the first channel
  678. let firstChannel = EmbeddedChannel(loop: self.loop)
  679. let firstH2mux = HTTP2StreamMultiplexer(
  680. mode: .client,
  681. channel: firstChannel,
  682. inboundStreamInitializer: nil
  683. )
  684. try firstChannel.pipeline.addHandler(
  685. GRPCIdleHandler(
  686. connectionManager: manager,
  687. multiplexer: firstH2mux,
  688. idleTimeout: .minutes(5),
  689. keepalive: .init(),
  690. logger: self.logger
  691. )
  692. ).wait()
  693. firstChannelPromise.succeed(firstChannel)
  694. XCTAssertNoThrow(
  695. try firstChannel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  696. .wait()
  697. )
  698. // Write a SETTINGS frame on the root stream.
  699. try self.waitForStateChange(from: .connecting, to: .ready) {
  700. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  701. XCTAssertNoThrow(try firstChannel.writeInbound(frame))
  702. }
  703. // Channel should now be ready.
  704. XCTAssertNoThrow(try readyChannelMux.wait())
  705. // Kill the first channel. But first ensure there's an active RPC, otherwise we'll idle.
  706. let streamCreated = NIOHTTP2StreamCreatedEvent(
  707. streamID: 1,
  708. localInitialWindowSize: nil,
  709. remoteInitialWindowSize: nil
  710. )
  711. firstChannel.pipeline.fireUserInboundEventTriggered(streamCreated)
  712. try self.waitForStateChange(from: .ready, to: .transientFailure) {
  713. XCTAssertNoThrow(try firstChannel.close().wait())
  714. }
  715. // Run to start connecting again.
  716. self.waitForStateChange(from: .transientFailure, to: .connecting) {
  717. self.loop.advanceTime(by: .seconds(1))
  718. }
  719. // Prepare the second channel
  720. let secondChannel = EmbeddedChannel(loop: self.loop)
  721. let secondH2mux = HTTP2StreamMultiplexer(
  722. mode: .client,
  723. channel: secondChannel,
  724. inboundStreamInitializer: nil
  725. )
  726. try secondChannel.pipeline.addHandler(
  727. GRPCIdleHandler(
  728. connectionManager: manager,
  729. multiplexer: secondH2mux,
  730. idleTimeout: .minutes(5),
  731. keepalive: .init(),
  732. logger: self.logger
  733. )
  734. ).wait()
  735. secondChannelPromise.succeed(secondChannel)
  736. XCTAssertNoThrow(
  737. try secondChannel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  738. .wait()
  739. )
  740. // Write a SETTINGS frame on the root stream.
  741. try self.waitForStateChange(from: .connecting, to: .ready) {
  742. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  743. XCTAssertNoThrow(try secondChannel.writeInbound(frame))
  744. }
  745. // Now shutdown
  746. try self.waitForStateChange(from: .ready, to: .shutdown) {
  747. let shutdown = manager.shutdown()
  748. self.loop.run()
  749. XCTAssertNoThrow(try shutdown.wait())
  750. }
  751. }
  752. func testGoAwayWhenReady() throws {
  753. let channelPromise = self.loop.makePromise(of: Channel.self)
  754. let manager = self.makeConnectionManager { _, _ in
  755. return channelPromise.futureResult
  756. }
  757. let readyChannelMux: EventLoopFuture<HTTP2StreamMultiplexer> = self
  758. .waitForStateChange(from: .idle, to: .connecting) {
  759. let readyChannelMux = manager.getHTTP2Multiplexer()
  760. self.loop.run()
  761. return readyChannelMux
  762. }
  763. // Setup the channel.
  764. let channel = EmbeddedChannel(loop: self.loop)
  765. let h2mux = HTTP2StreamMultiplexer(
  766. mode: .client,
  767. channel: channel,
  768. inboundStreamInitializer: nil
  769. )
  770. try channel.pipeline.addHandler(
  771. GRPCIdleHandler(
  772. connectionManager: manager,
  773. multiplexer: h2mux,
  774. idleTimeout: .minutes(5),
  775. keepalive: .init(),
  776. logger: self.logger
  777. )
  778. ).wait()
  779. channelPromise.succeed(channel)
  780. XCTAssertNoThrow(
  781. try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  782. .wait()
  783. )
  784. try self.waitForStateChange(from: .connecting, to: .ready) {
  785. // Write a SETTINGS frame on the root stream.
  786. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  787. XCTAssertNoThrow(try channel.writeInbound(frame))
  788. }
  789. // Wait for the HTTP/2 stream multiplexer, it _must_ be ready now.
  790. XCTAssertNoThrow(try readyChannelMux.wait())
  791. // Send a GO_AWAY; the details don't matter. This will cause the connection to go idle and the
  792. // channel to close.
  793. try self.waitForStateChange(from: .ready, to: .idle) {
  794. let goAway = HTTP2Frame(
  795. streamID: .rootStream,
  796. payload: .goAway(lastStreamID: 1, errorCode: .noError, opaqueData: nil)
  797. )
  798. XCTAssertNoThrow(try channel.writeInbound(goAway))
  799. self.loop.run()
  800. }
  801. self.loop.run()
  802. XCTAssertNoThrow(try channel.closeFuture.wait())
  803. // Now shutdown
  804. try self.waitForStateChange(from: .idle, to: .shutdown) {
  805. let shutdown = manager.shutdown()
  806. self.loop.run()
  807. XCTAssertNoThrow(try shutdown.wait())
  808. }
  809. }
  810. func testDoomedOptimisticChannelFromIdle() {
  811. var configuration = self.defaultConfiguration
  812. configuration.callStartBehavior = .fastFailure
  813. let manager = ConnectionManager(
  814. configuration: configuration,
  815. channelProvider: HookedChannelProvider { _, loop in
  816. return loop.makeFailedFuture(DoomedChannelError())
  817. },
  818. connectivityDelegate: nil,
  819. logger: self.logger
  820. )
  821. let candidate = manager.getHTTP2Multiplexer()
  822. self.loop.run()
  823. XCTAssertThrowsError(try candidate.wait())
  824. }
  825. func testDoomedOptimisticChannelFromConnecting() throws {
  826. var configuration = self.defaultConfiguration
  827. configuration.callStartBehavior = .fastFailure
  828. let promise = self.loop.makePromise(of: Channel.self)
  829. let manager = self.makeConnectionManager { _, _ in
  830. return promise.futureResult
  831. }
  832. self.waitForStateChange(from: .idle, to: .connecting) {
  833. // Trigger channel creation, and a connection attempt, we don't care about the HTTP/2 stream multiplexer.
  834. _ = manager.getHTTP2Multiplexer()
  835. self.loop.run()
  836. }
  837. // We're connecting: get an optimistic HTTP/2 stream multiplexer - this was selected in config.
  838. let optimisticChannelMux = manager.getHTTP2Multiplexer()
  839. self.loop.run()
  840. // Fail the promise.
  841. promise.fail(DoomedChannelError())
  842. XCTAssertThrowsError(try optimisticChannelMux.wait())
  843. }
  844. func testOptimisticChannelFromTransientFailure() throws {
  845. var configuration = self.defaultConfiguration
  846. configuration.callStartBehavior = .fastFailure
  847. configuration.connectionBackoff = ConnectionBackoff()
  848. let manager = self.makeConnectionManager(configuration: configuration) { _, _ in
  849. self.loop.makeFailedFuture(DoomedChannelError())
  850. }
  851. self.waitForStateChanges([
  852. Change(from: .idle, to: .connecting),
  853. Change(from: .connecting, to: .transientFailure),
  854. ]) {
  855. // Trigger channel creation, and a connection attempt, we don't care about the HTTP/2 stream multiplexer.
  856. _ = manager.getHTTP2Multiplexer()
  857. self.loop.run()
  858. }
  859. // Now we're sitting in transient failure. Get a HTTP/2 stream mux optimistically - selected in config.
  860. let optimisticChannelMux = manager.getHTTP2Multiplexer()
  861. self.loop.run()
  862. XCTAssertThrowsError(try optimisticChannelMux.wait()) { error in
  863. XCTAssertTrue(error is DoomedChannelError)
  864. }
  865. }
  866. func testOptimisticChannelFromShutdown() throws {
  867. var configuration = self.defaultConfiguration
  868. configuration.callStartBehavior = .fastFailure
  869. let manager = self.makeConnectionManager { _, _ in
  870. return self.loop.makeFailedFuture(DoomedChannelError())
  871. }
  872. let shutdown = manager.shutdown()
  873. self.loop.run()
  874. XCTAssertNoThrow(try shutdown.wait())
  875. // Get a channel optimistically. It'll fail, obviously.
  876. let channelMux = manager.getHTTP2Multiplexer()
  877. self.loop.run()
  878. XCTAssertThrowsError(try channelMux.wait())
  879. }
  880. func testForceIdleAfterInactive() throws {
  881. let channelPromise = self.loop.makePromise(of: Channel.self)
  882. let manager = self.makeConnectionManager { _, _ in
  883. return channelPromise.futureResult
  884. }
  885. // Start the connection.
  886. let readyChannelMux: EventLoopFuture<HTTP2StreamMultiplexer> = self.waitForStateChange(
  887. from: .idle,
  888. to: .connecting
  889. ) {
  890. let readyChannelMux = manager.getHTTP2Multiplexer()
  891. self.loop.run()
  892. return readyChannelMux
  893. }
  894. // Setup the real channel and activate it.
  895. let channel = EmbeddedChannel(loop: self.loop)
  896. let h2mux = HTTP2StreamMultiplexer(
  897. mode: .client,
  898. channel: channel,
  899. inboundStreamInitializer: nil
  900. )
  901. XCTAssertNoThrow(try channel.pipeline.addHandlers([
  902. GRPCIdleHandler(
  903. connectionManager: manager,
  904. multiplexer: h2mux,
  905. idleTimeout: .minutes(5),
  906. keepalive: .init(),
  907. logger: self.logger
  908. ),
  909. ]).wait())
  910. channelPromise.succeed(channel)
  911. self.loop.run()
  912. let connect = channel.connect(to: try SocketAddress(unixDomainSocketPath: "/ignored"))
  913. XCTAssertNoThrow(try connect.wait())
  914. // Write a SETTINGS frame on the root stream.
  915. try self.waitForStateChange(from: .connecting, to: .ready) {
  916. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  917. XCTAssertNoThrow(try channel.writeInbound(frame))
  918. }
  919. // The channel should now be ready.
  920. XCTAssertNoThrow(try readyChannelMux.wait())
  921. // Now drop the connection.
  922. try self.waitForStateChange(from: .ready, to: .shutdown) {
  923. let shutdown = manager.shutdown()
  924. self.loop.run()
  925. XCTAssertNoThrow(try shutdown.wait())
  926. }
  927. }
  928. func testCloseWithoutActiveRPCs() throws {
  929. let channelPromise = self.loop.makePromise(of: Channel.self)
  930. let manager = self.makeConnectionManager { _, _ in
  931. return channelPromise.futureResult
  932. }
  933. // Start the connection.
  934. let readyChannelMux = self.waitForStateChange(
  935. from: .idle,
  936. to: .connecting
  937. ) { () -> EventLoopFuture<HTTP2StreamMultiplexer> in
  938. let readyChannelMux = manager.getHTTP2Multiplexer()
  939. self.loop.run()
  940. return readyChannelMux
  941. }
  942. // Setup the actual channel and activate it.
  943. let channel = EmbeddedChannel(loop: self.loop)
  944. let h2mux = HTTP2StreamMultiplexer(
  945. mode: .client,
  946. channel: channel,
  947. inboundStreamInitializer: nil
  948. )
  949. XCTAssertNoThrow(try channel.pipeline.addHandlers([
  950. GRPCIdleHandler(
  951. connectionManager: manager,
  952. multiplexer: h2mux,
  953. idleTimeout: .minutes(5),
  954. keepalive: .init(),
  955. logger: self.logger
  956. ),
  957. ]).wait())
  958. channelPromise.succeed(channel)
  959. self.loop.run()
  960. let connect = channel.connect(to: try SocketAddress(unixDomainSocketPath: "/ignored"))
  961. XCTAssertNoThrow(try connect.wait())
  962. // "ready" the connection.
  963. try self.waitForStateChange(from: .connecting, to: .ready) {
  964. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  965. XCTAssertNoThrow(try channel.writeInbound(frame))
  966. }
  967. // The HTTP/2 stream multiplexer should now be ready.
  968. XCTAssertNoThrow(try readyChannelMux.wait())
  969. // Close the channel. There are no active RPCs so we should idle rather than be in the transient
  970. // failure state.
  971. self.waitForStateChange(from: .ready, to: .idle) {
  972. channel.pipeline.fireChannelInactive()
  973. }
  974. }
  975. func testIdleErrorDoesNothing() throws {
  976. let manager = self.makeConnectionManager()
  977. // Dropping an error on this manager should be fine.
  978. manager.channelError(DoomedChannelError())
  979. // Shutting down is then safe.
  980. try self.waitForStateChange(from: .idle, to: .shutdown) {
  981. let shutdown = manager.shutdown()
  982. self.loop.run()
  983. XCTAssertNoThrow(try shutdown.wait())
  984. }
  985. }
  986. func testHTTP2Delegates() throws {
  987. let channel = EmbeddedChannel(loop: self.loop)
  988. defer {
  989. XCTAssertNoThrow(try channel.finish())
  990. }
  991. let multiplexer = HTTP2StreamMultiplexer(
  992. mode: .client,
  993. channel: channel,
  994. inboundStreamInitializer: nil
  995. )
  996. class HTTP2Delegate: ConnectionManagerHTTP2Delegate {
  997. var streamsOpened = 0
  998. var streamsClosed = 0
  999. var maxConcurrentStreams = 0
  1000. func streamOpened(_ connectionManager: ConnectionManager) {
  1001. self.streamsOpened += 1
  1002. }
  1003. func streamClosed(_ connectionManager: ConnectionManager) {
  1004. self.streamsClosed += 1
  1005. }
  1006. func receivedSettingsMaxConcurrentStreams(
  1007. _ connectionManager: ConnectionManager,
  1008. maxConcurrentStreams: Int
  1009. ) {
  1010. self.maxConcurrentStreams = maxConcurrentStreams
  1011. }
  1012. }
  1013. let http2 = HTTP2Delegate()
  1014. let manager = ConnectionManager(
  1015. eventLoop: self.loop,
  1016. channelProvider: HookedChannelProvider { manager, eventLoop -> EventLoopFuture<Channel> in
  1017. let idleHandler = GRPCIdleHandler(
  1018. connectionManager: manager,
  1019. multiplexer: multiplexer,
  1020. idleTimeout: .minutes(5),
  1021. keepalive: ClientConnectionKeepalive(),
  1022. logger: self.logger
  1023. )
  1024. // We're going to cheat a bit by not putting the multiplexer in the channel. This allows
  1025. // us to just fire stream created/closed events into the channel.
  1026. do {
  1027. try channel.pipeline.syncOperations.addHandler(idleHandler)
  1028. } catch {
  1029. return eventLoop.makeFailedFuture(error)
  1030. }
  1031. return eventLoop.makeSucceededFuture(channel)
  1032. },
  1033. callStartBehavior: .waitsForConnectivity,
  1034. connectionBackoff: ConnectionBackoff(),
  1035. connectivityDelegate: nil,
  1036. http2Delegate: http2,
  1037. logger: self.logger
  1038. )
  1039. // Start connecting.
  1040. let futureMultiplexer = manager.getHTTP2Multiplexer()
  1041. self.loop.run()
  1042. // Do the actual connecting.
  1043. XCTAssertNoThrow(try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored")))
  1044. // The channel isn't ready until it's seen a SETTINGS frame.
  1045. func makeSettingsFrame(maxConcurrentStreams: Int) -> HTTP2Frame {
  1046. let settings = [HTTP2Setting(parameter: .maxConcurrentStreams, value: maxConcurrentStreams)]
  1047. return HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings)))
  1048. }
  1049. XCTAssertNoThrow(try channel.writeInbound(makeSettingsFrame(maxConcurrentStreams: 42)))
  1050. // We're ready now so the future multiplexer will resolve and we'll have seen an update to
  1051. // max concurrent streams.
  1052. XCTAssertNoThrow(try futureMultiplexer.wait())
  1053. XCTAssertEqual(http2.maxConcurrentStreams, 42)
  1054. XCTAssertNoThrow(try channel.writeInbound(makeSettingsFrame(maxConcurrentStreams: 13)))
  1055. XCTAssertEqual(http2.maxConcurrentStreams, 13)
  1056. // Open some streams.
  1057. for streamID in stride(from: HTTP2StreamID(1), to: HTTP2StreamID(9), by: 2) {
  1058. let streamCreated = NIOHTTP2StreamCreatedEvent(
  1059. streamID: streamID,
  1060. localInitialWindowSize: nil,
  1061. remoteInitialWindowSize: nil
  1062. )
  1063. channel.pipeline.fireUserInboundEventTriggered(streamCreated)
  1064. }
  1065. // ... and then close them.
  1066. for streamID in stride(from: HTTP2StreamID(1), to: HTTP2StreamID(9), by: 2) {
  1067. let streamClosed = StreamClosedEvent(streamID: streamID, reason: nil)
  1068. channel.pipeline.fireUserInboundEventTriggered(streamClosed)
  1069. }
  1070. XCTAssertEqual(http2.streamsOpened, 4)
  1071. XCTAssertEqual(http2.streamsClosed, 4)
  1072. }
  1073. func testChannelErrorWhenConnecting() throws {
  1074. let channelPromise = self.loop.makePromise(of: Channel.self)
  1075. let manager = self.makeConnectionManager { _, _ in
  1076. return channelPromise.futureResult
  1077. }
  1078. let multiplexer: EventLoopFuture<HTTP2StreamMultiplexer> = self.waitForStateChange(
  1079. from: .idle,
  1080. to: .connecting
  1081. ) {
  1082. let channel = manager.getHTTP2Multiplexer()
  1083. self.loop.run()
  1084. return channel
  1085. }
  1086. self.waitForStateChange(from: .connecting, to: .shutdown) {
  1087. manager.channelError(EventLoopError.shutdown)
  1088. }
  1089. XCTAssertThrowsError(try multiplexer.wait())
  1090. }
  1091. }
  1092. internal struct Change: Hashable, CustomStringConvertible {
  1093. var from: ConnectivityState
  1094. var to: ConnectivityState
  1095. var description: String {
  1096. return "\(self.from) → \(self.to)"
  1097. }
  1098. }
  1099. #if compiler(>=5.6)
  1100. // Unchecked as all mutable state is modified from a serial queue.
  1101. extension RecordingConnectivityDelegate: @unchecked Sendable {}
  1102. #endif // compiler(>=5.6)
  1103. internal class RecordingConnectivityDelegate: ConnectivityStateDelegate {
  1104. private let serialQueue = DispatchQueue(label: "io.grpc.testing")
  1105. private let semaphore = DispatchSemaphore(value: 0)
  1106. private var expectation: Expectation = .noExpectation
  1107. private let quiescingSemaphore = DispatchSemaphore(value: 0)
  1108. private enum Expectation {
  1109. /// We have no expectation of any changes. We'll just ignore any changes.
  1110. case noExpectation
  1111. /// We expect one change.
  1112. case one((Change) -> Void)
  1113. /// We expect 'count' changes.
  1114. case some(count: Int, recorded: [Change], ([Change]) -> Void)
  1115. var count: Int {
  1116. switch self {
  1117. case .noExpectation:
  1118. return 0
  1119. case .one:
  1120. return 1
  1121. case let .some(count, _, _):
  1122. return count
  1123. }
  1124. }
  1125. }
  1126. func connectivityStateDidChange(
  1127. from oldState: ConnectivityState,
  1128. to newState: ConnectivityState
  1129. ) {
  1130. self.serialQueue.async {
  1131. switch self.expectation {
  1132. case let .one(verify):
  1133. // We don't care about future changes.
  1134. self.expectation = .noExpectation
  1135. // Verify and notify.
  1136. verify(Change(from: oldState, to: newState))
  1137. self.semaphore.signal()
  1138. case .some(let count, var recorded, let verify):
  1139. recorded.append(Change(from: oldState, to: newState))
  1140. if recorded.count == count {
  1141. // We don't care about future changes.
  1142. self.expectation = .noExpectation
  1143. // Verify and notify.
  1144. verify(recorded)
  1145. self.semaphore.signal()
  1146. } else {
  1147. // Still need more responses.
  1148. self.expectation = .some(count: count, recorded: recorded, verify)
  1149. }
  1150. case .noExpectation:
  1151. // Ignore any changes.
  1152. ()
  1153. }
  1154. }
  1155. }
  1156. func connectionStartedQuiescing() {
  1157. self.serialQueue.async {
  1158. self.quiescingSemaphore.signal()
  1159. }
  1160. }
  1161. func expectChanges(_ count: Int, verify: @escaping ([Change]) -> Void) {
  1162. self.serialQueue.async {
  1163. self.expectation = .some(count: count, recorded: [], verify)
  1164. }
  1165. }
  1166. func expectChange(verify: @escaping (Change) -> Void) {
  1167. self.serialQueue.async {
  1168. self.expectation = .one(verify)
  1169. }
  1170. }
  1171. func waitForExpectedChanges(
  1172. timeout: DispatchTimeInterval,
  1173. file: StaticString = #filePath,
  1174. line: UInt = #line
  1175. ) {
  1176. let result = self.semaphore.wait(timeout: .now() + timeout)
  1177. switch result {
  1178. case .success:
  1179. ()
  1180. case .timedOut:
  1181. XCTFail(
  1182. "Timed out before verifying \(self.expectation.count) change(s)",
  1183. file: file, line: line
  1184. )
  1185. }
  1186. }
  1187. func waitForQuiescing(timeout: DispatchTimeInterval) {
  1188. let result = self.quiescingSemaphore.wait(timeout: .now() + timeout)
  1189. switch result {
  1190. case .success:
  1191. ()
  1192. case .timedOut:
  1193. XCTFail("Timed out waiting for connection to start quiescing")
  1194. }
  1195. }
  1196. }
  1197. extension ConnectionBackoff {
  1198. fileprivate static let oneSecondFixed = ConnectionBackoff(
  1199. initialBackoff: 1.0,
  1200. maximumBackoff: 1.0,
  1201. multiplier: 1.0,
  1202. jitter: 0.0
  1203. )
  1204. }
  1205. private struct DoomedChannelError: Error {}
  1206. internal struct HookedChannelProvider: ConnectionManagerChannelProvider {
  1207. internal var provider: (ConnectionManager, EventLoop) -> EventLoopFuture<Channel>
  1208. init(_ provider: @escaping (ConnectionManager, EventLoop) -> EventLoopFuture<Channel>) {
  1209. self.provider = provider
  1210. }
  1211. func makeChannel(
  1212. managedBy connectionManager: ConnectionManager,
  1213. onEventLoop eventLoop: EventLoop,
  1214. connectTimeout: TimeAmount?,
  1215. logger: Logger
  1216. ) -> EventLoopFuture<Channel> {
  1217. return self.provider(connectionManager, eventLoop)
  1218. }
  1219. }
  1220. extension ConnectionManager {
  1221. // For backwards compatibility, to avoid large diffs in these tests.
  1222. fileprivate func shutdown() -> EventLoopFuture<Void> {
  1223. return self.shutdown(mode: .forceful)
  1224. }
  1225. }