ConnectionManagerTests.swift 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  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. // Unchecked as all mutable state is modified from a serial queue.
  1100. extension RecordingConnectivityDelegate: @unchecked Sendable {}
  1101. internal class RecordingConnectivityDelegate: ConnectivityStateDelegate {
  1102. private let serialQueue = DispatchQueue(label: "io.grpc.testing")
  1103. private let semaphore = DispatchSemaphore(value: 0)
  1104. private var expectation: Expectation = .noExpectation
  1105. private let quiescingSemaphore = DispatchSemaphore(value: 0)
  1106. private enum Expectation {
  1107. /// We have no expectation of any changes. We'll just ignore any changes.
  1108. case noExpectation
  1109. /// We expect one change.
  1110. case one((Change) -> Void)
  1111. /// We expect 'count' changes.
  1112. case some(count: Int, recorded: [Change], ([Change]) -> Void)
  1113. var count: Int {
  1114. switch self {
  1115. case .noExpectation:
  1116. return 0
  1117. case .one:
  1118. return 1
  1119. case let .some(count, _, _):
  1120. return count
  1121. }
  1122. }
  1123. }
  1124. func connectivityStateDidChange(
  1125. from oldState: ConnectivityState,
  1126. to newState: ConnectivityState
  1127. ) {
  1128. self.serialQueue.async {
  1129. switch self.expectation {
  1130. case let .one(verify):
  1131. // We don't care about future changes.
  1132. self.expectation = .noExpectation
  1133. // Verify and notify.
  1134. verify(Change(from: oldState, to: newState))
  1135. self.semaphore.signal()
  1136. case .some(let count, var recorded, let verify):
  1137. recorded.append(Change(from: oldState, to: newState))
  1138. if recorded.count == count {
  1139. // We don't care about future changes.
  1140. self.expectation = .noExpectation
  1141. // Verify and notify.
  1142. verify(recorded)
  1143. self.semaphore.signal()
  1144. } else {
  1145. // Still need more responses.
  1146. self.expectation = .some(count: count, recorded: recorded, verify)
  1147. }
  1148. case .noExpectation:
  1149. // Ignore any changes.
  1150. ()
  1151. }
  1152. }
  1153. }
  1154. func connectionStartedQuiescing() {
  1155. self.serialQueue.async {
  1156. self.quiescingSemaphore.signal()
  1157. }
  1158. }
  1159. func expectChanges(_ count: Int, verify: @escaping ([Change]) -> Void) {
  1160. self.serialQueue.async {
  1161. self.expectation = .some(count: count, recorded: [], verify)
  1162. }
  1163. }
  1164. func expectChange(verify: @escaping (Change) -> Void) {
  1165. self.serialQueue.async {
  1166. self.expectation = .one(verify)
  1167. }
  1168. }
  1169. func waitForExpectedChanges(
  1170. timeout: DispatchTimeInterval,
  1171. file: StaticString = #filePath,
  1172. line: UInt = #line
  1173. ) {
  1174. let result = self.semaphore.wait(timeout: .now() + timeout)
  1175. switch result {
  1176. case .success:
  1177. ()
  1178. case .timedOut:
  1179. XCTFail(
  1180. "Timed out before verifying \(self.expectation.count) change(s)",
  1181. file: file, line: line
  1182. )
  1183. }
  1184. }
  1185. func waitForQuiescing(timeout: DispatchTimeInterval) {
  1186. let result = self.quiescingSemaphore.wait(timeout: .now() + timeout)
  1187. switch result {
  1188. case .success:
  1189. ()
  1190. case .timedOut:
  1191. XCTFail("Timed out waiting for connection to start quiescing")
  1192. }
  1193. }
  1194. }
  1195. extension ConnectionBackoff {
  1196. fileprivate static let oneSecondFixed = ConnectionBackoff(
  1197. initialBackoff: 1.0,
  1198. maximumBackoff: 1.0,
  1199. multiplier: 1.0,
  1200. jitter: 0.0
  1201. )
  1202. }
  1203. private struct DoomedChannelError: Error {}
  1204. internal struct HookedChannelProvider: ConnectionManagerChannelProvider {
  1205. internal var provider: (ConnectionManager, EventLoop) -> EventLoopFuture<Channel>
  1206. init(_ provider: @escaping (ConnectionManager, EventLoop) -> EventLoopFuture<Channel>) {
  1207. self.provider = provider
  1208. }
  1209. func makeChannel(
  1210. managedBy connectionManager: ConnectionManager,
  1211. onEventLoop eventLoop: EventLoop,
  1212. connectTimeout: TimeAmount?,
  1213. logger: Logger
  1214. ) -> EventLoopFuture<Channel> {
  1215. return self.provider(connectionManager, eventLoop)
  1216. }
  1217. }
  1218. extension ConnectionManager {
  1219. // For backwards compatibility, to avoid large diffs in these tests.
  1220. fileprivate func shutdown() -> EventLoopFuture<Void> {
  1221. return self.shutdown(mode: .forceful)
  1222. }
  1223. }