2
0

ConnectionManagerTests.swift 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567
  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. self.waitForStateChanges([
  865. Change(from: .idle, to: .connecting),
  866. Change(from: .connecting, to: .transientFailure),
  867. ]) {
  868. // Trigger channel creation, and a connection attempt, we don't care about the HTTP/2 stream multiplexer.
  869. _ = manager.getHTTP2Multiplexer()
  870. self.loop.run()
  871. }
  872. // Now we're sitting in transient failure. Get a HTTP/2 stream mux optimistically - selected in config.
  873. let optimisticChannelMux = manager.getHTTP2Multiplexer()
  874. self.loop.run()
  875. XCTAssertThrowsError(try optimisticChannelMux.wait()) { error in
  876. XCTAssertTrue(error is DoomedChannelError)
  877. }
  878. }
  879. func testOptimisticChannelFromShutdown() throws {
  880. var configuration = self.defaultConfiguration
  881. configuration.callStartBehavior = .fastFailure
  882. let manager = self.makeConnectionManager { _, _ in
  883. return self.loop.makeFailedFuture(DoomedChannelError())
  884. }
  885. let shutdown = manager.shutdown()
  886. self.loop.run()
  887. XCTAssertNoThrow(try shutdown.wait())
  888. // Get a channel optimistically. It'll fail, obviously.
  889. let channelMux = manager.getHTTP2Multiplexer()
  890. self.loop.run()
  891. XCTAssertThrowsError(try channelMux.wait())
  892. }
  893. func testForceIdleAfterInactive() throws {
  894. let channelPromise = self.loop.makePromise(of: Channel.self)
  895. let manager = self.makeConnectionManager { _, _ in
  896. return channelPromise.futureResult
  897. }
  898. // Start the connection.
  899. let readyChannelMux: EventLoopFuture<HTTP2StreamMultiplexer> = self.waitForStateChange(
  900. from: .idle,
  901. to: .connecting
  902. ) {
  903. let readyChannelMux = manager.getHTTP2Multiplexer()
  904. self.loop.run()
  905. return readyChannelMux
  906. }
  907. // Setup the real channel and activate it.
  908. let channel = EmbeddedChannel(loop: self.loop)
  909. let h2mux = HTTP2StreamMultiplexer(
  910. mode: .client,
  911. channel: channel,
  912. inboundStreamInitializer: nil
  913. )
  914. XCTAssertNoThrow(
  915. try channel.pipeline.addHandlers([
  916. GRPCIdleHandler(
  917. connectionManager: manager,
  918. multiplexer: h2mux,
  919. idleTimeout: .minutes(5),
  920. keepalive: .init(),
  921. logger: self.logger
  922. )
  923. ]).wait()
  924. )
  925. channelPromise.succeed(channel)
  926. self.loop.run()
  927. let connect = channel.connect(to: try SocketAddress(unixDomainSocketPath: "/ignored"))
  928. XCTAssertNoThrow(try connect.wait())
  929. // Write a SETTINGS frame on the root stream.
  930. try self.waitForStateChange(from: .connecting, to: .ready) {
  931. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  932. XCTAssertNoThrow(try channel.writeInbound(frame))
  933. }
  934. // The channel should now be ready.
  935. XCTAssertNoThrow(try readyChannelMux.wait())
  936. // Now drop the connection.
  937. try self.waitForStateChange(from: .ready, to: .shutdown) {
  938. let shutdown = manager.shutdown()
  939. self.loop.run()
  940. XCTAssertNoThrow(try shutdown.wait())
  941. }
  942. }
  943. func testCloseWithoutActiveRPCs() throws {
  944. let channelPromise = self.loop.makePromise(of: Channel.self)
  945. let manager = self.makeConnectionManager { _, _ in
  946. return channelPromise.futureResult
  947. }
  948. // Start the connection.
  949. let readyChannelMux = self.waitForStateChange(
  950. from: .idle,
  951. to: .connecting
  952. ) { () -> EventLoopFuture<HTTP2StreamMultiplexer> in
  953. let readyChannelMux = manager.getHTTP2Multiplexer()
  954. self.loop.run()
  955. return readyChannelMux
  956. }
  957. // Setup the actual channel and activate it.
  958. let channel = EmbeddedChannel(loop: self.loop)
  959. let h2mux = HTTP2StreamMultiplexer(
  960. mode: .client,
  961. channel: channel,
  962. inboundStreamInitializer: nil
  963. )
  964. XCTAssertNoThrow(
  965. try channel.pipeline.addHandlers([
  966. GRPCIdleHandler(
  967. connectionManager: manager,
  968. multiplexer: h2mux,
  969. idleTimeout: .minutes(5),
  970. keepalive: .init(),
  971. logger: self.logger
  972. )
  973. ]).wait()
  974. )
  975. channelPromise.succeed(channel)
  976. self.loop.run()
  977. let connect = channel.connect(to: try SocketAddress(unixDomainSocketPath: "/ignored"))
  978. XCTAssertNoThrow(try connect.wait())
  979. // "ready" the connection.
  980. try self.waitForStateChange(from: .connecting, to: .ready) {
  981. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  982. XCTAssertNoThrow(try channel.writeInbound(frame))
  983. }
  984. // The HTTP/2 stream multiplexer should now be ready.
  985. XCTAssertNoThrow(try readyChannelMux.wait())
  986. // Close the channel. There are no active RPCs so we should idle rather than be in the transient
  987. // failure state.
  988. self.waitForStateChange(from: .ready, to: .idle) {
  989. channel.pipeline.fireChannelInactive()
  990. }
  991. }
  992. func testIdleErrorDoesNothing() throws {
  993. let manager = self.makeConnectionManager()
  994. // Dropping an error on this manager should be fine.
  995. manager.channelError(DoomedChannelError())
  996. // Shutting down is then safe.
  997. try self.waitForStateChange(from: .idle, to: .shutdown) {
  998. let shutdown = manager.shutdown()
  999. self.loop.run()
  1000. XCTAssertNoThrow(try shutdown.wait())
  1001. }
  1002. }
  1003. func testHTTP2Delegates() throws {
  1004. let channel = EmbeddedChannel(loop: self.loop)
  1005. defer {
  1006. XCTAssertNoThrow(try channel.finish())
  1007. }
  1008. let multiplexer = HTTP2StreamMultiplexer(
  1009. mode: .client,
  1010. channel: channel,
  1011. inboundStreamInitializer: nil
  1012. )
  1013. class HTTP2Delegate: ConnectionManagerHTTP2Delegate {
  1014. var streamsOpened = 0
  1015. var streamsClosed = 0
  1016. var maxConcurrentStreams = 0
  1017. func streamOpened(_ connectionManager: ConnectionManager) {
  1018. self.streamsOpened += 1
  1019. }
  1020. func streamClosed(_ connectionManager: ConnectionManager) {
  1021. self.streamsClosed += 1
  1022. }
  1023. func receivedSettingsMaxConcurrentStreams(
  1024. _ connectionManager: ConnectionManager,
  1025. maxConcurrentStreams: Int
  1026. ) {
  1027. self.maxConcurrentStreams = maxConcurrentStreams
  1028. }
  1029. }
  1030. let http2 = HTTP2Delegate()
  1031. let manager = ConnectionManager(
  1032. eventLoop: self.loop,
  1033. channelProvider: HookedChannelProvider { manager, eventLoop -> EventLoopFuture<Channel> in
  1034. let idleHandler = GRPCIdleHandler(
  1035. connectionManager: manager,
  1036. multiplexer: multiplexer,
  1037. idleTimeout: .minutes(5),
  1038. keepalive: ClientConnectionKeepalive(),
  1039. logger: self.logger
  1040. )
  1041. // We're going to cheat a bit by not putting the multiplexer in the channel. This allows
  1042. // us to just fire stream created/closed events into the channel.
  1043. do {
  1044. try channel.pipeline.syncOperations.addHandler(idleHandler)
  1045. } catch {
  1046. return eventLoop.makeFailedFuture(error)
  1047. }
  1048. return eventLoop.makeSucceededFuture(channel)
  1049. },
  1050. callStartBehavior: .waitsForConnectivity,
  1051. idleBehavior: .closeWhenIdleTimeout,
  1052. connectionBackoff: ConnectionBackoff(),
  1053. connectivityDelegate: nil,
  1054. http2Delegate: http2,
  1055. logger: self.logger
  1056. )
  1057. // Start connecting.
  1058. let futureMultiplexer = manager.getHTTP2Multiplexer()
  1059. self.loop.run()
  1060. // Do the actual connecting.
  1061. XCTAssertNoThrow(try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored")))
  1062. // The channel isn't ready until it's seen a SETTINGS frame.
  1063. func makeSettingsFrame(maxConcurrentStreams: Int) -> HTTP2Frame {
  1064. let settings = [HTTP2Setting(parameter: .maxConcurrentStreams, value: maxConcurrentStreams)]
  1065. return HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings)))
  1066. }
  1067. XCTAssertNoThrow(try channel.writeInbound(makeSettingsFrame(maxConcurrentStreams: 42)))
  1068. // We're ready now so the future multiplexer will resolve and we'll have seen an update to
  1069. // max concurrent streams.
  1070. XCTAssertNoThrow(try futureMultiplexer.wait())
  1071. XCTAssertEqual(http2.maxConcurrentStreams, 42)
  1072. XCTAssertNoThrow(try channel.writeInbound(makeSettingsFrame(maxConcurrentStreams: 13)))
  1073. XCTAssertEqual(http2.maxConcurrentStreams, 13)
  1074. // Open some streams.
  1075. for streamID in stride(from: HTTP2StreamID(1), to: HTTP2StreamID(9), by: 2) {
  1076. let streamCreated = NIOHTTP2StreamCreatedEvent(
  1077. streamID: streamID,
  1078. localInitialWindowSize: nil,
  1079. remoteInitialWindowSize: nil
  1080. )
  1081. channel.pipeline.fireUserInboundEventTriggered(streamCreated)
  1082. }
  1083. // ... and then close them.
  1084. for streamID in stride(from: HTTP2StreamID(1), to: HTTP2StreamID(9), by: 2) {
  1085. let streamClosed = StreamClosedEvent(streamID: streamID, reason: nil)
  1086. channel.pipeline.fireUserInboundEventTriggered(streamClosed)
  1087. }
  1088. XCTAssertEqual(http2.streamsOpened, 4)
  1089. XCTAssertEqual(http2.streamsClosed, 4)
  1090. }
  1091. func testChannelErrorWhenConnecting() throws {
  1092. let channelPromise = self.loop.makePromise(of: Channel.self)
  1093. let manager = self.makeConnectionManager { _, _ in
  1094. return channelPromise.futureResult
  1095. }
  1096. let multiplexer: EventLoopFuture<HTTP2StreamMultiplexer> = self.waitForStateChange(
  1097. from: .idle,
  1098. to: .connecting
  1099. ) {
  1100. let channel = manager.getHTTP2Multiplexer()
  1101. self.loop.run()
  1102. return channel
  1103. }
  1104. self.waitForStateChange(from: .connecting, to: .shutdown) {
  1105. channelPromise.fail(EventLoopError.shutdown)
  1106. }
  1107. XCTAssertThrowsError(try multiplexer.wait())
  1108. }
  1109. func testChannelErrorAndConnectFailWhenConnecting() throws {
  1110. // This test checks a path through the connection manager which previously led to an invalid
  1111. // state (a connect failure in a state other than connecting). To trigger these we need to
  1112. // fire an error down the pipeline containing the idle handler and fail the connect promise.
  1113. let escapedChannelPromise = self.loop.makePromise(of: Channel.self)
  1114. let channelPromise = self.loop.makePromise(of: Channel.self)
  1115. var configuration = self.defaultConfiguration
  1116. configuration.connectionBackoff = ConnectionBackoff()
  1117. let manager = self.makeConnectionManager(
  1118. configuration: configuration
  1119. ) { connectionManager, loop in
  1120. let channel = EmbeddedChannel(loop: loop as! EmbeddedEventLoop)
  1121. let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: channel) {
  1122. $0.eventLoop.makeSucceededVoidFuture()
  1123. }
  1124. let idleHandler = GRPCIdleHandler(
  1125. connectionManager: connectionManager,
  1126. multiplexer: multiplexer,
  1127. idleTimeout: .minutes(60),
  1128. keepalive: .init(),
  1129. logger: self.clientLogger
  1130. )
  1131. channel.pipeline.addHandler(idleHandler).whenSuccess {
  1132. escapedChannelPromise.succeed(channel)
  1133. }
  1134. return channelPromise.futureResult
  1135. }
  1136. // Ask for the multiplexer to trigger channel creation.
  1137. self.waitForStateChange(from: .idle, to: .connecting) {
  1138. _ = manager.getHTTP2Multiplexer()
  1139. self.loop.run()
  1140. }
  1141. // Fire an error down the pipeline.
  1142. let channel = try escapedChannelPromise.futureResult.wait()
  1143. channel.pipeline.fireErrorCaught(GRPCStatus(code: .unavailable))
  1144. // Fail the channel promise.
  1145. channelPromise.fail(GRPCStatus(code: .unavailable))
  1146. }
  1147. func testClientKeepaliveJitterWithoutClamping() {
  1148. let original = ClientConnectionKeepalive(interval: .seconds(2), timeout: .seconds(1))
  1149. let keepalive = original.jitteringInterval(byAtMost: .milliseconds(500))
  1150. XCTAssertGreaterThanOrEqual(keepalive.interval, .milliseconds(1500))
  1151. XCTAssertLessThanOrEqual(keepalive.interval, .milliseconds(2500))
  1152. }
  1153. func testClientKeepaliveJitterClampedToTimeout() {
  1154. let original = ClientConnectionKeepalive(interval: .seconds(2), timeout: .seconds(1))
  1155. let keepalive = original.jitteringInterval(byAtMost: .seconds(2))
  1156. // Strictly greater than the timeout of 1 seconds.
  1157. XCTAssertGreaterThan(keepalive.interval, .seconds(1))
  1158. XCTAssertLessThanOrEqual(keepalive.interval, .seconds(4))
  1159. }
  1160. func testServerKeepaliveJitterWithoutClamping() {
  1161. let original = ServerConnectionKeepalive(interval: .seconds(2), timeout: .seconds(1))
  1162. let keepalive = original.jitteringInterval(byAtMost: .milliseconds(500))
  1163. XCTAssertGreaterThanOrEqual(keepalive.interval, .milliseconds(1500))
  1164. XCTAssertLessThanOrEqual(keepalive.interval, .milliseconds(2500))
  1165. }
  1166. func testServerKeepaliveJitterClampedToTimeout() {
  1167. let original = ServerConnectionKeepalive(interval: .seconds(2), timeout: .seconds(1))
  1168. let keepalive = original.jitteringInterval(byAtMost: .seconds(2))
  1169. // Strictly greater than the timeout of 1 seconds.
  1170. XCTAssertGreaterThan(keepalive.interval, .seconds(1))
  1171. XCTAssertLessThanOrEqual(keepalive.interval, .seconds(4))
  1172. }
  1173. func testConnectTimeoutIsRespectedWithNoRetries() {
  1174. // Setup a factory which makes channels. We'll use this as the point to check that the
  1175. // connect timeout is as expected.
  1176. struct Provider: ConnectionManagerChannelProvider {
  1177. func makeChannel(
  1178. managedBy connectionManager: ConnectionManager,
  1179. onEventLoop eventLoop: any EventLoop,
  1180. connectTimeout: TimeAmount?,
  1181. logger: Logger
  1182. ) -> EventLoopFuture<Channel> {
  1183. XCTAssertEqual(connectTimeout, .seconds(314_159_265))
  1184. return eventLoop.makeFailedFuture(DoomedChannelError())
  1185. }
  1186. }
  1187. var configuration = self.defaultConfiguration
  1188. configuration.connectionBackoff = ConnectionBackoff(
  1189. minimumConnectionTimeout: 314_159_265,
  1190. retries: .none
  1191. )
  1192. let manager = ConnectionManager(
  1193. configuration: configuration,
  1194. channelProvider: Provider(),
  1195. connectivityDelegate: self.monitor,
  1196. idleBehavior: .closeWhenIdleTimeout,
  1197. logger: self.logger
  1198. )
  1199. // Setup the state change expectations and trigger them by asking for the multiplexer.
  1200. // We expect connecting to shutdown as no connect retries are configured and the factory
  1201. // always returns errors.
  1202. let multiplexer = self.waitForStateChanges([
  1203. Change(from: .idle, to: .connecting),
  1204. Change(from: .connecting, to: .shutdown),
  1205. ]) {
  1206. let multiplexer = manager.getHTTP2Multiplexer()
  1207. self.loop.run()
  1208. return multiplexer
  1209. }
  1210. XCTAssertThrowsError(try multiplexer.wait()) { error in
  1211. XCTAssert(error is DoomedChannelError)
  1212. }
  1213. }
  1214. }
  1215. internal struct Change: Hashable, CustomStringConvertible {
  1216. var from: ConnectivityState
  1217. var to: ConnectivityState
  1218. var description: String {
  1219. return "\(self.from) → \(self.to)"
  1220. }
  1221. }
  1222. // Unchecked as all mutable state is modified from a serial queue.
  1223. extension RecordingConnectivityDelegate: @unchecked Sendable {}
  1224. internal class RecordingConnectivityDelegate: ConnectivityStateDelegate {
  1225. private let serialQueue = DispatchQueue(label: "io.grpc.testing")
  1226. private let semaphore = DispatchSemaphore(value: 0)
  1227. private var expectation: Expectation = .noExpectation
  1228. private let quiescingSemaphore = DispatchSemaphore(value: 0)
  1229. private enum Expectation {
  1230. /// We have no expectation of any changes. We'll just ignore any changes.
  1231. case noExpectation
  1232. /// We expect one change.
  1233. case one((Change) -> Void)
  1234. /// We expect 'count' changes.
  1235. case some(count: Int, recorded: [Change], ([Change]) -> Void)
  1236. var count: Int {
  1237. switch self {
  1238. case .noExpectation:
  1239. return 0
  1240. case .one:
  1241. return 1
  1242. case let .some(count, _, _):
  1243. return count
  1244. }
  1245. }
  1246. }
  1247. func connectivityStateDidChange(
  1248. from oldState: ConnectivityState,
  1249. to newState: ConnectivityState
  1250. ) {
  1251. self.serialQueue.async {
  1252. switch self.expectation {
  1253. case let .one(verify):
  1254. // We don't care about future changes.
  1255. self.expectation = .noExpectation
  1256. // Verify and notify.
  1257. verify(Change(from: oldState, to: newState))
  1258. self.semaphore.signal()
  1259. case .some(let count, var recorded, let verify):
  1260. recorded.append(Change(from: oldState, to: newState))
  1261. if recorded.count == count {
  1262. // We don't care about future changes.
  1263. self.expectation = .noExpectation
  1264. // Verify and notify.
  1265. verify(recorded)
  1266. self.semaphore.signal()
  1267. } else {
  1268. // Still need more responses.
  1269. self.expectation = .some(count: count, recorded: recorded, verify)
  1270. }
  1271. case .noExpectation:
  1272. // Ignore any changes.
  1273. ()
  1274. }
  1275. }
  1276. }
  1277. func connectionStartedQuiescing() {
  1278. self.serialQueue.async {
  1279. self.quiescingSemaphore.signal()
  1280. }
  1281. }
  1282. func expectChanges(_ count: Int, verify: @escaping ([Change]) -> Void) {
  1283. self.serialQueue.async {
  1284. self.expectation = .some(count: count, recorded: [], verify)
  1285. }
  1286. }
  1287. func expectChange(verify: @escaping (Change) -> Void) {
  1288. self.serialQueue.async {
  1289. self.expectation = .one(verify)
  1290. }
  1291. }
  1292. func waitForExpectedChanges(
  1293. timeout: DispatchTimeInterval,
  1294. file: StaticString = #filePath,
  1295. line: UInt = #line
  1296. ) {
  1297. let result = self.semaphore.wait(timeout: .now() + timeout)
  1298. switch result {
  1299. case .success:
  1300. ()
  1301. case .timedOut:
  1302. XCTFail(
  1303. "Timed out before verifying \(self.expectation.count) change(s)",
  1304. file: file,
  1305. line: line
  1306. )
  1307. }
  1308. }
  1309. func waitForQuiescing(timeout: DispatchTimeInterval) {
  1310. let result = self.quiescingSemaphore.wait(timeout: .now() + timeout)
  1311. switch result {
  1312. case .success:
  1313. ()
  1314. case .timedOut:
  1315. XCTFail("Timed out waiting for connection to start quiescing")
  1316. }
  1317. }
  1318. }
  1319. extension ConnectionBackoff {
  1320. fileprivate static let oneSecondFixed = ConnectionBackoff(
  1321. initialBackoff: 1.0,
  1322. maximumBackoff: 1.0,
  1323. multiplier: 1.0,
  1324. jitter: 0.0
  1325. )
  1326. }
  1327. private struct DoomedChannelError: Error {}
  1328. internal struct HookedChannelProvider: ConnectionManagerChannelProvider {
  1329. internal var provider: (ConnectionManager, EventLoop) -> EventLoopFuture<Channel>
  1330. init(_ provider: @escaping (ConnectionManager, EventLoop) -> EventLoopFuture<Channel>) {
  1331. self.provider = provider
  1332. }
  1333. func makeChannel(
  1334. managedBy connectionManager: ConnectionManager,
  1335. onEventLoop eventLoop: EventLoop,
  1336. connectTimeout: TimeAmount?,
  1337. logger: Logger
  1338. ) -> EventLoopFuture<Channel> {
  1339. return self.provider(connectionManager, eventLoop)
  1340. }
  1341. }
  1342. extension ConnectionManager {
  1343. // For backwards compatibility, to avoid large diffs in these tests.
  1344. fileprivate func shutdown() -> EventLoopFuture<Void> {
  1345. return self.shutdown(mode: .forceful)
  1346. }
  1347. }