ConnectionManagerTests.swift 52 KB

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