ConnectionManagerTests.swift 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  1. /*
  2. * Copyright 2020, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import EchoModel
  17. @testable import GRPC
  18. import NIO
  19. import NIOHTTP2
  20. import XCTest
  21. class ConnectionManagerTests: GRPCTestCase {
  22. private let loop = EmbeddedEventLoop()
  23. private let recorder = RecordingConnectivityDelegate()
  24. private var defaultConfiguration: ClientConnection.Configuration {
  25. return ClientConnection.Configuration(
  26. target: .unixDomainSocket("/ignored"),
  27. eventLoopGroup: self.loop,
  28. connectivityStateDelegate: self.recorder,
  29. connectionBackoff: nil,
  30. backgroundActivityLogger: self.clientLogger
  31. )
  32. }
  33. override func tearDown() {
  34. XCTAssertNoThrow(try self.loop.syncShutdownGracefully())
  35. super.tearDown()
  36. }
  37. private func waitForStateChange<Result>(
  38. from: ConnectivityState,
  39. to: ConnectivityState,
  40. timeout: DispatchTimeInterval = .seconds(1),
  41. file: StaticString = #file,
  42. line: UInt = #line,
  43. body: () throws -> Result
  44. ) rethrows -> Result {
  45. self.recorder.expectChange {
  46. XCTAssertEqual($0, Change(from: from, to: to), file: file, line: line)
  47. }
  48. let result = try body()
  49. self.recorder.waitForExpectedChanges(timeout: timeout, file: file, line: line)
  50. return result
  51. }
  52. private func waitForStateChanges<Result>(
  53. _ changes: [Change],
  54. timeout: DispatchTimeInterval = .seconds(1),
  55. file: StaticString = #file,
  56. line: UInt = #line,
  57. body: () throws -> Result
  58. ) rethrows -> Result {
  59. self.recorder.expectChanges(changes.count) {
  60. XCTAssertEqual($0, changes)
  61. }
  62. let result = try body()
  63. self.recorder.waitForExpectedChanges(timeout: timeout, file: file, line: line)
  64. return result
  65. }
  66. }
  67. extension ConnectionManagerTests {
  68. func testIdleShutdown() throws {
  69. let manager = ConnectionManager(configuration: self.defaultConfiguration, logger: self.logger)
  70. try self.waitForStateChange(from: .idle, to: .shutdown) {
  71. let shutdown = manager.shutdown()
  72. self.loop.run()
  73. XCTAssertNoThrow(try shutdown.wait())
  74. }
  75. // Getting a channel should fail.
  76. let channel = manager.getChannel()
  77. self.loop.run()
  78. XCTAssertThrowsError(try channel.wait())
  79. }
  80. func testConnectFromIdleFailsWithNoReconnect() {
  81. let channelPromise = self.loop.makePromise(of: Channel.self)
  82. let manager = ConnectionManager.testingOnly(
  83. configuration: self.defaultConfiguration,
  84. logger: self.logger
  85. ) {
  86. channelPromise.futureResult
  87. }
  88. let channel: EventLoopFuture<Channel> = self.waitForStateChange(from: .idle, to: .connecting) {
  89. let channel = manager.getChannel()
  90. self.loop.run()
  91. return channel
  92. }
  93. self.waitForStateChange(from: .connecting, to: .shutdown) {
  94. channelPromise.fail(DoomedChannelError())
  95. }
  96. XCTAssertThrowsError(try channel.wait()) {
  97. XCTAssertTrue($0 is DoomedChannelError)
  98. }
  99. }
  100. func testConnectAndDisconnect() throws {
  101. let channelPromise = self.loop.makePromise(of: Channel.self)
  102. let manager = ConnectionManager.testingOnly(
  103. configuration: self.defaultConfiguration,
  104. logger: self.logger
  105. ) {
  106. channelPromise.futureResult
  107. }
  108. // Start the connection.
  109. self.waitForStateChange(from: .idle, to: .connecting) {
  110. _ = manager.getChannel()
  111. self.loop.run()
  112. }
  113. // Setup the real channel and activate it.
  114. let channel = EmbeddedChannel(
  115. handler: GRPCIdleHandler(
  116. mode: .client(manager),
  117. logger: self.logger,
  118. idleTimeout: .minutes(5)
  119. ),
  120. loop: self.loop
  121. )
  122. channelPromise.succeed(channel)
  123. XCTAssertNoThrow(
  124. try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  125. .wait()
  126. )
  127. // Write a settings frame on the root stream; this'll make the channel 'ready'.
  128. try self.waitForStateChange(from: .connecting, to: .ready) {
  129. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  130. XCTAssertNoThrow(try channel.writeInbound(frame))
  131. }
  132. // Close the channel.
  133. try self.waitForStateChange(from: .ready, to: .shutdown) {
  134. // Now the channel should be available: shut it down.
  135. let shutdown = manager.shutdown()
  136. self.loop.run()
  137. XCTAssertNoThrow(try shutdown.wait())
  138. }
  139. }
  140. func testConnectAndIdle() throws {
  141. let channelPromise = self.loop.makePromise(of: Channel.self)
  142. let manager = ConnectionManager.testingOnly(
  143. configuration: self.defaultConfiguration,
  144. logger: self.logger
  145. ) {
  146. channelPromise.futureResult
  147. }
  148. // Start the connection.
  149. let readyChannel: EventLoopFuture<Channel> = self
  150. .waitForStateChange(from: .idle, to: .connecting) {
  151. let readyChannel = manager.getChannel()
  152. self.loop.run()
  153. return readyChannel
  154. }
  155. // Setup the channel.
  156. let channel = EmbeddedChannel(
  157. handler: GRPCIdleHandler(
  158. mode: .client(manager),
  159. logger: self.logger,
  160. idleTimeout: .minutes(5)
  161. ),
  162. loop: self.loop
  163. )
  164. channelPromise.succeed(channel)
  165. XCTAssertNoThrow(
  166. try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  167. .wait()
  168. )
  169. // Write a settings frame on the root stream; this'll make the channel 'ready'.
  170. try self.waitForStateChange(from: .connecting, to: .ready) {
  171. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  172. XCTAssertNoThrow(try channel.writeInbound(frame))
  173. // Wait for the channel, it _must_ be ready now.
  174. XCTAssertNoThrow(try readyChannel.wait())
  175. }
  176. // Go idle. This will shutdown the channel.
  177. try self.waitForStateChange(from: .ready, to: .idle) {
  178. self.loop.advanceTime(by: .minutes(5))
  179. XCTAssertNoThrow(try readyChannel.flatMap { $0.closeFuture }.wait())
  180. }
  181. // Now shutdown.
  182. try self.waitForStateChange(from: .idle, to: .shutdown) {
  183. let shutdown = manager.shutdown()
  184. self.loop.run()
  185. XCTAssertNoThrow(try shutdown.wait())
  186. }
  187. }
  188. func testIdleTimeoutWhenThereAreActiveStreams() throws {
  189. let channelPromise = self.loop.makePromise(of: Channel.self)
  190. let manager = ConnectionManager.testingOnly(
  191. configuration: self.defaultConfiguration,
  192. logger: self.logger
  193. ) {
  194. channelPromise.futureResult
  195. }
  196. // Start the connection.
  197. let readyChannel: EventLoopFuture<Channel> = self
  198. .waitForStateChange(from: .idle, to: .connecting) {
  199. let readyChannel = manager.getChannel()
  200. self.loop.run()
  201. return readyChannel
  202. }
  203. // Setup the channel.
  204. let channel = EmbeddedChannel(
  205. handler: GRPCIdleHandler(
  206. mode: .client(manager),
  207. logger: self.logger,
  208. idleTimeout: .minutes(5)
  209. ),
  210. loop: self.loop
  211. )
  212. channelPromise.succeed(channel)
  213. XCTAssertNoThrow(
  214. try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  215. .wait()
  216. )
  217. // Write a settings frame on the root stream; this'll make the channel 'ready'.
  218. try self.waitForStateChange(from: .connecting, to: .ready) {
  219. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  220. XCTAssertNoThrow(try channel.writeInbound(frame))
  221. // Wait for the channel, it _must_ be ready now.
  222. XCTAssertNoThrow(try readyChannel.wait())
  223. }
  224. // "create" a stream; the details don't matter here.
  225. let streamCreated = NIOHTTP2StreamCreatedEvent(
  226. streamID: 1,
  227. localInitialWindowSize: nil,
  228. remoteInitialWindowSize: nil
  229. )
  230. channel.pipeline.fireUserInboundEventTriggered(streamCreated)
  231. // Wait for the idle timeout: this should _not_ cause the channel to idle.
  232. self.loop.advanceTime(by: .minutes(5))
  233. // Now we're going to close the stream and wait for an idle timeout and then shutdown.
  234. self.waitForStateChange(from: .ready, to: .idle) {
  235. // Close the stream.
  236. let streamClosed = StreamClosedEvent(streamID: 1, reason: nil)
  237. channel.pipeline.fireUserInboundEventTriggered(streamClosed)
  238. // ... wait for the idle timeout,
  239. self.loop.advanceTime(by: .minutes(5))
  240. }
  241. // Now shutdown.
  242. try self.waitForStateChange(from: .idle, to: .shutdown) {
  243. let shutdown = manager.shutdown()
  244. self.loop.run()
  245. XCTAssertNoThrow(try shutdown.wait())
  246. }
  247. }
  248. func testConnectAndThenBecomeInactive() throws {
  249. let channelPromise = self.loop.makePromise(of: Channel.self)
  250. let manager = ConnectionManager.testingOnly(
  251. configuration: self.defaultConfiguration,
  252. logger: self.logger
  253. ) {
  254. channelPromise.futureResult
  255. }
  256. let readyChannel: EventLoopFuture<Channel> = self
  257. .waitForStateChange(from: .idle, to: .connecting) {
  258. let readyChannel = manager.getChannel()
  259. self.loop.run()
  260. return readyChannel
  261. }
  262. // Setup the channel.
  263. let channel = EmbeddedChannel(
  264. handler: GRPCIdleHandler(
  265. mode: .client(manager),
  266. logger: self.logger,
  267. idleTimeout: .minutes(5)
  268. ),
  269. loop: self.loop
  270. )
  271. channelPromise.succeed(channel)
  272. XCTAssertNoThrow(
  273. try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  274. .wait()
  275. )
  276. try self.waitForStateChange(from: .connecting, to: .shutdown) {
  277. // Okay: now close the channel; the `readyChannel` future has not been completed yet.
  278. let shutdown = manager.shutdown()
  279. self.loop.run()
  280. XCTAssertNoThrow(try shutdown.wait())
  281. }
  282. // We failed to get a channel and we don't have reconnect configured: we should be shutdown and
  283. // the `readyChannel` should error.
  284. XCTAssertThrowsError(try readyChannel.wait())
  285. }
  286. func testConnectOnSecondAttempt() throws {
  287. let channelPromise: EventLoopPromise<Channel> = self.loop.makePromise()
  288. let channelFutures: [EventLoopFuture<Channel>] = [
  289. self.loop.makeFailedFuture(DoomedChannelError()),
  290. channelPromise.futureResult,
  291. ]
  292. var channelFutureIterator = channelFutures.makeIterator()
  293. var configuration = self.defaultConfiguration
  294. configuration.connectionBackoff = .oneSecondFixed
  295. let manager = ConnectionManager.testingOnly(configuration: configuration, logger: self.logger) {
  296. guard let next = channelFutureIterator.next() else {
  297. XCTFail("Too many channels requested")
  298. return self.loop.makeFailedFuture(DoomedChannelError())
  299. }
  300. return next
  301. }
  302. let readyChannel: EventLoopFuture<Channel> = self.waitForStateChanges([
  303. Change(from: .idle, to: .connecting),
  304. Change(from: .connecting, to: .transientFailure),
  305. ]) {
  306. // Get a channel.
  307. let readyChannel = manager.getChannel()
  308. self.loop.run()
  309. return readyChannel
  310. }
  311. // Get a channel from the manager: it is a future for the same channel.
  312. let anotherReadyChannel = manager.getChannel()
  313. self.loop.run()
  314. // Move time forwards by a second to start the next connection attempt.
  315. self.waitForStateChange(from: .transientFailure, to: .connecting) {
  316. self.loop.advanceTime(by: .seconds(1))
  317. }
  318. // Setup the actual channel and complete the promise.
  319. let channel = EmbeddedChannel(
  320. handler: GRPCIdleHandler(
  321. mode: .client(manager),
  322. logger: self.logger,
  323. idleTimeout: .minutes(5)
  324. ),
  325. loop: self.loop
  326. )
  327. channelPromise.succeed(channel)
  328. XCTAssertNoThrow(
  329. try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  330. .wait()
  331. )
  332. // Write a SETTINGS frame on the root stream.
  333. try self.waitForStateChange(from: .connecting, to: .ready) {
  334. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  335. XCTAssertNoThrow(try channel.writeInbound(frame))
  336. }
  337. // Wait for the channel, it _must_ be ready now.
  338. XCTAssertNoThrow(try readyChannel.wait())
  339. XCTAssertNoThrow(try anotherReadyChannel.wait())
  340. // Now shutdown.
  341. try self.waitForStateChange(from: .ready, to: .shutdown) {
  342. let shutdown = manager.shutdown()
  343. self.loop.run()
  344. XCTAssertNoThrow(try shutdown.wait())
  345. }
  346. }
  347. func testShutdownWhileConnecting() throws {
  348. let channelPromise = self.loop.makePromise(of: Channel.self)
  349. let manager = ConnectionManager.testingOnly(
  350. configuration: self.defaultConfiguration,
  351. logger: self.logger
  352. ) {
  353. channelPromise.futureResult
  354. }
  355. let readyChannel: EventLoopFuture<Channel> = self
  356. .waitForStateChange(from: .idle, to: .connecting) {
  357. let readyChannel = manager.getChannel()
  358. self.loop.run()
  359. return readyChannel
  360. }
  361. // Now shutdown.
  362. try self.waitForStateChange(from: .connecting, to: .shutdown) {
  363. let shutdown = manager.shutdown()
  364. self.loop.run()
  365. XCTAssertNoThrow(try shutdown.wait())
  366. }
  367. // The channel we were requesting should fail.
  368. XCTAssertThrowsError(try readyChannel.wait())
  369. // We still have our channel promise to fulfil: if it succeeds then it too should be closed.
  370. channelPromise.succeed(EmbeddedChannel(loop: self.loop))
  371. let channel = try channelPromise.futureResult.wait()
  372. self.loop.run()
  373. XCTAssertNoThrow(try channel.closeFuture.wait())
  374. }
  375. func testShutdownWhileTransientFailure() throws {
  376. var configuration = self.defaultConfiguration
  377. configuration.connectionBackoff = .oneSecondFixed
  378. let manager = ConnectionManager.testingOnly(configuration: configuration, logger: self.logger) {
  379. self.loop.makeFailedFuture(DoomedChannelError())
  380. }
  381. let readyChannel: EventLoopFuture<Channel> = self.waitForStateChanges([
  382. Change(from: .idle, to: .connecting),
  383. Change(from: .connecting, to: .transientFailure),
  384. ]) {
  385. // Get a channel.
  386. let readyChannel = manager.getChannel()
  387. self.loop.run()
  388. return readyChannel
  389. }
  390. // Now shutdown.
  391. try self.waitForStateChange(from: .transientFailure, to: .shutdown) {
  392. let shutdown = manager.shutdown()
  393. self.loop.run()
  394. XCTAssertNoThrow(try shutdown.wait())
  395. }
  396. // The channel we were requesting should fail.
  397. XCTAssertThrowsError(try readyChannel.wait())
  398. }
  399. func testShutdownWhileActive() throws {
  400. let channelPromise = self.loop.makePromise(of: Channel.self)
  401. let manager = ConnectionManager.testingOnly(
  402. configuration: self.defaultConfiguration,
  403. logger: self.logger
  404. ) {
  405. channelPromise.futureResult
  406. }
  407. let readyChannel: EventLoopFuture<Channel> = self
  408. .waitForStateChange(from: .idle, to: .connecting) {
  409. let readyChannel = manager.getChannel()
  410. self.loop.run()
  411. return readyChannel
  412. }
  413. // Prepare the channel
  414. let channel = EmbeddedChannel(
  415. handler: GRPCIdleHandler(
  416. mode: .client(manager),
  417. logger: self.logger,
  418. idleTimeout: .minutes(5)
  419. ),
  420. loop: self.loop
  421. )
  422. channelPromise.succeed(channel)
  423. XCTAssertNoThrow(
  424. try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  425. .wait()
  426. )
  427. // (No state change expected here: active is an internal state.)
  428. // Now shutdown.
  429. try self.waitForStateChange(from: .connecting, to: .shutdown) {
  430. let shutdown = manager.shutdown()
  431. self.loop.run()
  432. XCTAssertNoThrow(try shutdown.wait())
  433. }
  434. // The channel we were requesting should fail.
  435. XCTAssertThrowsError(try readyChannel.wait())
  436. }
  437. func testShutdownWhileShutdown() throws {
  438. let manager = ConnectionManager(configuration: self.defaultConfiguration, logger: self.logger)
  439. try self.waitForStateChange(from: .idle, to: .shutdown) {
  440. let firstShutdown = manager.shutdown()
  441. self.loop.run()
  442. XCTAssertNoThrow(try firstShutdown.wait())
  443. }
  444. let secondShutdown = manager.shutdown()
  445. self.loop.run()
  446. XCTAssertNoThrow(try secondShutdown.wait())
  447. }
  448. func testTransientFailureWhileActive() throws {
  449. var configuration = self.defaultConfiguration
  450. configuration.connectionBackoff = .oneSecondFixed
  451. let channelPromise: EventLoopPromise<Channel> = self.loop.makePromise()
  452. let channelFutures: [EventLoopFuture<Channel>] = [
  453. channelPromise.futureResult,
  454. self.loop.makeFailedFuture(DoomedChannelError()),
  455. ]
  456. var channelFutureIterator = channelFutures.makeIterator()
  457. let manager = ConnectionManager.testingOnly(configuration: configuration, logger: self.logger) {
  458. guard let next = channelFutureIterator.next() else {
  459. XCTFail("Too many channels requested")
  460. return self.loop.makeFailedFuture(DoomedChannelError())
  461. }
  462. return next
  463. }
  464. let readyChannel: EventLoopFuture<Channel> = self
  465. .waitForStateChange(from: .idle, to: .connecting) {
  466. let readyChannel = manager.getChannel()
  467. self.loop.run()
  468. return readyChannel
  469. }
  470. // Prepare the channel
  471. let firstChannel = EmbeddedChannel(
  472. handler: GRPCIdleHandler(
  473. mode: .client(manager),
  474. logger: self.logger,
  475. idleTimeout: .minutes(5)
  476. ),
  477. loop: self.loop
  478. )
  479. channelPromise.succeed(firstChannel)
  480. XCTAssertNoThrow(
  481. try firstChannel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  482. .wait()
  483. )
  484. // (No state change expected here: active is an internal state.)
  485. // Close the channel (simulate e.g. TLS handshake failed)
  486. try self.waitForStateChange(from: .connecting, to: .transientFailure) {
  487. XCTAssertNoThrow(try firstChannel.close().wait())
  488. }
  489. // Start connecting again.
  490. self.waitForStateChanges([
  491. Change(from: .transientFailure, to: .connecting),
  492. Change(from: .connecting, to: .transientFailure),
  493. ]) {
  494. self.loop.advanceTime(by: .seconds(1))
  495. }
  496. // Now shutdown
  497. try self.waitForStateChange(from: .transientFailure, to: .shutdown) {
  498. let shutdown = manager.shutdown()
  499. self.loop.run()
  500. XCTAssertNoThrow(try shutdown.wait())
  501. }
  502. // The channel never came up: it should be throw.
  503. XCTAssertThrowsError(try readyChannel.wait())
  504. }
  505. func testTransientFailureWhileReady() throws {
  506. var configuration = self.defaultConfiguration
  507. configuration.connectionBackoff = .oneSecondFixed
  508. let firstChannelPromise: EventLoopPromise<Channel> = self.loop.makePromise()
  509. let secondChannelPromise: EventLoopPromise<Channel> = self.loop.makePromise()
  510. let channelFutures: [EventLoopFuture<Channel>] = [
  511. firstChannelPromise.futureResult,
  512. secondChannelPromise.futureResult,
  513. ]
  514. var channelFutureIterator = channelFutures.makeIterator()
  515. let manager = ConnectionManager.testingOnly(configuration: configuration, logger: self.logger) {
  516. guard let next = channelFutureIterator.next() else {
  517. XCTFail("Too many channels requested")
  518. return self.loop.makeFailedFuture(DoomedChannelError())
  519. }
  520. return next
  521. }
  522. let readyChannel: EventLoopFuture<Channel> = self
  523. .waitForStateChange(from: .idle, to: .connecting) {
  524. let readyChannel = manager.getChannel()
  525. self.loop.run()
  526. return readyChannel
  527. }
  528. // Prepare the first channel
  529. let firstChannel = EmbeddedChannel(
  530. handler: GRPCIdleHandler(
  531. mode: .client(manager),
  532. logger: self.logger,
  533. idleTimeout: .minutes(5)
  534. ),
  535. loop: self.loop
  536. )
  537. firstChannelPromise.succeed(firstChannel)
  538. XCTAssertNoThrow(
  539. try firstChannel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  540. .wait()
  541. )
  542. // Write a SETTINGS frame on the root stream.
  543. try self.waitForStateChange(from: .connecting, to: .ready) {
  544. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  545. XCTAssertNoThrow(try firstChannel.writeInbound(frame))
  546. }
  547. // Channel should now be ready.
  548. XCTAssertNoThrow(try readyChannel.wait())
  549. // Kill the first channel. But first ensure there's an active RPC, otherwise we'll idle.
  550. let streamCreated = NIOHTTP2StreamCreatedEvent(
  551. streamID: 1,
  552. localInitialWindowSize: nil,
  553. remoteInitialWindowSize: nil
  554. )
  555. firstChannel.pipeline.fireUserInboundEventTriggered(streamCreated)
  556. try self.waitForStateChange(from: .ready, to: .transientFailure) {
  557. XCTAssertNoThrow(try firstChannel.close().wait())
  558. }
  559. // Run to start connecting again.
  560. self.waitForStateChange(from: .transientFailure, to: .connecting) {
  561. self.loop.advanceTime(by: .seconds(1))
  562. }
  563. // Prepare the second channel
  564. let secondChannel = EmbeddedChannel(
  565. handler: GRPCIdleHandler(
  566. mode: .client(manager),
  567. logger: self.logger,
  568. idleTimeout: .minutes(5)
  569. ),
  570. loop: self.loop
  571. )
  572. secondChannelPromise.succeed(secondChannel)
  573. XCTAssertNoThrow(
  574. try secondChannel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  575. .wait()
  576. )
  577. // Write a SETTINGS frame on the root stream.
  578. try self.waitForStateChange(from: .connecting, to: .ready) {
  579. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  580. XCTAssertNoThrow(try secondChannel.writeInbound(frame))
  581. }
  582. // Now shutdown
  583. try self.waitForStateChange(from: .ready, to: .shutdown) {
  584. let shutdown = manager.shutdown()
  585. self.loop.run()
  586. XCTAssertNoThrow(try shutdown.wait())
  587. }
  588. }
  589. func testGoAwayWhenReady() throws {
  590. let channelPromise = self.loop.makePromise(of: Channel.self)
  591. let manager = ConnectionManager.testingOnly(
  592. configuration: self.defaultConfiguration,
  593. logger: self.logger
  594. ) {
  595. channelPromise.futureResult
  596. }
  597. let readyChannel: EventLoopFuture<Channel> = self
  598. .waitForStateChange(from: .idle, to: .connecting) {
  599. let readyChannel = manager.getChannel()
  600. self.loop.run()
  601. return readyChannel
  602. }
  603. // Setup the channel.
  604. let channel = EmbeddedChannel(
  605. handler: GRPCIdleHandler(
  606. mode: .client(manager),
  607. logger: self.logger,
  608. idleTimeout: .minutes(5)
  609. ),
  610. loop: self.loop
  611. )
  612. channelPromise.succeed(channel)
  613. XCTAssertNoThrow(
  614. try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  615. .wait()
  616. )
  617. try self.waitForStateChange(from: .connecting, to: .ready) {
  618. // Write a SETTINGS frame on the root stream.
  619. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  620. XCTAssertNoThrow(try channel.writeInbound(frame))
  621. }
  622. // Wait for the channel, it _must_ be ready now.
  623. XCTAssertNoThrow(try readyChannel.wait())
  624. // Send a GO_AWAY; the details don't matter. This will cause the connection to go idle and the
  625. // channel to close.
  626. try self.waitForStateChange(from: .ready, to: .idle) {
  627. let goAway = HTTP2Frame(
  628. streamID: .rootStream,
  629. payload: .goAway(lastStreamID: 1, errorCode: .noError, opaqueData: nil)
  630. )
  631. XCTAssertNoThrow(try channel.writeInbound(goAway))
  632. }
  633. self.loop.run()
  634. XCTAssertNoThrow(try channel.closeFuture.wait())
  635. // Now shutdown
  636. try self.waitForStateChange(from: .idle, to: .shutdown) {
  637. let shutdown = manager.shutdown()
  638. self.loop.run()
  639. XCTAssertNoThrow(try shutdown.wait())
  640. }
  641. }
  642. func testDoomedOptimisticChannelFromIdle() {
  643. let manager = ConnectionManager.testingOnly(
  644. configuration: self.defaultConfiguration,
  645. logger: self.logger
  646. ) {
  647. self.loop.makeFailedFuture(DoomedChannelError())
  648. }
  649. let candidate = manager.getOptimisticChannel()
  650. self.loop.run()
  651. XCTAssertThrowsError(try candidate.wait())
  652. }
  653. func testDoomedOptimisticChannelFromConnecting() throws {
  654. let promise = self.loop.makePromise(of: Channel.self)
  655. let manager = ConnectionManager.testingOnly(
  656. configuration: self.defaultConfiguration,
  657. logger: self.logger
  658. ) {
  659. promise.futureResult
  660. }
  661. self.waitForStateChange(from: .idle, to: .connecting) {
  662. // Trigger channel creation, and a connection attempt, we don't care about the channel.
  663. _ = manager.getChannel()
  664. self.loop.run()
  665. }
  666. // We're connecting: get an optimistic channel.
  667. let optimisticChannel = manager.getOptimisticChannel()
  668. self.loop.run()
  669. // Fail the promise.
  670. promise.fail(DoomedChannelError())
  671. XCTAssertThrowsError(try optimisticChannel.wait())
  672. }
  673. func testOptimisticChannelFromTransientFailure() throws {
  674. var configuration = self.defaultConfiguration
  675. configuration.connectionBackoff = ConnectionBackoff()
  676. let manager = ConnectionManager.testingOnly(configuration: configuration, logger: self.logger) {
  677. self.loop.makeFailedFuture(DoomedChannelError())
  678. }
  679. self.waitForStateChanges([
  680. Change(from: .idle, to: .connecting),
  681. Change(from: .connecting, to: .transientFailure),
  682. ]) {
  683. // Trigger channel creation, and a connection attempt, we don't care about the channel.
  684. _ = manager.getChannel()
  685. self.loop.run()
  686. }
  687. // Now we're sitting in transient failure. Get a channel optimistically.
  688. let optimisticChannel = manager.getOptimisticChannel()
  689. self.loop.run()
  690. XCTAssertThrowsError(try optimisticChannel.wait()) { error in
  691. XCTAssertTrue(error is DoomedChannelError)
  692. }
  693. }
  694. func testOptimisticChannelFromShutdown() throws {
  695. let manager = ConnectionManager.testingOnly(
  696. configuration: self.defaultConfiguration,
  697. logger: self.logger
  698. ) {
  699. self.loop.makeFailedFuture(DoomedChannelError())
  700. }
  701. let shutdown = manager.shutdown()
  702. self.loop.run()
  703. XCTAssertNoThrow(try shutdown.wait())
  704. // Get a channel optimistically. It'll fail, obviously.
  705. let channel = manager.getOptimisticChannel()
  706. self.loop.run()
  707. XCTAssertThrowsError(try channel.wait())
  708. }
  709. func testDoubleIdle() throws {
  710. class CloseDroppingHandler: ChannelOutboundHandler {
  711. typealias OutboundIn = Any
  712. func close(context: ChannelHandlerContext, mode: CloseMode,
  713. promise: EventLoopPromise<Void>?) {
  714. promise?
  715. .fail(GRPCStatus(code: .unavailable, message: "Purposefully dropping channel close"))
  716. }
  717. }
  718. let channelPromise = self.loop.makePromise(of: Channel.self)
  719. let manager = ConnectionManager.testingOnly(
  720. configuration: self.defaultConfiguration,
  721. logger: self.logger
  722. ) {
  723. channelPromise.futureResult
  724. }
  725. // Start the connection.
  726. let readyChannel: EventLoopFuture<Channel> = self
  727. .waitForStateChange(from: .idle, to: .connecting) {
  728. let readyChannel = manager.getChannel()
  729. self.loop.run()
  730. return readyChannel
  731. }
  732. // Setup the real channel and activate it.
  733. let channel = EmbeddedChannel(loop: self.loop)
  734. XCTAssertNoThrow(try channel.pipeline.addHandlers([
  735. CloseDroppingHandler(),
  736. GRPCIdleHandler(mode: .client(manager), logger: manager.logger, idleTimeout: .minutes(5)),
  737. ]).wait())
  738. channelPromise.succeed(channel)
  739. self.loop.run()
  740. XCTAssertNoThrow(
  741. try channel.connect(to: SocketAddress(unixDomainSocketPath: "/ignored"))
  742. .wait()
  743. )
  744. // Write a SETTINGS frame on the root stream.
  745. try self.waitForStateChange(from: .connecting, to: .ready) {
  746. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  747. XCTAssertNoThrow(try channel.writeInbound(frame))
  748. }
  749. // The channel should now be ready.
  750. XCTAssertNoThrow(try readyChannel.wait())
  751. // Send a GO_AWAY; the details don't matter. This will cause the connection to go idle and the
  752. // channel to close.
  753. try self.waitForStateChange(from: .ready, to: .idle) {
  754. let goAway = HTTP2Frame(
  755. streamID: .rootStream,
  756. payload: .goAway(lastStreamID: 1, errorCode: .noError, opaqueData: nil)
  757. )
  758. XCTAssertNoThrow(try channel.writeInbound(goAway))
  759. }
  760. // We dropped the close; now wait for the scheduled idle to fire.
  761. //
  762. // Previously doing this this would fail a precondition.
  763. self.loop.advanceTime(by: .minutes(5))
  764. }
  765. func testForceIdleAfterInactive() throws {
  766. let channelPromise = self.loop.makePromise(of: Channel.self)
  767. let manager = ConnectionManager.testingOnly(
  768. configuration: self.defaultConfiguration,
  769. logger: self.logger
  770. ) {
  771. channelPromise.futureResult
  772. }
  773. // Start the connection.
  774. let readyChannel: EventLoopFuture<Channel> = self.waitForStateChange(
  775. from: .idle,
  776. to: .connecting
  777. ) {
  778. let readyChannel = manager.getChannel()
  779. self.loop.run()
  780. return readyChannel
  781. }
  782. // Setup the real channel and activate it.
  783. let channel = EmbeddedChannel(loop: self.loop)
  784. XCTAssertNoThrow(try channel.pipeline.addHandlers([
  785. GRPCIdleHandler(mode: .client(manager), logger: manager.logger, idleTimeout: .minutes(5)),
  786. ]).wait())
  787. channelPromise.succeed(channel)
  788. self.loop.run()
  789. let connect = channel.connect(to: try SocketAddress(unixDomainSocketPath: "/ignored"))
  790. XCTAssertNoThrow(try connect.wait())
  791. // Write a SETTINGS frame on the root stream.
  792. try self.waitForStateChange(from: .connecting, to: .ready) {
  793. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  794. XCTAssertNoThrow(try channel.writeInbound(frame))
  795. }
  796. // The channel should now be ready.
  797. XCTAssertNoThrow(try readyChannel.wait())
  798. // Now drop the connection.
  799. try self.waitForStateChange(from: .ready, to: .shutdown) {
  800. let shutdown = manager.shutdown()
  801. self.loop.run()
  802. XCTAssertNoThrow(try shutdown.wait())
  803. }
  804. // Fire a connection idled event, i.e. keepalive timeout has fired. This should be a no-op.
  805. // Previously this would hit a precondition failure.
  806. channel.pipeline.fireUserInboundEventTriggered(ConnectionIdledEvent())
  807. }
  808. func testCloseWithoutActiveRPCs() throws {
  809. let channelPromise = self.loop.makePromise(of: Channel.self)
  810. let manager = ConnectionManager.testingOnly(
  811. configuration: self.defaultConfiguration,
  812. logger: self.logger
  813. ) {
  814. channelPromise.futureResult
  815. }
  816. // Start the connection.
  817. let readyChannel = self.waitForStateChange(
  818. from: .idle,
  819. to: .connecting
  820. ) { () -> EventLoopFuture<Channel> in
  821. let readyChannel = manager.getChannel()
  822. self.loop.run()
  823. return readyChannel
  824. }
  825. // Setup the actual channel and activate it.
  826. let channel = EmbeddedChannel(loop: self.loop)
  827. XCTAssertNoThrow(try channel.pipeline.addHandlers([
  828. GRPCIdleHandler(mode: .client(manager), logger: manager.logger, idleTimeout: .minutes(5)),
  829. ]).wait())
  830. channelPromise.succeed(channel)
  831. self.loop.run()
  832. let connect = channel.connect(to: try SocketAddress(unixDomainSocketPath: "/ignored"))
  833. XCTAssertNoThrow(try connect.wait())
  834. // "ready" the connection.
  835. try self.waitForStateChange(from: .connecting, to: .ready) {
  836. let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
  837. XCTAssertNoThrow(try channel.writeInbound(frame))
  838. }
  839. // The channel should now be ready.
  840. XCTAssertNoThrow(try readyChannel.wait())
  841. // Close the channel. There are no active RPCs so we should idle rather than be in the transient
  842. // failure state.
  843. self.waitForStateChange(from: .ready, to: .idle) {
  844. channel.pipeline.fireChannelInactive()
  845. }
  846. }
  847. }
  848. internal struct Change: Hashable, CustomStringConvertible {
  849. var from: ConnectivityState
  850. var to: ConnectivityState
  851. var description: String {
  852. return "\(self.from) → \(self.to)"
  853. }
  854. }
  855. internal class RecordingConnectivityDelegate: ConnectivityStateDelegate {
  856. private let serialQueue = DispatchQueue(label: "io.grpc.testing")
  857. private let semaphore = DispatchSemaphore(value: 0)
  858. private var expectation: Expectation = .noExpectation
  859. private enum Expectation {
  860. /// We have no expectation of any changes. We'll just ignore any changes.
  861. case noExpectation
  862. /// We expect one change.
  863. case one((Change) -> Void)
  864. /// We expect 'count' changes.
  865. case some(count: Int, recorded: [Change], ([Change]) -> Void)
  866. var count: Int {
  867. switch self {
  868. case .noExpectation:
  869. return 0
  870. case .one:
  871. return 1
  872. case let .some(count, _, _):
  873. return count
  874. }
  875. }
  876. }
  877. func connectivityStateDidChange(from oldState: ConnectivityState,
  878. to newState: ConnectivityState) {
  879. self.serialQueue.async {
  880. switch self.expectation {
  881. case let .one(verify):
  882. // We don't care about future changes.
  883. self.expectation = .noExpectation
  884. // Verify and notify.
  885. verify(Change(from: oldState, to: newState))
  886. self.semaphore.signal()
  887. case .some(let count, var recorded, let verify):
  888. recorded.append(Change(from: oldState, to: newState))
  889. if recorded.count == count {
  890. // We don't care about future changes.
  891. self.expectation = .noExpectation
  892. // Verify and notify.
  893. verify(recorded)
  894. self.semaphore.signal()
  895. } else {
  896. // Still need more responses.
  897. self.expectation = .some(count: count, recorded: recorded, verify)
  898. }
  899. case .noExpectation:
  900. // Ignore any changes.
  901. ()
  902. }
  903. }
  904. }
  905. func expectChanges(_ count: Int, verify: @escaping ([Change]) -> Void) {
  906. self.serialQueue.async {
  907. self.expectation = .some(count: count, recorded: [], verify)
  908. }
  909. }
  910. func expectChange(verify: @escaping (Change) -> Void) {
  911. self.serialQueue.async {
  912. self.expectation = .one(verify)
  913. }
  914. }
  915. func waitForExpectedChanges(
  916. timeout: DispatchTimeInterval,
  917. file: StaticString = #file,
  918. line: UInt = #line
  919. ) {
  920. let result = self.semaphore.wait(timeout: .now() + timeout)
  921. switch result {
  922. case .success:
  923. ()
  924. case .timedOut:
  925. XCTFail(
  926. "Timed out before verifying \(self.expectation.count) change(s)",
  927. file: file, line: line
  928. )
  929. }
  930. }
  931. }
  932. private extension ConnectionBackoff {
  933. static let oneSecondFixed = ConnectionBackoff(
  934. initialBackoff: 1.0,
  935. maximumBackoff: 1.0,
  936. multiplier: 1.0,
  937. jitter: 0.0
  938. )
  939. }
  940. private struct DoomedChannelError: Error {}