ConnectionManagerTests.swift 51 KB

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