ConnectionManagerTests.swift 50 KB

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