ClientConnection.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. /*
  2. * Copyright 2019, 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 Foundation
  17. import NIO
  18. import NIOHTTP2
  19. import NIOSSL
  20. import NIOTLS
  21. import Logging
  22. /// Provides a single, managed connection to a server.
  23. ///
  24. /// The connection to the server is provided by a single channel which will attempt to reconnect
  25. /// to the server if the connection is dropped. This connection is guaranteed to always use the same
  26. /// event loop.
  27. ///
  28. /// The connection is initially setup with a handler to verify that TLS was established
  29. /// successfully (assuming TLS is being used).
  30. ///
  31. /// ┌──────────────────────────┐
  32. /// │ DelegatingErrorHandler │
  33. /// └──────────▲───────────────┘
  34. /// HTTP2Frame│
  35. /// ┌──────────┴───────────────┐
  36. /// │ SettingsObservingHandler │
  37. /// └──────────▲───────────────┘
  38. /// HTTP2Frame│
  39. /// │ ⠇ ⠇ ⠇ ⠇
  40. /// │ ┌┴─▼┐ ┌┴─▼┐
  41. /// │ │ | │ | HTTP/2 streams
  42. /// │ └▲─┬┘ └▲─┬┘
  43. /// │ │ │ │ │ HTTP2Frame
  44. /// ┌─┴────────────────┴─▼───┴─▼┐
  45. /// │ HTTP2StreamMultiplexer |
  46. /// └─▲───────────────────────┬─┘
  47. /// HTTP2Frame│ │HTTP2Frame
  48. /// ┌─┴───────────────────────▼─┐
  49. /// │ NIOHTTP2Handler │
  50. /// └─▲───────────────────────┬─┘
  51. /// ByteBuffer│ │ByteBuffer
  52. /// ┌─┴───────────────────────▼─┐
  53. /// │ TLSVerificationHandler │
  54. /// └─▲───────────────────────┬─┘
  55. /// ByteBuffer│ │ByteBuffer
  56. /// ┌─┴───────────────────────▼─┐
  57. /// │ NIOSSLHandler │
  58. /// └─▲───────────────────────┬─┘
  59. /// ByteBuffer│ │ByteBuffer
  60. /// │ ▼
  61. ///
  62. /// The `TLSVerificationHandler` observes the outcome of the SSL handshake and determines
  63. /// whether a `ClientConnection` should be returned to the user. In either eventuality, the
  64. /// handler removes itself from the pipeline once TLS has been verified. There is also a handler
  65. /// after the multiplexer for observing the initial settings frame, after which it determines that
  66. /// the connection state is `.ready` and removes itself from the channel. Finally there is a
  67. /// delegated error handler which uses the error delegate associated with this connection
  68. /// (see `DelegatingErrorHandler`).
  69. ///
  70. /// See `BaseClientCall` for a description of the pipelines associated with each HTTP/2 stream.
  71. public class ClientConnection {
  72. private let id: String
  73. private let logger: Logger
  74. /// The channel which will handle gRPC calls.
  75. internal var channel: EventLoopFuture<Channel> {
  76. willSet {
  77. self.willSetChannel(to: newValue)
  78. }
  79. didSet {
  80. self.didSetChannel(to: self.channel)
  81. }
  82. }
  83. /// HTTP multiplexer from the `channel` handling gRPC calls.
  84. internal var multiplexer: EventLoopFuture<HTTP2StreamMultiplexer>
  85. /// The configuration for this client.
  86. internal let configuration: Configuration
  87. internal let scheme: String
  88. internal let authority: String
  89. /// A monitor for the connectivity state.
  90. public let connectivity: ConnectivityStateMonitor
  91. /// The `EventLoop` this connection is using.
  92. public var eventLoop: EventLoop {
  93. return self.channel.eventLoop
  94. }
  95. /// Creates a new connection from the given configuration. Prefer using
  96. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  97. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  98. ///
  99. /// - Important: Users should prefer using `ClientConnection.secure(group:)` to build a connection
  100. /// with TLS, or `ClientConnection.insecure(group:)` to build a connection without TLS.
  101. public init(configuration: Configuration) {
  102. self.configuration = configuration
  103. self.scheme = configuration.tls == nil ? "http" : "https"
  104. self.authority = configuration.target.host
  105. let id = String(describing: UUID())
  106. self.id = id
  107. var logger = Logger(subsystem: .clientChannel)
  108. logger[metadataKey: MetadataKey.connectionID] = "\(id)"
  109. self.logger = logger
  110. self.connectivity = ConnectivityStateMonitor(
  111. delegate: configuration.connectivityStateDelegate,
  112. logger: logger
  113. )
  114. let eventLoop = configuration.eventLoopGroup.next()
  115. self.channel = ClientConnection.makeChannel(
  116. configuration: self.configuration,
  117. eventLoop: eventLoop,
  118. connectivity: self.connectivity,
  119. backoffIterator: configuration.connectionBackoff?.makeIterator(),
  120. logger: logger
  121. )
  122. self.multiplexer = self.channel.flatMap {
  123. $0.pipeline.handler(type: HTTP2StreamMultiplexer.self)
  124. }
  125. // `willSet` and `didSet` are *not* called on initialization, call them explicitly now.
  126. self.willSetChannel(to: self.channel)
  127. self.didSetChannel(to: self.channel)
  128. }
  129. /// Closes the connection to the server.
  130. public func close() -> EventLoopFuture<Void> {
  131. if self.connectivity.state == .shutdown {
  132. // We're already shutdown or in the process of shutting down.
  133. return self.channel.flatMap { $0.closeFuture }
  134. } else {
  135. self.connectivity.initiateUserShutdown()
  136. return self.channel.flatMap { $0.close() }
  137. }
  138. }
  139. }
  140. extension ClientConnection {
  141. /// Register a callback on the close future of the given `channel` to replace the channel (if
  142. /// possible) and also replace the `multiplexer` with that from the new channel.
  143. ///
  144. /// - Parameter channel: The channel that will be set.
  145. private func willSetChannel(to channel: EventLoopFuture<Channel>) {
  146. // If we're about to set the channel and the user has initiated a shutdown (i.e. while the new
  147. // channel was being created) then it is no longer needed.
  148. guard !self.connectivity.userHasInitiatedShutdown else {
  149. channel.whenSuccess { channel in
  150. self.logger.debug("user initiated shutdown during connection, closing channel")
  151. channel.close(mode: .all, promise: nil)
  152. }
  153. return
  154. }
  155. // If we get a channel and it closes then create a new one, if necessary.
  156. channel.flatMap { $0.closeFuture }.whenComplete { result in
  157. switch result {
  158. case .success:
  159. self.logger.debug("client connection shutdown successfully")
  160. case .failure(let error):
  161. self.logger.warning(
  162. "client connection shutdown failed",
  163. metadata: [MetadataKey.error: "\(error)"]
  164. )
  165. }
  166. guard self.connectivity.canAttemptReconnect else {
  167. return
  168. }
  169. // Something went wrong, but we'll try to fix it so let's update our state to reflect that.
  170. self.connectivity.state = .transientFailure
  171. self.logger.debug("client connection channel closed, creating a new one")
  172. self.channel = ClientConnection.makeChannel(
  173. configuration: self.configuration,
  174. eventLoop: channel.eventLoop,
  175. connectivity: self.connectivity,
  176. backoffIterator: self.configuration.connectionBackoff?.makeIterator(),
  177. logger: self.logger
  178. )
  179. }
  180. self.multiplexer = channel.flatMap {
  181. $0.pipeline.handler(type: HTTP2StreamMultiplexer.self)
  182. }
  183. }
  184. /// Register a callback on the given `channel` to update the connectivity state.
  185. ///
  186. /// - Parameter channel: The channel that was set.
  187. private func didSetChannel(to channel: EventLoopFuture<Channel>) {
  188. channel.whenFailure { _ in
  189. self.connectivity.state = .shutdown
  190. }
  191. }
  192. }
  193. // Note: documentation is inherited.
  194. extension ClientConnection: GRPCChannel {
  195. public func makeUnaryCall<Request: GRPCPayload, Response: GRPCPayload>(
  196. path: String,
  197. request: Request,
  198. callOptions: CallOptions
  199. ) -> UnaryCall<Request, Response> where Request : GRPCPayload, Response : GRPCPayload {
  200. return UnaryCall(
  201. path: path,
  202. scheme: self.scheme,
  203. authority: self.authority,
  204. callOptions: callOptions,
  205. eventLoop: self.eventLoop,
  206. multiplexer: self.multiplexer,
  207. errorDelegate: self.configuration.errorDelegate,
  208. logger: self.logger,
  209. request: request
  210. )
  211. }
  212. public func makeClientStreamingCall<Request: GRPCPayload, Response: GRPCPayload>(
  213. path: String,
  214. callOptions: CallOptions
  215. ) -> ClientStreamingCall<Request, Response> {
  216. return ClientStreamingCall(
  217. path: path,
  218. scheme: self.scheme,
  219. authority: self.authority,
  220. callOptions: callOptions,
  221. eventLoop: self.eventLoop,
  222. multiplexer: self.multiplexer,
  223. errorDelegate: self.configuration.errorDelegate,
  224. logger: self.logger
  225. )
  226. }
  227. public func makeServerStreamingCall<Request: GRPCPayload, Response: GRPCPayload>(
  228. path: String,
  229. request: Request,
  230. callOptions: CallOptions,
  231. handler: @escaping (Response) -> Void
  232. ) -> ServerStreamingCall<Request, Response> {
  233. return ServerStreamingCall(
  234. path: path,
  235. scheme: self.scheme,
  236. authority: self.authority,
  237. callOptions: callOptions,
  238. eventLoop: self.eventLoop,
  239. multiplexer: self.multiplexer,
  240. errorDelegate: self.configuration.errorDelegate,
  241. logger: self.logger,
  242. request: request,
  243. handler: handler
  244. )
  245. }
  246. public func makeBidirectionalStreamingCall<Request: GRPCPayload, Response: GRPCPayload>(
  247. path: String,
  248. callOptions: CallOptions,
  249. handler: @escaping (Response) -> Void
  250. ) -> BidirectionalStreamingCall<Request, Response> {
  251. return BidirectionalStreamingCall(
  252. path: path,
  253. scheme: self.scheme,
  254. authority: self.authority,
  255. callOptions: callOptions,
  256. eventLoop: self.eventLoop,
  257. multiplexer: self.multiplexer,
  258. errorDelegate: self.configuration.errorDelegate,
  259. logger: self.logger,
  260. handler: handler
  261. )
  262. }
  263. }
  264. extension ClientConnection {
  265. /// Attempts to create a new `Channel` using the given configuration.
  266. ///
  267. /// This involves: creating a `ClientBootstrapProtocol`, connecting to a target and verifying that
  268. /// the TLS handshake was successful (if TLS was configured). We _may_ additiionally set a
  269. /// connection timeout and schedule a retry attempt (should the connection fail) if a
  270. /// `ConnectionBackoffIterator` is provided.
  271. ///
  272. /// - Parameter configuration: The configuration to start the connection with.
  273. /// - Parameter eventLoop: The event loop to use for this connection.
  274. /// - Parameter connectivity: A connectivity state monitor.
  275. /// - Parameter backoffIterator: An `Iterator` for `ConnectionBackoff` providing a sequence of
  276. /// connection timeouts and backoff to use when attempting to create a connection.
  277. private class func makeChannel(
  278. configuration: Configuration,
  279. eventLoop: EventLoop,
  280. connectivity: ConnectivityStateMonitor,
  281. backoffIterator: ConnectionBackoffIterator?,
  282. logger: Logger
  283. ) -> EventLoopFuture<Channel> {
  284. guard connectivity.state == .idle || connectivity.state == .transientFailure else {
  285. return configuration.eventLoopGroup.next().makeFailedFuture(GRPCStatus.processingError)
  286. }
  287. logger.debug("attempting to connect", metadata: ["target": "\(configuration.target)", "event_loop": "\(eventLoop)"])
  288. connectivity.state = .connecting
  289. let timeoutAndBackoff = backoffIterator?.next()
  290. let bootstrap = self.makeBootstrap(
  291. configuration: configuration,
  292. eventLoop: eventLoop,
  293. timeout: timeoutAndBackoff?.timeout,
  294. connectivityMonitor: connectivity,
  295. logger: logger
  296. )
  297. let channel = bootstrap.connect(to: configuration.target).flatMap { channel -> EventLoopFuture<Channel> in
  298. if configuration.tls != nil {
  299. return channel.verifyTLS().map { channel }
  300. } else {
  301. return channel.eventLoop.makeSucceededFuture(channel)
  302. }
  303. }
  304. // If we don't have backoff then we can't retry, just return the `channel` no matter what
  305. // state we are in.
  306. guard let backoff = timeoutAndBackoff?.backoff else {
  307. logger.debug("backoff exhausted, no more connection attempts will be made")
  308. return channel
  309. }
  310. // If our connection attempt was unsuccessful, schedule another attempt in some time.
  311. return channel.flatMapError { error in
  312. logger.notice("connection attempt failed", metadata: [MetadataKey.error: "\(error)"])
  313. // We will try to connect again: the failure is transient.
  314. connectivity.state = .transientFailure
  315. return ClientConnection.scheduleReconnectAttempt(
  316. in: backoff,
  317. on: channel.eventLoop,
  318. configuration: configuration,
  319. connectivity: connectivity,
  320. backoffIterator: backoffIterator,
  321. logger: logger
  322. )
  323. }
  324. }
  325. /// Schedule an attempt to make a channel in `timeout` seconds on the given `eventLoop`.
  326. private class func scheduleReconnectAttempt(
  327. in timeout: TimeInterval,
  328. on eventLoop: EventLoop,
  329. configuration: Configuration,
  330. connectivity: ConnectivityStateMonitor,
  331. backoffIterator: ConnectionBackoffIterator?,
  332. logger: Logger
  333. ) -> EventLoopFuture<Channel> {
  334. logger.debug("scheduling connection attempt", metadata: ["delay_seconds": "\(timeout)"])
  335. // The `futureResult` of the scheduled task is of type
  336. // `EventLoopFuture<EventLoopFuture<Channel>>`, so we need to `flatMap` it to
  337. // remove a level of indirection.
  338. return eventLoop.scheduleTask(in: .seconds(timeInterval: timeout)) {
  339. ClientConnection.makeChannel(
  340. configuration: configuration,
  341. eventLoop: eventLoop,
  342. connectivity: connectivity,
  343. backoffIterator: backoffIterator,
  344. logger: logger
  345. )
  346. }.futureResult.flatMap { channel in
  347. channel
  348. }
  349. }
  350. /// Makes and configures a `ClientBootstrap` using the provided configuration.
  351. ///
  352. /// Enables `SO_REUSEADDR` and `TCP_NODELAY` and configures the `channelInitializer` to use the
  353. /// handlers detailed in the documentation for `ClientConnection`.
  354. ///
  355. /// - Parameter configuration: The configuration to prepare the bootstrap with.
  356. /// - Parameter eventLoop: The `EventLoop` to use for the bootstrap.
  357. /// - Parameter timeout: The connection timeout in seconds.
  358. /// - Parameter connectivityMonitor: The connectivity state monitor for the created channel.
  359. private class func makeBootstrap(
  360. configuration: Configuration,
  361. eventLoop: EventLoop,
  362. timeout: TimeInterval?,
  363. connectivityMonitor: ConnectivityStateMonitor,
  364. logger: Logger
  365. ) -> ClientBootstrapProtocol {
  366. // Provide a server hostname if we're using TLS. Prefer the override.
  367. var serverHostname: String? = configuration.tls.map {
  368. if let hostnameOverride = $0.hostnameOverride {
  369. logger.debug("using hostname override for TLS", metadata: ["server-hostname": "\(hostnameOverride)"])
  370. return hostnameOverride
  371. } else {
  372. let host = configuration.target.host
  373. logger.debug("using host from connection target for TLS", metadata: ["server-hostname": "\(host)"])
  374. return host
  375. }
  376. }
  377. if let hostname = serverHostname, hostname.isIPAddress {
  378. logger.debug("IP address cannot be used for TLS SNI extension. No host used", metadata: ["server-hostname": "\(hostname)"])
  379. serverHostname = nil
  380. }
  381. let bootstrap = PlatformSupport.makeClientBootstrap(group: eventLoop, logger: logger)
  382. // Enable SO_REUSEADDR and TCP_NODELAY.
  383. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  384. .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  385. .channelInitializer { channel in
  386. channel.configureGRPCClient(
  387. tlsConfiguration: configuration.tls?.configuration,
  388. tlsServerHostname: serverHostname,
  389. connectivityMonitor: connectivityMonitor,
  390. errorDelegate: configuration.errorDelegate,
  391. logger: logger
  392. )
  393. }
  394. if let timeout = timeout {
  395. logger.debug("setting connect timeout", metadata: ["timeout_seconds" : "\(timeout)"])
  396. return bootstrap.connectTimeout(.seconds(timeInterval: timeout))
  397. } else {
  398. logger.debug("no connect timeout provided")
  399. return bootstrap
  400. }
  401. }
  402. }
  403. // MARK: - Configuration structures
  404. /// A target to connect to.
  405. public enum ConnectionTarget {
  406. /// The host and port.
  407. case hostAndPort(String, Int)
  408. /// The path of a Unix domain socket.
  409. case unixDomainSocket(String)
  410. /// A NIO socket address.
  411. case socketAddress(SocketAddress)
  412. var host: String {
  413. switch self {
  414. case .hostAndPort(let host, _):
  415. return host
  416. case .socketAddress(.v4(let address)):
  417. return address.host
  418. case .socketAddress(.v6(let address)):
  419. return address.host
  420. case .unixDomainSocket, .socketAddress(.unixDomainSocket):
  421. return "localhost"
  422. }
  423. }
  424. }
  425. extension ClientConnection {
  426. /// The configuration for a connection.
  427. public struct Configuration {
  428. /// The target to connect to.
  429. public var target: ConnectionTarget
  430. /// The event loop group to run the connection on.
  431. public var eventLoopGroup: EventLoopGroup
  432. /// An error delegate which is called when errors are caught. Provided delegates **must not
  433. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  434. /// cycle.
  435. public var errorDelegate: ClientErrorDelegate?
  436. /// A delegate which is called when the connectivity state is changed.
  437. public var connectivityStateDelegate: ConnectivityStateDelegate?
  438. /// TLS configuration for this connection. `nil` if TLS is not desired.
  439. public var tls: TLS?
  440. /// The connection backoff configuration. If no connection retrying is required then this should
  441. /// be `nil`.
  442. public var connectionBackoff: ConnectionBackoff?
  443. /// The HTTP protocol used for this connection.
  444. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  445. return self.tls == nil ? .http : .https
  446. }
  447. /// Create a `Configuration` with some pre-defined defaults. Prefer using
  448. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  449. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  450. ///
  451. /// - Parameter target: The target to connect to.
  452. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  453. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  454. /// on debug builds.
  455. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  456. /// - Parameter tlsConfiguration: TLS configuration, defaulting to `nil`.
  457. /// - Parameter connectionBackoff: The connection backoff configuration to use.
  458. /// - Parameter messageEncoding: Message compression configuration, defaults to no compression.
  459. public init(
  460. target: ConnectionTarget,
  461. eventLoopGroup: EventLoopGroup,
  462. errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate(),
  463. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  464. tls: Configuration.TLS? = nil,
  465. connectionBackoff: ConnectionBackoff? = ConnectionBackoff()
  466. ) {
  467. self.target = target
  468. self.eventLoopGroup = eventLoopGroup
  469. self.errorDelegate = errorDelegate
  470. self.connectivityStateDelegate = connectivityStateDelegate
  471. self.tls = tls
  472. self.connectionBackoff = connectionBackoff
  473. }
  474. }
  475. }
  476. // MARK: - Configuration helpers/extensions
  477. fileprivate extension ClientBootstrapProtocol {
  478. /// Connect to the given connection target.
  479. ///
  480. /// - Parameter target: The target to connect to.
  481. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  482. switch target {
  483. case .hostAndPort(let host, let port):
  484. return self.connect(host: host, port: port)
  485. case .unixDomainSocket(let path):
  486. return self.connect(unixDomainSocketPath: path)
  487. case .socketAddress(let address):
  488. return self.connect(to: address)
  489. }
  490. }
  491. }
  492. extension Channel {
  493. /// Configure the channel with TLS.
  494. ///
  495. /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and
  496. /// the `TLSVerificationHandler` which verifies that a successful handshake was completed.
  497. ///
  498. /// - Parameter configuration: The configuration to configure the channel with.
  499. /// - Parameter serverHostname: The server hostname to use if the hostname should be verified.
  500. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
  501. func configureTLS(
  502. _ configuration: TLSConfiguration,
  503. serverHostname: String?,
  504. errorDelegate: ClientErrorDelegate?,
  505. logger: Logger
  506. ) -> EventLoopFuture<Void> {
  507. do {
  508. let sslClientHandler = try NIOSSLClientHandler(
  509. context: try NIOSSLContext(configuration: configuration),
  510. serverHostname: serverHostname
  511. )
  512. return self.pipeline.addHandlers(sslClientHandler, TLSVerificationHandler(logger: logger))
  513. } catch {
  514. return self.eventLoop.makeFailedFuture(error)
  515. }
  516. }
  517. /// Returns the `verification` future from the `TLSVerificationHandler` in this channels pipeline.
  518. func verifyTLS() -> EventLoopFuture<Void> {
  519. return self.pipeline.handler(type: TLSVerificationHandler.self).flatMap {
  520. $0.verification
  521. }
  522. }
  523. func configureGRPCClient(
  524. tlsConfiguration: TLSConfiguration?,
  525. tlsServerHostname: String?,
  526. connectivityMonitor: ConnectivityStateMonitor,
  527. errorDelegate: ClientErrorDelegate?,
  528. logger: Logger
  529. ) -> EventLoopFuture<Void> {
  530. let tlsConfigured = tlsConfiguration.map {
  531. self.configureTLS($0, serverHostname: tlsServerHostname, errorDelegate: errorDelegate, logger: logger)
  532. }
  533. return (tlsConfigured ?? self.eventLoop.makeSucceededFuture(())).flatMap {
  534. self.configureHTTP2Pipeline(mode: .client)
  535. }.flatMap { _ in
  536. let settingsObserver = InitialSettingsObservingHandler(
  537. connectivityStateMonitor: connectivityMonitor,
  538. logger: logger
  539. )
  540. let errorHandler = DelegatingErrorHandler(
  541. logger: logger,
  542. delegate: errorDelegate
  543. )
  544. return self.pipeline.addHandlers(settingsObserver, errorHandler)
  545. }
  546. }
  547. func configureGRPCClient(
  548. errorDelegate: ClientErrorDelegate?,
  549. logger: Logger
  550. ) -> EventLoopFuture<Void> {
  551. return self.configureHTTP2Pipeline(mode: .client).flatMap { _ in
  552. self.pipeline.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  553. }
  554. }
  555. }
  556. fileprivate extension TimeAmount {
  557. /// Creates a new `TimeAmount` from the given time interval in seconds.
  558. ///
  559. /// - Parameter timeInterval: The amount of time in seconds
  560. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  561. return .nanoseconds(Int64(timeInterval * 1_000_000_000))
  562. }
  563. }
  564. fileprivate extension String {
  565. var isIPAddress: Bool {
  566. // We need some scratch space to let inet_pton write into.
  567. var ipv4Addr = in_addr()
  568. var ipv6Addr = in6_addr()
  569. return self.withCString { ptr in
  570. return inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
  571. inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
  572. }
  573. }
  574. }